carlos / platform Public

Domain registration Plan 1 (buy a domain)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 982ee187b0d4def5c2c67dd924c193c5edb77b1c parent 08bf527
1 file changed, +365 −0
  • docs/superpowers/plans/2026-11-01-domain-registration-1-buy.md +365 −0
diff --git a/docs/superpowers/plans/2026-11-01-domain-registration-1-buy.md b/docs/superpowers/plans/2026-11-01-domain-registration-1-buy.md
new file mode 100644
index 000000000..9bb8c6309
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-01-domain-registration-1-buy.md
@@ -0,0 +1,365 @@
+# Domain registration, Plan 1: buy a domain 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:** A Carloku customer runs `carlos domains buy shop.example --app shop` (or uses "Buy a domain" in the console), pays, and a few minutes later the domain and `www` serve that app over HTTPS from a zone on Carloku-branded nameservers.
+
+**Architecture:** Three provider-neutral seams (`internal/registrar`, `internal/zonehost`, one-off payments added to `internal/billing`) with Openprovider, Route 53 and Stripe adapters. A console-side purchase state machine, persisted in console.db and advanced by a console pass, runs: quote, pay (Stripe Checkout, payment mode, manual capture), create zone, register, capture, attach through the existing `attachDomain` core. Boxes learn about the domain only through the existing claim path.
+
+**Tech Stack:** Go, modernc SQLite (console.db), AWS SDK v2 Route 53 (through `internal/rootaws`), Stripe REST (existing `internal/billingstripe` client), Openprovider REST `/v1`.
+
+**Spec:** `docs/superpowers/specs/2026-11-01-domain-registration-design.md` (rev 3, approved). Read §3 (rulings), §4.1, §5.1-§5.4, §6, §7 before any task.
+
+**Plans in this series:** 1 buy (this plan). 2 keep it working (apex reconverge on edge change, daily registrar reconcile, balance alert, nameserver setup check verb, registrant email verification surfaced per spec §4.4). 3 renewals (auto-renew flag, off-session charges, expiry emails). 4 customer records and transfer out (§5.3a, §4.3, account-deletion refusal).
+
+## Global Constraints
+
+- Core packages (`internal/registrar`, `internal/zonehost`, `internal/domainreg`, `internal/console`) never import the AWS SDK or Openprovider types. Adapters live in `internal/registrar/openprovider` and `internal/zonehost/route53zones`; AWS clients load through `internal/rootaws`. Add both adapter import paths to the existing provider-boundary import test if one exists (`git grep -l "aws-sdk-go-v2" -- '*_test.go' | xargs grep -l "import"` to find it); otherwise Task 1 adds `internal/registrar/boundary_test.go` asserting `internal/registrar`, `internal/zonehost`, `internal/domainreg` import neither `github.com/aws/` nor `.../openprovider`.
+- Every registration Carloku makes has registrar-side auto-renew OFF (spec §5.5).
+- Money is never taken without a registration, and a registration is never made without an authorised payment (spec §2 anti-goals, §5.1). An ambiguous registrar or payment answer is never read as a failure (§5.1 step 6).
+- Buying refuses a domain or `www.<domain>` already claimed by another account or app, before any payment, using `domains.ErrHostUnavailable`'s existing neutral refusal. Buying never evicts a claim (§5.1 step 1).
+- A purchase needs a paid plan: reuse `customDomainRefusal` (`internal/console/plancaps.go:253`).
+- Zero new steady-state S3 requests. The purchase pass reads console.db only. Route 53: one `ListResourceRecordSets` on the steering zone per purchase. Openprovider: check, contact, register, lookup calls per purchase only.
+- No registrar or DNS host name in any customer-facing string. Every new customer-facing string lives in a `*_copy.go` file, drafted in this plan and replaced by the Luna copy pass in Task 11 before merge. Copy rules: no em or en dashes, `cli.`/`door.` keys lower case with no final full stop.
+- Secrets (Openprovider password, bearer token) never appear in logs or `%v`/`%#v` output: `String()`/`GoString()` redact, as `billingstripe.Client` does (`internal/billingstripe/client.go:114-116`). Config errors name the variable, never the value.
+- A deployment missing any one of registrar, zone host, billing or catalog has no buy door and the capability block says so (§7.1). The console still boots when an adapter fails to construct (log and leave nil, the `mailBackends` pattern at `cmd/console/main.go:1287`).
+- Openprovider: build on `https://api.openprovider.eu/v1` (the `/v1beta` paths retire 2027-06-30). Dev and tests use the Openprovider sandbox; base URL is configuration.
+- Branded zones: SOA and NS rewritten to the configured nameserver names; NS TTL 172800, SOA minimum 900 once set (spec §5.2 follows AWS's procedure; the low-TTL bring-up is the operator runbook's job, not per zone).
+- Review budget: Astra per-task review only on Tasks 5, 7 and 8 (billing, purchase engine, doors); one whole-branch Astra review before merge. At most three rounds; stop at the first round with no P1 (AGENTS.md stopping rules).
+- Local verification: run only the touched packages' tests with `-run` (AGENTS.md, "Targeted local tests"); CI runs the full suite.
+
+## Review Focus
+
+1. **The customer abandons or never finishes Checkout.** Expected: the purchase expires after the Checkout session expires (Stripe default 24 h; set `expires_at` to 1 h), no zone exists, nothing registered, state `expired`. Test in Task 7: `TestPurchaseCheckoutExpiredLeavesNothing`.
+2. **Someone else registers the name between check and pay.** Expected: Register returns `registrar.ErrUnavailable`, the authorisation is cancelled, the zone deleted, state `failed` with reason `taken`, and the customer sees "that name was registered by someone else" copy. Test in Task 7: `TestPurchaseNameTakenAfterPaymentCancelsAndCleansUp`.
+3. **The console restarts mid-purchase.** Expected: the pass resumes from the persisted state without a second registration or second capture (idempotency keys derive from the purchase ID). Test in Task 7: `TestPurchaseResumesAfterRestartWithoutDoubleRegister`.
+4. **Mixed-case or trailing-dot input, IDNs, and subdomains** (`Shop.Example.`, `bücher.example`, `shop.example.co.uk` vs `www.shop.example`). Expected: names are lowercased, trailing dot stripped, IDNs converted to A-labels with `idna.Lookup`, and anything that is not exactly a registrable domain (eTLD+1) is refused at check. Test in Task 4: `TestQuoteNormalizesAndRefusesNonRegistrable`.
+5. **Two buys of the same name at once** (double click, two terminals, two accounts). Expected: at most one purchase per domain is non-terminal (unique partial index); the second request gets the neutral "not available" refusal before any payment. Test in Task 6: `TestOnlyOneLivePurchasePerDomain`, and Task 8: `TestBuyDoorSecondConcurrentBuyRefused`.
+
+---
+
+### Task 1: Registrar seam and fake
+
+**Files:**
+- Create: `internal/registrar/registrar.go`
+- Create: `internal/registrar/registrartest/fake.go`
+- Create: `internal/registrar/registrar_test.go`
+- Create (if no shared boundary test exists): `internal/registrar/boundary_test.go`
+
+**Interfaces:**
+- Produces:
+ ```go
+ package registrar
+ type Money struct { Currency string; Minor int64 } // ISO 4217 lower case, minor units
+ type Availability struct { Domain string; Available, Premium bool; Cost Money }
+ type Contact struct { FirstName, LastName, Company, Email, Phone, Street, City, State, PostalCode, Country string } // Country ISO 3166-1 alpha-2
+ type Registration struct { Domain string; Years int; Nameservers []string; OwnerHandle string; Key string } // Key: idempotency, the purchase ID
+ type Registered struct { Domain, RegistrarID string; Expires time.Time; Nameservers []string }
+ type Registrar interface {
+ Check(ctx context.Context, domain string) (Availability, error)
+ EnsureContact(ctx context.Context, existingHandle string, c Contact) (handle string, err error)
+ Register(ctx context.Context, r Registration) (Registered, error)
+ Lookup(ctx context.Context, domain string) (Registered, bool, error) // false: not in our account
+ Balance(ctx context.Context) (Money, error)
+ }
+ var ErrUnavailable = errors.New("registrar: domain not available")
+ var ErrRefused = errors.New("registrar: refused") // definite, nothing registered
+ var ErrIndeterminate = errors.New("registrar: outcome unknown") // timeout, 5xx after send
+ func (c Contact) Validate() error // required: FirstName, LastName, Email, Phone, Street, City, PostalCode, Country
+ ```
+ `registrartest.New() *Fake` implements `Registrar`; fields `Available map[string]Availability`, `Domains map[string]Registered`, `BalanceMoney Money`, `RegisterErr error` (one-shot), `Calls []string` ("check:x", "register:x", ...). `Register` with a `Key` already seen returns the stored `Registered` (idempotent).
+
+- [ ] **Step 1: Write failing tests** in `registrar_test.go`: `TestContactValidateRequiresFields` (empty Contact returns an error naming `FirstName`; a full one returns nil; Country `"gb"` and `"GBR"` refused, `"GB"` accepted) and `TestFakeRegisterIsIdempotentByKey` (two `Register` calls with the same Key return equal `Registered` and `Calls` holds one `"register:shop.example"`).
+- [ ] **Step 2: Run** `go test ./internal/registrar/... -run 'TestContact|TestFake'`; expect FAIL (undefined).
+- [ ] **Step 3: Implement** the types, errors, `Validate`, and the fake. Boundary test if needed (see Global Constraints).
+- [ ] **Step 4: Run** the same command; expect PASS.
+- [ ] **Step 5: Commit** `registrar: provider-neutral registrar seam and fake`.
+
+### Task 2: Openprovider adapter
+
+**Files:**
+- Create: `internal/registrar/openprovider/client.go`
+- Create: `internal/registrar/openprovider/client_test.go`
+- Create: `internal/registrar/openprovider/testdata/*.json` (response bodies copied from the Openprovider `/v1` reference, one per call)
+
+**Interfaces:**
+- Consumes: Task 1 types.
+- Produces: `type Config struct { BaseURL, Username, Password string; HTTP *http.Client }`; `func New(cfg Config) (*Client, error)` (error names the empty field); `*Client` implements `registrar.Registrar`; `func (c *Client) String() string` returns `"openprovider(" + BaseURL + ")"`, `GoString` the same.
+
+Endpoints (`/v1`, bearer token from `POST /auth/login`, re-login once on 401): `POST /domains/check` (with price), `POST /customers` (create handle) / `PUT /customers/{handle}` (update), `POST /domains` (register: `autorenew: "off"`, name servers from the request, owner/admin/tech/billing handles all `OwnerHandle`, period `Years`), `GET /domains?full_name=` (Lookup), reseller balance endpoint from the reference. Confirm exact field names against developer.openprovider.com before writing testdata.
+
+Error mapping: transport error or 5xx on `POST /domains` → `ErrIndeterminate`; a documented "domain not available / already registered" code → `ErrUnavailable`; any other 4xx → `ErrRefused` wrapping the provider message. Premium names: `Availability.Premium = true`. Registration requests WHOIS privacy wherever the TLD allows it (spec §4.4); assert it in `TestRegisterSendsAutorenewOffAndNameservers`.
+
+- [ ] **Step 1: Write failing tests** against an `httptest.Server` serving testdata: `TestCheckParsesAvailabilityAndCost` (`shop.example` available, `Cost{Currency:"eur", Minor: 899}` from the fixture), `TestRegisterSendsAutorenewOffAndNameservers` (decode the request body: autorenew `"off"`, the four names in order, all four handles equal), `TestRegisterTimeoutIsIndeterminate` (server sleeps past a 50 ms client timeout → `errors.Is(err, registrar.ErrIndeterminate)`), `TestRegisterTakenIsUnavailable`, `TestReloginOnce401` (first call 401, login counted twice, call succeeds; a second 401 returns an error, no loop), `TestStringRedactsSecrets` (`fmt.Sprintf("%v %#v", c, c)` contains neither password nor token).
+- [ ] **Step 2: Run** `go test ./internal/registrar/openprovider/ -run .`; expect FAIL.
+- [ ] **Step 3: Implement** the client.
+- [ ] **Step 4: Run**; expect PASS.
+- [ ] **Step 5: Commit** `registrar/openprovider: /v1 adapter (check, contact, register, lookup, balance)`.
+
+### Task 3: Zone host seam, fake and Route 53 adapter
+
+**Files:**
+- Create: `internal/zonehost/zonehost.go`, `internal/zonehost/zonehosttest/fake.go`, `internal/zonehost/zonehost_test.go`
+- Create: `internal/zonehost/route53zones/route53.go`, `internal/zonehost/route53zones/route53_test.go`
+
+**Interfaces:**
+- Produces:
+ ```go
+ package zonehost
+ type ApexTarget struct { IP, Region, SetID, HealthCheckID string } // Region empty: plain A record value
+ type TXT struct { Name, Value string }
+ type ManagedSet struct { Apex []ApexTarget; WWW bool; TXT []TXT }
+ type Zone struct { ID, Domain string }
+ type Host interface {
+ CreateZone(ctx context.Context, domain, key string) (Zone, error) // idempotent on key (Route 53 CallerReference)
+ DeleteZone(ctx context.Context, z Zone) error // deletes managed records first; not-found is success
+ SetManaged(ctx context.Context, z Zone, m ManagedSet) error // upsert to exactly m (removes managed records not in m)
+ Nameservers() []string // the branded names, trailing-dot free
+ }
+ type ApexSource interface { ApexTargets(ctx context.Context) ([]ApexTarget, error) }
+ func StaticApex(ips []string) ApexSource // plain A values, no region
+ func (m ManagedSet) Validate() error // ≥1 apex target; all latency or all plain; no duplicate SetID
+ ```
+ `zonehosttest.New(ns ...string) *Fake` (zones by domain, `Managed map[string]ManagedSet`, `Calls []string`, one-shot `CreateErr`, `SetErr`).
+ `route53zones.New(ctx, Config) (*Host, error)`, `Config{ DelegationSetID string; Nameservers []string; SteeringZoneID, SteeringHost string }`; `*Host` implements `zonehost.Host`; `(*Host).Steered() zonehost.ApexSource` reads `SteeringHost`'s A record sets from `SteeringZoneID` with `ListResourceRecordSets` and returns one `ApexTarget` per set (IP, `Region`, `SetIdentifier`, `HealthCheckId`); error when `SteeringZoneID` is empty.
+
+Route 53 writes: `CreateHostedZone` with `DelegationSetId` and `CallerReference = key`; then one `ChangeResourceRecordSets` batch: UPSERT SOA (primary = `Nameservers()[0]`, rest of the SOA kept), UPSERT NS (the four names, TTL 172800), apex A records (latency: `SetIdentifier`, `Region`, `HealthCheckId`, TTL 60; plain: one record set, TTL 300), `www` as an ALIAS A to the apex in the same zone (`EvaluateTargetHealth: true`), TXT records TTL 300. Records are tagged as managed by name+type, so `SetManaged` deletes managed apex sets whose `SetIdentifier` is no longer wanted.
+
+- [ ] **Step 1: Write failing tests:** `TestManagedSetValidate` (empty apex refused; mixed latency+plain refused; duplicate SetID refused); `TestFakeSetManagedReplaces`; in `route53_test.go` with a fake `route53API` interface (the `internal/steering/route53.go:81` pattern): `TestCreateZoneUsesDelegationSetAndRewritesSOANS` (asserts `DelegationSetId`, SOA primary `ns1.<branded>.`, NS values the four names), `TestSetManagedLatencyCopiesHealthChecks` (two targets → two A sets with their `HealthCheckId`, `Region`, `SetIdentifier`), `TestSetManagedDropsStaleSet` (a set ID not in the new m is DELETEd), `TestWWWIsSameZoneAlias`, `TestSteeredReadsSteeringHost` (record sets for `edge.apps.example.` returned as targets; other names ignored).
+- [ ] **Step 2: Run** `go test ./internal/zonehost/... -run .`; expect FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run**; expect PASS.
+- [ ] **Step 5: Commit** `zonehost: zone host seam, fake, Route 53 adapter on a branded delegation set`.
+
+### Task 4: TLD catalog and quoting
+
+**Files:**
+- Create: `internal/domainreg/catalog.go`, `internal/domainreg/catalog_test.go`, `internal/domainreg/testdata/catalog.json`
+
+**Interfaces:**
+- Consumes: `registrar.Money`.
+- Produces:
+ ```go
+ package domainreg
+ type TLD struct {
+ Register map[string]int64 `json:"register"` // currency -> minor units, one year
+ Renew map[string]int64 `json:"renew"`
+ MaxCost registrar.Money `json:"max_cost"` // refuse when the registrar's cost exceeds this
+ }
+ type Catalog struct { Version string; TLDs map[string]TLD; DailyCap int `json:"daily_cap"` }
+ func LoadCatalog(path string) (*Catalog, error) // DisallowUnknownFields, the plans.LoadCatalog pattern
+ func Normalize(name string) (string, error) // lower, strip trailing dot, idna.Lookup.ToASCII, must equal publicsuffix eTLD+1
+ type Quote struct { Domain, TLD, Currency string; Price int64; Cost registrar.Money } // Cost: the registrar's, for the balance check
+ func (c *Catalog) Quote(domain, currency string, a registrar.Availability) (Quote, error)
+ var ErrNotRegistrable, ErrTLDNotOffered, ErrPremium, ErrNotAvailable, ErrCostAboveCeiling error
+ ```
+ Plan decision (deviation from spec §6.2's wording, same intent): the margin guard is a per-TLD `max_cost` in the registrar's currency, so no exchange rate is needed. Note it in the spec's §6.2 as an implementation note in this task's commit.
+
+- [ ] **Step 1: Write failing tests:** `TestQuoteNormalizesAndRefusesNonRegistrable` (`"Shop.Example."` → `shop.example`; `"bücher.example"` → `xn--bcher-kva.example`; `"www.shop.example"`, `"example"`, `"co.uk"` → `ErrNotRegistrable`; `"shop.example.co.uk"` accepted), `TestQuoteRefusals` (unknown TLD → `ErrTLDNotOffered`; `Premium` → `ErrPremium`; `!Available` → `ErrNotAvailable`; cost 1201 with max 1200 same currency → `ErrCostAboveCeiling`; cost in a different currency than `MaxCost` → `ErrCostAboveCeiling`, never a silent pass), `TestQuotePrice` (`com` in `gbp` returns the catalog's `register.gbp`), `TestLoadCatalogRejectsUnknownFields`.
+- [ ] **Step 2: Run** `go test ./internal/domainreg/ -run .`; expect FAIL.
+- [ ] **Step 3: Implement** (`golang.org/x/net/publicsuffix` and `golang.org/x/net/idna` are already dependencies; check `go.mod`).
+- [ ] **Step 4: Run**; expect PASS.
+- [ ] **Step 5: Commit** `domainreg: TLD catalog, name normalization, quoting with a cost ceiling`.
+
+### Task 5: One-off payments in the billing seam (risky: per-task review)
+
+**Files:**
+- Modify: `internal/billing/billing.go` (interface at `:242`)
+- Modify: `internal/billing/billingtest/fake.go`
+- Create: `internal/billingstripe/payment.go`, `internal/billingstripe/payment_test.go`
+- Modify: `internal/billingstripe/prepared.go` (Send dispatch)
+
+**Interfaces:**
+- Produces, added to `billing`:
+ ```go
+ type PaymentCheckoutRequest struct {
+ AccountSqid, Customer, Currency string
+ Amount int64 // minor units, before tax
+ Description string // the line item name, e.g. the domain
+ Reference string // our purchase ID, into metadata
+ SuccessURL, CancelURL string
+ ExpiresAt time.Time
+ Key string
+ }
+ type PaymentInfo struct { SessionID, URL, PaymentIntent, Status string; Authorised bool; Amount, AmountTotal int64; Currency string }
+ // Provider gains:
+ PreparePaymentCheckout(req PaymentCheckoutRequest) (Prepared, error)
+ PaymentCheckout(ctx context.Context, sessionID string) (PaymentInfo, error)
+ PrepareCapture(paymentIntent, key string) (Prepared, error)
+ PrepareCancelPayment(paymentIntent, key string) (Prepared, error)
+ // Result gains: Payment *PaymentInfo
+ ```
+ Stripe: Checkout Session `mode=payment`, `payment_intent_data[capture_method]=manual`, `line_items[0][price_data]` with `currency`, `unit_amount`, `product_data[name]`, `tax_behavior=exclusive`, `automatic_tax[enabled]=true`, `customer`, `expires_at`, `metadata[account]`, `metadata[purchase]`. `Authorised` is true when the session is `complete` and its PaymentIntent status is `requires_capture`. Capture: `POST /v1/payment_intents/{id}/capture`. Cancel: `POST /v1/payment_intents/{id}/cancel`. Idempotency keys from `Key`; outcomes classified through the existing `classify` (`prepared.go:258`), so a lost answer is `billing.ErrNoResponse`/`ErrIndeterminate`, never success or failure.
+
+- [ ] **Step 1: Write failing tests** (Stripe client tests use the existing httptest Stripe fake in `billingstripe`; find it with `git grep -n "httptest" internal/billingstripe/*_test.go`): `TestPaymentCheckoutForm` (decoded form has every field above; `mode=payment`; `capture_method=manual`), `TestPaymentCheckoutAuthorised` (session complete + PI `requires_capture` → `Authorised`; PI `requires_payment_method` → false), `TestCaptureAndCancelUseIdempotencyKey`, `TestCaptureLostAnswerIsIndeterminate` (connection closed after request read). Fake: `TestFakePaymentLifecycle` in `billingtest` (complete, capture, cancel; capture after cancel errors).
+- [ ] **Step 2: Run** `go test ./internal/billing/... ./internal/billingstripe/ -run 'Payment|Capture|Cancel'`; expect FAIL.
+- [ ] **Step 3: Implement.** Every existing `billing.Provider` implementation must compile; `git grep -n "billing.Provider" -- '*.go'` lists them.
+- [ ] **Step 4: Run**; expect PASS. Also `go vet ./internal/billing/... ./internal/billingstripe/ ./internal/console/`.
+- [ ] **Step 5: Commit** `billing: one-off authorise-and-capture payments (Stripe Checkout payment mode)`.
+- [ ] **Step 6: Astra task review** (billing). Brief from `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`.
+
+### Task 6: Console store for contacts, purchases and registrations
+
+**Files:**
+- Create: `internal/console/domainstore.go`, `internal/console/domainstore_test.go`
+- Modify: `internal/console/store.go` (append `s.migrateDomains()` to the migrator chain at `:624-678`)
+
+**Interfaces:**
+- Produces:
+ ```go
+ type PurchaseState string
+ const (
+ PurchaseAwaitingPayment PurchaseState = "awaiting_payment"
+ PurchaseAuthorised = "authorised"
+ PurchaseZoneReady = "zone_ready"
+ PurchaseRegistering = "registering" // Register sent; outcome may be unknown
+ PurchaseRegistered = "registered"
+ PurchaseCaptured = "captured"
+ PurchaseDone = "done" // attached
+ PurchaseFailed = "failed" // terminal; Reason says why
+ PurchaseExpired = "expired" // terminal; Checkout never paid
+ PurchaseUnpaid = "unpaid" // terminal; registered but capture failed (spec §5.1 step 7)
+ )
+ type DomainPurchase struct {
+ ID string; AccountID int64; Domain, App, Currency string; Amount int64
+ State PurchaseState; Reason string
+ CheckoutSession, PaymentIntent, ZoneID, RegistrarID string
+ Attempts int; CheckoutExpires, CreatedAt, UpdatedAt time.Time
+ }
+ func (s *Store) CreateDomainPurchase(p DomainPurchase) error // ErrDomainPurchaseLive when a non-terminal purchase for Domain exists
+ func (s *Store) DomainPurchase(id string) (*DomainPurchase, error)
+ func (s *Store) AdvanceDomainPurchase(id string, from, to PurchaseState, set func(*DomainPurchase)) error // compare-and-set on state; ErrPurchaseStateMoved
+ func (s *Store) LiveDomainPurchases() ([]DomainPurchase, error) // non-terminal
+ func (s *Store) PurchasesToday(accountID int64, now time.Time) (int, error) // UTC day
+ func (s *Store) DomainContact(accountID int64) (registrar.Contact, string /*handle*/, error)
+ func (s *Store) SetDomainContact(accountID int64, c registrar.Contact, handle string) error
+ func (s *Store) AddDomainRegistration(r DomainRegistration) error
+ type DomainRegistration struct { Domain string; AccountID int64; RegistrarID, ZoneID string; Expires time.Time; AutoRenew bool; CreatedAt time.Time }
+ ```
+ Tables: `domain_contacts(account_id PK, contact TEXT json, handle TEXT, updated_at INTEGER)`; `domain_purchases(id TEXT PK, ... , state TEXT, ...)` with `CREATE UNIQUE INDEX ... ON domain_purchases(domain) WHERE state NOT IN ('done','failed','expired','unpaid')`; `domain_registrations(domain TEXT PK, account_id, registrar_id, zone_id, expires_at INTEGER, auto_renew INTEGER NOT NULL DEFAULT 1, created_at INTEGER)`. Purchase IDs: `"dp_" + 16 random hex`.
+
+- [ ] **Step 1: Write failing tests:** `TestOnlyOneLivePurchasePerDomain` (second create → `ErrDomainPurchaseLive`; after the first reaches `failed`, a new one succeeds), `TestAdvanceIsCompareAndSet` (advance from a stale `from` → `ErrPurchaseStateMoved`, row unchanged), `TestPurchasesTodayCountsUTCDay`, `TestDomainContactRoundTrip`, `TestMigrateDomainsIdempotent` (open twice).
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'Purchase|DomainContact|MigrateDomains'`; expect FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run**; expect PASS.
+- [ ] **Step 5: Commit** `console: domain purchase, registration and contact tables`.
+
+### Task 7: The purchase engine (risky: per-task review)
+
+**Files:**
+- Create: `internal/console/domainbuy.go`, `internal/console/domainbuy_test.go`
+- Modify: `internal/console/server.go` (Config fields and the pass start), `internal/console/billingwebhook.go:60` (route payment-mode `EventCheckout` to `s.nudgePurchase`)
+
+**Interfaces:**
+- Consumes: Tasks 1, 3, 4, 5, 6; `attachDomain` (`domainattach.go:107`); `s.domainChallenge(host, account) dnsRecord` (`domainpolicy.go:258`); `customDomainRefusal`; `s.store.BillingAccount(acct.ID)` for currency and Stripe customer; `heldElsewhere` / claim reads used by the attach door.
+- Produces:
+ ```go
+ // Config gains (nil/zero: no buy door)
+ Registrar registrar.Registrar
+ ZoneHost zonehost.Host
+ DomainApex zonehost.ApexSource // nil: zonehost.StaticApex(dnsTargets IPs)
+ DomainCatalog *domainreg.Catalog
+ func (s *Server) domainBuyReady() bool
+ func (s *Server) quoteDomain(ctx context.Context, acct *Account, name string) (domainreg.Quote, *doorRefusal)
+ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, name string, c registrar.Contact, principal string) (*DomainPurchase, string /*checkout URL*/, *doorRefusal)
+ func (s *Server) advancePurchase(ctx context.Context, id string) error // one step per call; safe to call concurrently (CAS)
+ func (s *Server) nudgePurchase(id string) // non-blocking wake of the pass
+ func (s *Server) StartDomainPurchasePass(ctx context.Context) // every 15 s and on nudge; LiveDomainPurchases only
+ ```
+
+Step order inside `advancePurchase` (spec §5.1), each step its own CAS transition:
+1. `awaiting_payment`: read `PaymentCheckout`. Authorised → `authorised`. Expired, or past `CheckoutExpires` → `expired`. Open → no change.
+2. `authorised`: `ZoneHost.CreateZone(domain, key=purchaseID)`, then `SetManaged` with apex from `DomainApex`, `WWW: true`, TXT = `domainChallenge` for apex and `www` when `s.cfg.DomainProof` (so the attach is proven). → `zone_ready`.
+3. `zone_ready`: move to `registering` FIRST, then `Register(Key: purchaseID, Nameservers: ZoneHost.Nameservers(), Years: 1, OwnerHandle)`.
+4. `registering`: success → `registered` (store `RegistrarID`, add `DomainRegistration` with `AutoRenew: true`). `ErrUnavailable`/`ErrRefused` → cancel payment, delete zone, `failed` (reason `taken`/`refused`). `ErrIndeterminate` or a crash in this state → next call does `Lookup(domain)`: found in our account → treat as success; not found and the registrar has had 10 minutes → retry `Register` with the same Key (the fake and the adapter are idempotent by Key); never cancel the payment while the outcome is unknown.
+5. `registered`: `Send(PrepareCapture(pi, key=purchaseID+":capture"))`. Success → `captured`. Definite failure → `unpaid` (alert operator via the existing alert/email path, email owner). Indeterminate → stay, retry next pass.
+6. `captured`: `attachDomain` for `domain` and `www.domain` naming the app (principal from the purchase). Success (including pending, which the proof TXT should make rare) → `done`. A refusal → stay `captured`, `Reason` set, retry next pass; after 10 attempts alert the operator. The domain is the customer's either way.
+
+Refusals in `startDomainPurchase`, all before Checkout is created: `domainBuyReady` false → 404 (door absent); `customDomainRefusal`; app must exist; contact `Validate`; `PurchasesToday >= DailyCap`; claims on domain or `www.` held by another account/app → `domains.ErrHostUnavailable`'s refusal; `quoteDomain` refusals; `Registrar.Balance` < the quote's registrar cost → operator alert + refusal "buying domains is unavailable right now"; `CreateDomainPurchase` → `ErrDomainPurchaseLive` maps to the same neutral refusal as a held claim. Then `EnsureContact` (store the handle), then `PreparePaymentCheckout` with `ExpiresAt` now+1h, currency = the account's billing currency, amount = quote price.
+
+- [ ] **Step 1: Write failing tests** with `registrartest`, `zonehosttest`, `billingtest` fakes on a `newConsoleFixtureWith` server: `TestPurchaseHappyPathAttachesApexAndWWW` (after payment authorised, repeated `advancePurchase` reaches `done`; fake registrar saw nameservers = branded set and one register; payment captured once; claims exist for both hosts naming the app; a `DomainRegistration` row with `AutoRenew` true), `TestPurchaseCheckoutExpiredLeavesNothing`, `TestPurchaseNameTakenAfterPaymentCancelsAndCleansUp`, `TestPurchaseIndeterminateRegisterNeverCancels` (RegisterErr = ErrIndeterminate; payment not cancelled; Lookup finds it → `registered`), `TestPurchaseResumesAfterRestartWithoutDoubleRegister` (new Server over the same store mid-`registering`; one register, one capture), `TestPurchaseCaptureFailsMarksUnpaidKeepsDomain`, `TestStartRefusesClaimHeldElsewhereBeforePayment` (no Checkout created), `TestStartRefusesFreePlan`, `TestStartRefusesOverDailyCap`, `TestStartRefusesLowRegistrarBalance`, `TestApexFromSteeringSource` (latency targets passed through to `SetManaged`) and `TestApexStaticWithoutSteering`.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestPurchase|TestStart|TestApex'`; expect FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run**; expect PASS.
+- [ ] **Step 5: Commit** `console: domain purchase engine (pay, zone, register, capture, attach)`.
+- [ ] **Step 6: Astra task review** (billing + production storage + termination of money flows).
+
+### Task 8: Console doors and capability (risky: per-task review)
+
+**Files:**
+- Create: `internal/console/apidomainbuy.go`, `internal/console/apidomainbuy_test.go`, `internal/console/domainbuy_copy.go`
+- Create: `internal/console/appdomainbuy.go` (browser), template additions beside the Domains tab template (find it from `appdomains.go:50`'s render call)
+- Modify: `internal/console/authcli.go` (routes near `:912`), `internal/console/domainstate.go:270` (`deploymentCapability.Features` gains `"buy"` when `domainBuyReady()`)
+
+**Interfaces:**
+- Consumes: Task 7.
+- Produces, CLI API (person-only via `s.apiPerson`, owner role required, `domainsGate` rate ceiling):
+ - `POST /api/cli/accounts/{account}/domains/check` body `{"name"}` → `{"domain","price","currency","available":true}` or a refusal (`writeDoorRefusalJSON`).
+ - `POST /api/cli/accounts/{account}/domains/purchases` body `{"name","app","contact":{...}?}` → `{"id","checkout_url","state"}`. Contact optional when stored; missing and not stored → 422 `{"error", "code":"contact"}`.
+ - `GET /api/cli/accounts/{account}/domains/purchases/{id}` → `{"id","domain","app","state","reason","domain_state"}` where `domain_state` is the existing managed-domains `state` for the apex once attached. Calls `nudgePurchase` so a waiting CLI advances promptly. Another account's ID → 404, byte-identical to unknown.
+ - Browser: "Buy a domain" on the app's Domains tab (owner only, CSRF): name → quote → contact form (prefilled) → redirect to Checkout; Checkout `success_url` returns to a purchase page that polls the GET door and shows the steps.
+
+- [ ] **Step 1: Write failing tests:** `TestBuyDoorAbsentWhenNotConfigured` (404 and capability lacks `"buy"`), `TestBuyDoorOwnerOnly` (member 404 or 403 as the billing doors do; service token refused), `TestBuyDoorSecondConcurrentBuyRefused`, `TestPurchaseStatusOtherAccount404`, `TestCheckDoorRefusalsAreNeutral` (held claim and live purchase give identical bodies), `TestBrowserBuyRedirectsToCheckout`.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'BuyDoor|PurchaseStatus|CheckDoor|BrowserBuy'`; expect FAIL.
+- [ ] **Step 3: Implement**; all strings from `domainbuy_copy.go`, marked "Plan 1 drafts, replaced by the Luna pass (Task 11)".
+- [ ] **Step 4: Run**; expect PASS.
+- [ ] **Step 5: Commit** `console: domain check and buy doors, purchase status, browser flow`.
+- [ ] **Step 6: Astra task review** (security gate: authorization, neutral refusals).
+
+### Task 9: `carlos domains check` and `carlos domains buy`
+
+**Files:**
+- Modify: `domains_cli.go` (`runDomains` switch at `:95`, `domainsUsage` at `:22`)
+- Create: `domains_buy_cli.go`, `domains_buy_cli_test.go`, `domains_buy_copy.go`
+- Modify: `apimode.go` (session methods next to `postDomainAttachFull` at `:4626`)
+
+**Interfaces:**
+- Consumes: Task 8's doors.
+- Produces: `(s *apiSession) postDomainCheck(ctx, acct apiAcct, name string) (domainQuoteResp, error)`, `postDomainPurchase(ctx, acct, name, app string, contact *registrar.Contact) (domainPurchaseResp, error)`, `getDomainPurchase(ctx, acct, id string) (domainPurchaseResp, error)`.
+ - `carlos domains check <name> [--account] [--console]`: prints the name, availability and price with currency.
+ - `carlos domains buy <name> --app <a> [--contact-file contact.json] [--yes] [--no-wait]`: shows the price and asks to confirm unless `--yes`; a `code:"contact"` answer prompts for the contact fields interactively when stdin is a terminal, else exits naming `--contact-file`; prints the Checkout link; then (unless `--no-wait`) polls the status door every 3 s, printing each new state once, and exits 0 at `done` with `domain_state`, non-zero at `failed`/`expired`/`unpaid` with the reason. It waits on `domain_state` reaching `live` for up to 10 minutes after `done`, then says it will finish in the background.
+
+- [ ] **Step 1: Write failing tests** (httptest + `newTestSession`, the `domains_cli_test.go` pattern): `TestDomainsCheckPrintsPrice`, `TestDomainsBuyPrintsCheckoutAndWaitsToLive` (scripted states awaiting_payment → authorised → registered → captured → done, domain_state issuing-cert → live; output lists each state once), `TestDomainsBuyFailedExitsNonZeroWithReason`, `TestDomainsBuyContactMissingNonTTYNamesFlag`.
+- [ ] **Step 2: Run** `go test . -run 'TestDomainsCheck|TestDomainsBuy'`; expect FAIL.
+- [ ] **Step 3: Implement**; strings from `domains_buy_copy.go` (drafts).
+- [ ] **Step 4: Run**; expect PASS.
+- [ ] **Step 5: Commit** `cli: carlos domains check and buy`.
+
+### Task 10: Console wiring, configuration and operator runbook
+
+**Files:**
+- Modify: `cmd/console/main.go` (the `console.Config{}` literal near `:510-565`; a `domainBackends(...)` constructor beside `mailBackends` at `:1287`)
+- Create: `cmd/console/domains.go`, `cmd/console/domains_test.go`
+- Create: `docs/site/domains-buying.md` (operator runbook: Openprovider membership and sandbox, prepaid balance, nameserver domain, reusable delegation set, A/AAAA for the four names, glue, low-TTL bring-up then restore, ECS note for public resolvers, env vars, how to verify with `dig`)
+
+**Interfaces:**
+- Produces env vars (all required together; any missing → buy door off, one log line naming what is missing):
+ `CARLOS_OPENPROVIDER_URL`, `CARLOS_OPENPROVIDER_USERNAME`, `CARLOS_OPENPROVIDER_PASSWORD` (EnvironmentFile only), `CARLOS_DOMAIN_DELEGATION_SET_ID`, `CARLOS_DOMAIN_NAMESERVERS` (four comma-separated names), `CARLOS_DOMAIN_CATALOG` (path; `domainreg.LoadCatalog`, a load error is fatal like `CARLOS_PLAN_CATALOG`).
+ `func domainBackends(getenv func(string) string, newRegistrar func(openprovider.Config) (registrar.Registrar, error), newZones func(context.Context, route53zones.Config) (*route53zones.Host, error)) (registrar.Registrar, zonehost.Host, zonehost.ApexSource, *domainreg.Catalog, error)`; apex source is `(*Host).Steered()` when `steeringHost()` is set, else nil (Task 7 falls back to static).
+
+- [ ] **Step 1: Write failing tests:** `TestDomainBackendsAllOrNothing` (each var missing in turn → nil backends, message names the variable, never a value), `TestDomainBackendsSteeredWhenSteeringOn`, `TestDomainBackendsErrorNeverLeaksPassword`.
+- [ ] **Step 2: Run** `go test ./cmd/console/ -run DomainBackends`; expect FAIL.
+- [ ] **Step 3: Implement**, plus the runbook.
+- [ ] **Step 4: Run**; expect PASS. `go build ./...` and the cross-compile check CI runs (`GOOS=darwin go build ./...`, `GOOS=windows go build ./...`).
+- [ ] **Step 5: Commit** `console: wire domain registration backends; operator runbook`.
+
+### Task 11: Copy pass
+
+**Files:**
+- Create: `docs/superpowers/specs/LUNA-COPY-BRIEF-DOMAINS-1.md` (house rules, the facts that must stay true: customer is the registrant, no provider names, the 1 to 5 minute expectation, unpaid/expired/taken meanings), then `LUNA-COPY-RESULT-DOMAINS-1.md` from the pass
+- Modify: `internal/console/domainbuy_copy.go`, `domains_buy_copy.go`; Create: `approved_domains_buy_copy_test.go` pinning approved strings
+
+- [ ] **Step 1:** Write the brief listing every string key with where it appears.
+- [ ] **Step 2:** Run the Luna pass (Paul's delegated copy review, see memory "large copy decks delegated"); apply the result table verbatim.
+- [ ] **Step 3:** Pin approved strings in the test; run `go test . ./internal/console/ -run Approved`; expect PASS.
+- [ ] **Step 4: Commit** `domains: approved copy (Luna pass DOMAINS-1)`.
+
+### Task 12: Switch on and witness on dev
+
+Production infrastructure needs Paul's scoped approval (AGENTS.md). This task asks for it and does nothing before it is given.
+
+- [ ] **Step 1:** Post on the branch's amadan discussion and ask Paul for: an Openprovider sandbox account, the dev nameserver domain, approval to create the dev delegation set and its records, and approval to set the env vars on the dev console.
+- [ ] **Step 2:** With approval, follow `docs/site/domains-buying.md` on dev; check with `dig NS <sandbox test domain> @ns1.<dev ns domain>` that the branded names answer.
+- [ ] **Step 3:** Merge (whole-branch Astra review done, CI green), release and roll to dev per the release recipe.
+- [ ] **Step 4: Witness:** `carlos domains buy` a sandbox domain for the `wakecheck` app on dev with a Stripe test card; record each state with timestamps and the time to `live` in the discussion. Sandbox registrations do not reach a real registry, so the final DNS leg is witnessed by querying the zone on the branded servers directly; the full public-DNS witness is flagship's first real purchase after Plan 2.
+- [ ] **Step 5:** Set the flagship switch-on date in the discussion (spec §9).