carlos / platform Public

plan: account subdomains, one slice in eight tasks

Also corrects the spec's door path to /api/cli/accounts/{account}/
subdomain, beside the plan door.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev a3261cd4f7e790b8468a9e5837c12e862b234cd0 parent cf7884a
2 files changed, +264 −1
  • docs/superpowers/plans/2026-11-11-account-subdomains.md +263 −0
  • docs/superpowers/specs/2026-11-11-account-subdomains-design.md +1 −1

Intent

Human

<task-notification> <task-id>a080abece70305c2d</task-id> <tool-use-id>toolu_013ukY2ESVXEZ9UinYFFUzHu</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/709ac745-ee81-4971-97b8-321e18b19cf6/tasks/a080abece70305c2d.output</output-file> <status>completed</status> <summary>Agent "Map box and edge alias code" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>1. **`internal/domains/claims.go`: create-only writes, conditional deletes, wrappers** - `func claimRawAttachInstanceCatchall(ctx context.Context, s release.Store, parent, account, app, createdAt, createdBy string) (created bool, err error)` is at :448. - It first checks that the parent claim is held by the same account and is neither pending nor regional (:449-464). - It then loops on `getClaimETag` (:474), which returns etag `""` when the claim is absent. - The write is `s.Put(ctx, ClaimKey(host), body, etag)` (:491). With an empty etag this is create-only. On `release.ErrCASConflict` it retries once (:493). - There is no separate helper for the conditional put. The `etag` argument to `Put` is the CAS. - `claimRawDetachClaimAt(ctx, s, host, account, app, etag string) (bool, error)` is at :840. It re-reads the claim, requires `curETag == etag` plus an account/app match (:848), then calls `release.DeleteIfMatch(ctx, s, ClaimKey(host), etag)` (:851). A CAS conflict returns false. - `DeleteIfMatch` is at `internal/release/conditional_delete.go:29`. `ErrConditionalDeleteUnsupported` is at :16. - Plain `claimRawDetachClaim` (:805) uses `DeleteIfMatch` only when `cur.Instances` is set (:816-824). Otherwise it uses `s.Delete` (:826). - **Wrappers.** The exported functions at :1200-1248 (`AttachInstanceCatchall`, `DetachClaimAt`, etc.) each call `release.WithAppMutation(ctx, s, account, app, "domains.&lt;Name&gt;", func(claimContext) error {…claimRaw…})`. - `WithAppMutation` is at `internal/release/app_mutation.go:12`. It runs the function under `AppMutationRunner.RunAppMutation` when the store implements it (the console store, and `hostops/app_mutation_runner.go:58`). Otherwise it calls the function directly. - It is keyed by (account, app). A namespace claim has no App, so you need to decide what to pass. - **Guard tests.** These pin every `Put` site by function name plus a sha256 of its source: - `TestPlan9B8RecordWriteCensus` (`internal/provision/plan9_b8_census_test.go:360`). The inventory entry for `claimRawAttachInstanceCatchall` is at :749. - The census in `internal/provision/regional_domains_447_census_test.go`, at :82. - A new claim writer must be added to both. Changed digests are reviewed, never blessed. - `TestClaimConsoleMutationInvariant` (`internal/console/claim_invariant_test.go:309`) census-checks console doors through `claimFixtures` and `claimSerialDoors`. A new console door will need a fixture. - I found no code generator for the wrappers. 2. **`internal/domains/aliases.go`** - `ReconcileAliasesReport` is at :414. - Claims are listed at :423: `cache.listWithHosts(ctx, s)` returns `claims, listed, dropped`. - Routes come from `reg.List()` (:427). `byHost` is built at :431. - `existing := reg.ListAliases()` is at :440. - The desired maps are declared at :452-455. - The main loop over claims starts at :461. - Pending claims are skipped at :468. Regional claims `continue` at :475-497. - `deriveHAIngressAliases` is called at :499. - The plain alias block is :504-551: `desired[c.Host]=true` and `reg.UpsertAlias` at :542-549. - Paths are handled at :575. Wildcard and catch-all at :690-780. - `deriveInstanceAliases` is called at :782-789. Its signature (:129): ```go func deriveInstanceAliases(claims []Claim, listed map[string]bool, routes []registry.Route, byHost map[string]registry.Route, existing []registry.RouteAlias, deploymentRoutes map[string]bool, desired map[string]bool, labelHosts func(account, app string) (map[string]int, map[string]bool, error), reg *registry.Registry, now func() time.Time) (incomplete bool) ``` - Its route filter (:171) is `rt.Provisioned &amp;&amp; !rt.IsSidecar() &amp;&amp; !rt.Replica &amp;&amp; rt.App==c.App &amp;&amp; release.RouteAccount(rt)==c.Account`. - **How rows are written.** Each pass upserts immediately and marks `desired[name]=true`. After every pass, the sweep at :790-802 deletes every existing alias not in `desired`, unless `StartupNoRemoval` is set. - **Where `deriveNamespaceAliases` slots in.** Directly after :782-789, before the removal at :790, with the same inputs. It would also need the apps domain. - **Where the "foreign claim under a held namespace derives nothing" rule goes.** Build the set of held namespaces before the loop (around :455). Then skip the claim before :499. That one skip covers HA ingress, plain aliases, paths and wildcard alike. Doing it inside :504 only would leave paths and wildcard open. - **Apps domain.** It is not available in this pass. `AliasReport` (:291-339) has no such field. The caller, `aliasPassReportingComplete` (`internal/host/agent.go:1480`, which calls the pass at :1511), passes only Region, `FleetRefused` and so on. `PLATFORM_APPS_DOMAIN` reaches `domains.Config.AppsDomain` (`reconcile.go:34`) through `domainsTickConfig` (`agent.go:3835-3854`). You would need to add an `AliasReport` input set from the environment there. 3. **Registry** (`internal/registry/registry.go`) - `Route` fields: `Slug` :55, `Kind` :56 (sidecar means `Kind=="sidecar"`, `IsSidecar()` :504), `HA` :256, `Platform` :341, `Provisioned` :357, `Account` :393, `Replica bool` :477 (this is the replica marker). - `RouteAlias` (:3559) has `Alias, Host, Account, App, DNSStatus, DNSCheckedAt, CertExpiresAt, CreatedAt`. - Nothing can mark a row as coming from a namespace claim. The table is defined at :822-831, and `UpsertAlias` (:3602) writes only those columns. - **Migrations.** `migrate()` (:792) uses `CREATE TABLE IF NOT EXISTS` and swallows `ALTER TABLE … ADD COLUMN` "duplicate column" errors. Route columns go through `routeAddedColumns` (:700). Note :1112: a new route column must be added in six places. - A new small table follows the `wildcard_domains` and `regional_domains` pattern (:837-861). A new alias column would mean changing `ListAliases`, `UpsertAlias` and `remote_dispatch.go:467`. 4. **`internal/edge/wildcard.go`** - The signature is `func parentsFor(staticAndDelegated []string, appsDomain string, hosts []string) []string` (:203). The sqid rule is at :222. - Its only production caller is `refresh()` (:276), as `parentsFor(..., w.appsDomain, w.hosts())`. - `hosts` is `e.deploymentHosts`, wired at :964. `deploymentHosts` (`edge.go:1697`) is `currentHosts()` (:1679) plus the home map's `Hosts()`. `currentHosts` admits Platform or Provisioned rows that are not aliases, plus platform aliases. Attached aliases are excluded (:1675-1683). - **Registry access.** The edge does read its registry here: `e.reg.ListWildcardDomains()` at :939, inside the `delegated` closure, with a last-good fallback. A held-names table could be read the same way. - Test files: `wildcard_test.go` (:71, :441), `wildcard_parents_test.go`, `steeringprobe_test.go` :166/:182. 5. **Other readers of aliases** - `deriveHAIngressAliases` (`aliases.go:1023`) is driven by claims (`c.Route` or `c.Wildcard`), not by alias rows. It skips claims with `Instances` set (:1024), so instance-derived names get no HA ingress. Namespace names would likewise need explicit handling. - Regional: `deriveRegional` (:931) is driven by claims. The edge's regional fold runs after the alias fold and replaces any alias with the same key (`edge.go:1490-1493`). - Edge `Reload` (`edge.go:1464-1487`) is driven by alias rows. - The edges file (`internal/host/edgesfile.go:797-850`) is driven by alias rows. It publishes only rows with `DNSStatus=="pointing"` and skips `*.` rows. It reads `PLATFORM_APPS_DOMAIN` itself (:666). - The readings sweep, `StampHealth` (`domains/reconcile.go:454`, aliases at :475, cert stamp at :557), is driven by alias rows. So is the status snapshot read at `agent.go:5115`. - The issuer's `deploymentHost` / `Allowed` (`edge.go:1790`) checks the served map, which includes aliases. It is driven by alias rows. - `assetpolicy.go:266` is driven by alias rows. - `handleAPIDomainList` (`console/apidomains.go:1329`) joins claims to the box readings, so it is driven by claims. A derived name has no claim of its own. 6. **Tests** - The fixtures are in `internal/domains/instancecatchall_test.go`. - Representative tests: - `TestInstanceCatchallDerivesOneAliasPerInstance` (:60) - `TestInstanceCatchallExactClaimWins` (:113) - `TestInstanceCatchallKeepsNamesWhenTheListingFails` (:507) - `TestInstanceCatchallCap` (:375) - Helpers in the same file: - `addInstance` (:17) does `reg.Upsert` plus `SetProvisioned`. - `aliasMap` (:29). - `jellyStore` (:45), built on `release.NewDirStore(t.TempDir())`. - `reconcile` (:53). - Fake stores: `unreadableKeyStore` (:394), `replacingStore` (:436), `listFailStore` (:498). - Helpers in `aliases_test.go`: `aliasRegWith` (:19), `putClaim` (:36), `deleteClaim` (:50), `aliasNow` (:68). 7. **Caps** - `maxInstanceAliases = 1000` is at `aliases.go:55`. It is counted by a local `derived` counter inside `deriveInstanceAliases` (:134, checks at :216 and :227). - The only other use is `TestInstanceCatchallCap` (`instancecatchall_test.go:378-387`). - Sharing the cap means the counter would have to be passed between the two functions or returned from one to the other.</result> <usage><subagent_tokens>122314</subagent_tokens><tool_uses>43</tool_uses><duration_ms>290298</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>af92f166403668811</task-id> <tool-use-id>toolu_01R9uPydBM8Ab6iUNXPt4vMr</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/709ac745-ee81-4971-97b8-321e18b19cf6/tasks/af92f166403668811.output</output-file> <status>completed</status> <summary>Agent "Map console and CLI surfaces" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Everything below was read from the worktree. Two findings change the plan as the spec states it: - **Path:** there is no `/api/accounts/...` door. Account-scoped API doors live under `/api/cli/accounts/{account}/...`. - **Claim cache:** `domains.ClaimCache` has no single-claim read. It only lists all claims. 1. **Console API routing and auth** - **Where routes live:** every route is one entry in the `routeDecls` table, `internal/console/routedecls.go:94`. `registerDecls(match)` (`routedecls.go:1221`) registers them. Entries of kind `kindCLI` go through `cliRoute(d, h)` (`authcli.go:448`), which applies the role gate. Setting `Allow: svcrole.Set{}` admits no service credential. - **Door to copy:** `handleAPIAccountPlanSet`, registered as `{Pattern: "POST /api/cli/accounts/{account}/plan", Kind: kindCLI, Allow: svcrole.Set{}, ...}` (`routedecls.go:982`; the GET is at :981). - Its shared gate is `accountPlanDoor(w, r) (string, *Account, bool)` (`apiaccountplan.go:45`). It calls `cliUser` (person only), then `s.store.IsOperator`, then `AccountBySqid(r.PathValue("account"))`, and refuses with a 404. - The handler (`apiaccountplan.go:95`) uses `allowWrite`, `readJSONStrictLimit`, `jsonError` and `writeJSON`. - **Auth helpers:** - `func (s *Server) apiPerson(w, r) bool` (`apicli.go:369`): refuses anything but `PrincipalUser` with the 401 from `cliNotSignedIn`. - `func (s *Server) cliUser(w, r) (string, bool)` (`authcli.go:731`): accepts only a person's CLI token. - `func (s *Server) platformOperator(addr string) bool` (`domainpolicy.go:120`): an owner of the ops account, or an address on `SystemOperators`. - `principalPlatformOperator(p Principal) bool` (`domainpolicy.go:137`): the same check, for a person only. - `func (s *Server) apiSystemRoller(w, r) (addr string, owner, ok bool)` (`apisystemupdate.go:144`): the same rule, with a bare 404 refusal. - **Spec mismatch:** `accountPlanDoor` uses `store.IsOperator`, not `platformOperator`. The spec's rule matches `apiSystemRoller` and `platformOperator`. - **Files a new route must also update:** `internal/console/testdata/claim-routes.txt` (:77, :257), `claim_invariant_fixtures_test.go` (:904, :1506), `claim_invariant_probes_{read,nonapp}_test.go` (:361, :1158) and `svcroutes_test.go:237-238`. 2. **Claim cache and tests** - **The cache:** `Server.claims domains.ClaimCache` (`server.go:1172`), defined at `internal/domains/claimcache.go:47`. - It has only three methods: `List(ctx, s) ([]Claim, error)` (:80), `ListWithUnread` (:95) and `Reset` (:217). There is no `Get`. - The single read is `domains.GetClaim(ctx, s release.Store, host) (*Claim, error)` (`claims.go:629`, uncached). `GetClaimETag` is at :624. - Existing callers of `claims.List`: `apidomains.go:1344`, `appsettings.go:789`. - **Tests:** - `TestDomainHostPolicyMatrix` (`domainplatform_test.go:37`) uses a bare `&amp;Server{cfg: Config{AppsDomain: "apps.test", ...}}` with no store. Note that `otherAccountsNamespace` returns true when `s.store == nil` (`domainpolicy.go:191`). - `TestAppsDomainNamespacesBelongToTheirAccounts` (`domainproof_test.go:251`) and `TestDeletedAccountsNamespaceStaysReserved` (:411). - **Fixtures:** - `attachFixture(t) (*consoleFixture, *Account)` (`domainattach_test.go:36`): sets AppsDomain to `oncarlos.com`, uses a real `Store`, and its release store is `fx.rel`. - `platformFixture` (`domainplatform_test.go:19`) and `newConsoleFixture` (`server_test.go:45`). 3. **Places that turn a host into a URL** (`[app]` means it carries an app or instance route host) - **API JSON** - The `url` fields in `apicli.go:616`, `apitemporary.go:244` and `authcli.go:1620` point at the console, not the app. `GET /api/cli/apps` (`apicli.go:725`) returns no host at all. - `[app]` `linkPublicationURL` builds `"https://" + s.apexHost(...)` (`apilinks.go:126`). It is used at `apilinks.go:155` and :223, and by `linkAppURL` (`accountlinks.go:203`), whose result is at :175, :259 and :443. - `[app]` `homeLinkPublicURL` (`homelink.go:152`), returned at `homelink.go:584` and :747. - `[app]` demo claim: `demo_claim_auth.go:502` and `demo_claim_status_page.go:42`. - `apidemo.go:643` uses the demo host. - Instance, record and route answers expose `json:"host"` (for example `apiinstances.go:1575`, `apiroutes.go:53`, `apistatusinstances.go:74`). The CLI turns these into URLs. - **Console pages and templates** (all `[app]`) - `apps.html:25`, :42 and :59, fed by `appRow{URL: apexHost(mine)}` (`server.go:6860`, `ladder.go:330`). - `ladder.html:88` (from `ladder.go:154` and :252). - `flow.html:37` and :49 (from `flow.go:203`). - `app_instance.html:7` and :26 (Aliases come from `instancepage.go:293-314`). - `app_instances.html:85`, `app_releases.html:165` and `app_overview.html:12` (linked apps only). - `demo_claim.html:156` and :187 (from `demo_claim_page.go:179`). - `domain_buy.html:41` is a custom domain, so it is not affected. - **Emails:** I found no app links. The senders that go through `deliver` (`alertnotify.go:747`, `plangracepass.go:236`, `storenotify.go:88`, `domainbuy.go:877`, `server.go:3281`) build no apps-domain URL. - **Other, not shown to users:** - `mailPushURL` (`mailpush.go:648`) is a webhook target. It should stay on the sqid host. - Probes: `demo_claim_transfer.go:597`, `demo_publish.go:234`. - Tunnel and console URLs: `authcli.go:882`, `managedenrol.go:195`. 4. **CLI** - **Dispatch:** `accountsCommand()` (`accounts.go:79`) is a `clireg.Node` with children `raw("create", cust, runAccountsCreate)` and `raw("plan", op, runAccountsPlan)` (:85-88). The CLI golden file is `testdata/clireg-golden.jsonl` (`clireg_golden_test.go:35`). - **HTTP helpers:** - `create` uses `newConsoleClient(base, token)` and `(*consoleClient).do(ctx, method, path, in, out)` (`auth.go:409`, :426). - The model to copy is `plan`: `requirePlanAPISession` (`accounts_plan.go:284`), then `sess.getJSON` / `postJSON` (`apimode.go:835`, :917) and `deleteJSON` (:3278). See `accounts_plan.go:159-165`. - **CLI code that builds URLs itself:** no root `*.go` file references the apps domain. The CLI prefixes API-returned hosts with `https://` in these places: - `deploy.go:1684` (`watchOrigin`) and `deploy.go:1752`. - `deploywatch.go:584-595`, with hosts from instance records (`deploy.go:587`, `deploywatch.go:698`). - `canary.go:661`, `instances_import.go:469`, and `devbox_cli.go:478` and :553. - The watch also probes these hosts, so a display host would need a separate field from the identity host. 5. **Copy gate** - Each copy set has a record (JSON or `.md`) under `docs/superpowers/plans/`, plus a test `approved_&lt;feature&gt;_copy_test.go` that pins its ID list as a literal. - The test checks four things: the record has `approved_by`/`approved_on`; it names exactly the pinned IDs; each `Text` appears byte for byte in its `File`; and approved strings are applied. - The shared helpers are `checkApprovedCopy` (`approved_copy_test.go:71`), `copyApplied` (:145) and `copyAppliedWith` (:131). Table-style records instead reuse the moves helpers (`approved_operator_pages_copy_test.go:12-31`). - "Digests" in `approved_copy_digests_test.go` is the name of the pointer-digest feature, not a hash. 6. **Deny and reserve lists** - `func (s *Server) platformDomains(exemptAppsDomain bool) []string` (`apidomains.go:144`). - `func (s *Server) reservedDomains(exemptAppsDomain bool) []string` (:153). It adds the apps domain only when `ReservePlatformDomains` is on; the steering host is never exempt. - `func (s *Server) denyEntries(entries []string, exemptAppsDomain bool) []string` (:176). - `domainHostPolicy` passes `allowed` as the exempt flag (`domainpolicy.go:84-98`). - `CONSOLE_DENY_DOMAINS` is read by `denyDomains()` (`cmd/console/main.go:1528`) into `DenyDomains` (:567). `reservePlatformDomains()` is at :1489, wired at :569. The config fields are at `server.go:719`, :733 and :750. 7. **Account settings page** - Route `GET /a/{sqid}/settings` (`routedecls.go:193`) goes to `handleAccountSettings` (`server.go:4143`), which renders `"account_settings"` (:4181). - `svcpage.go:236` re-renders the same page. - The template is `internal/console/templates/account_settings.html`. Its Identity table (lines 9-14) is the natural place to show the subdomain.</result> <usage><subagent_tokens>149730</subagent_tokens><tool_uses>73</tool_uses><duration_ms>463511</duration_ms></usage> </task-notification>

diff --git a/docs/superpowers/plans/2026-11-11-account-subdomains.md b/docs/superpowers/plans/2026-11-11-account-subdomains.md
new file mode 100644
index 000000000..195276c59
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-11-account-subdomains.md
@@ -0,0 +1,263 @@
+# Account Subdomains 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 platform operator gives an account a subdomain `<name>`; every
+app of the account then answers at `<prefix>.<name>.<apps-domain>`, and the
+platform shows that URL as the app's URL.
+
+**Architecture:** A namespace claim (`domains/*.<name>.<apps-domain>.json`,
+`AccountNamespace: true`) is the only new record. Boxes derive alias rows
+from it in `ReconcileAliasesReport` and publish held names to a small
+registry table the edge reads for wildcard parents. The console extends its
+namespace checks, adds one operator door, and routes every displayed app
+URL through `canonicalHost`.
+
+**Tech Stack:** Go, SQLite registry, bucket (`release.Store`), console
+templates.
+
+**Spec:** `docs/superpowers/specs/2026-11-11-account-subdomains-design.md`
+(approved 2026-11-11). Section numbers below (§4.2 and so on) are the spec's.
+
+## Global Constraints
+
+- Neutral example names only in tests, comments and copy: account `bdq`,
+ name `harbour`, app `shop`, apps domain `apps.test` (console tests) or
+ `oncarlos.com` (existing `attachFixture`). Never a tenant's name.
+- Every user-facing string goes through copy review (Task 1) before it is
+ written into a file. No em dashes in copy. Console pages get the UX pass
+ (AGENTS.md) in the same review.
+- Tests run locally are targeted: `go test ./<pkg> -run <Name>`. No full
+ suites, no `-race` sweeps locally; CI on amadan runs the rest.
+- `GOCACHE` stays at its default.
+- Commit subjects under 80 characters; body after a blank line.
+- `CARLOS_HOST` and `apexHost(sqid, app)` are identity and do not change.
+ Only display sites use `canonicalHost`.
+- Name rules (§4.2), copied exactly: label shape
+ `^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$`; refuse hyphens at positions 3
+ and 4; refuse `domains.ValidSqid(name) && len(name) < 7`; refuse
+ `domains.IsReservedSqid(name)`.
+
+## Review Focus
+
+1. **Name set on an account with no routes yet.** Nothing is derived and no
+ wildcard is ordered; the first app created afterwards answers under the
+ name with no further step. (Task 3 test.)
+2. **HA app in the account.** The name must reach the HA ingress map like
+ an exact claim does, or HA apps silently miss the name. (Task 3 test.)
+3. **Operator types `Harbour ` or `harbour.apps.test`.** Trim and lowercase;
+ anything that is not then a bare label is refused with the shape reason.
+ (Task 2 test.)
+4. **Box without `PLATFORM_APPS_DOMAIN`.** The namespace pass derives
+ nothing and does not fail the alias pass. (Task 3 test.)
+5. **Subdomain removed.** Console pages and API answers flip back to the
+ sqid host on the next read after the claim cache refreshes, never show
+ a name that no longer serves for longer than one cache interval.
+ (Task 6 test.)
+
+---
+
+### Task 1: Copy deck and UX pass (gate)
+
+**Files:**
+- Create: `docs/superpowers/plans/2026-11-11-account-subdomains-copy.json`
+ (record shape of an existing `approved_*_copy` record)
+
+- [ ] **Step 1: Draft every string** the later tasks need, each with an ID:
+ - CLI: `set` success, `set` still-issuing note, `remove` success, `show`
+ with and without a name, usage line.
+ - Refusals (one each): bad shape; sqid-shaped and shorter than 7;
+ reserved label; held by another account (names nothing about that
+ account); infrastructure name; something already lives there (lists
+ hosts); account already has a subdomain; remove refused while
+ hand-attached names remain (lists them); not a platform operator.
+ - Console: account settings row label and its two states; app page
+ label for the sqid URL ("permanent address" wording).
+- [ ] **Step 2: UX pass** on the account settings row and the app/instance
+ pages showing two URLs (dashboardy, state first, little reading).
+- [ ] **Step 3: Run copy review** (copy-review skill) and wait for Paul's
+ edits; apply them verbatim to the record with `approved_by`/`approved_on`.
+- [ ] **Step 4: Commit** the record.
+
+Later tasks use only approved strings by ID.
+
+### Task 2: The namespace claim in `internal/domains`
+
+**Files:**
+- Modify: `internal/domains/claims.go` (Claim field, attach/detach)
+- Create: `internal/domains/namespace.go`
+- Test: `internal/domains/namespace_test.go`
+- Modify: `internal/provision/plan9_b8_census_test.go`,
+ `internal/provision/regional_domains_447_census_test.go` (new writers)
+
+**Interfaces:**
+- Produces:
+ - `Claim.AccountNamespace bool` with tag `json:"account_namespace,omitempty"`.
+ - `func NamespaceHost(name, appsDomain string) string` → `"*." + name + "." + appsDomain`.
+ - `func NormalizeSubdomain(raw string) (string, bool)` (trim, lowercase, shape).
+ - `type SubdomainRefusal string` with constants `SubdomainShape`,
+ `SubdomainSqidShaped`, `SubdomainReserved` (used here) and
+ `SubdomainHeld`, `SubdomainInfrastructure`, `SubdomainOccupied`,
+ `SubdomainAccountHasOne` (used by Task 5).
+ - `func SubdomainRuleRefusal(name string) SubdomainRefusal` ("" when allowed; §4.2 rules that need no store: shape, `xn--`, sqid-shaped under 7, reserved).
+ - `func AttachAccountNamespace(ctx, s release.Store, name, appsDomain, account, createdAt, createdBy string) (created bool, err error)`.
+ - `func DetachAccountNamespaceAt(ctx, s release.Store, name, appsDomain, account, etag string) (bool, error)`.
+ - `func AccountNamespaces(claims []Claim, appsDomain string) (byName map[string]string, byAccount map[string]string)` — name→sqid and sqid→name from claims with `AccountNamespace` set, not pending, shape-valid.
+
+- [ ] **Step 1: Write failing tests** in `namespace_test.go`:
+ - `TestSubdomainRuleRefusal`: table — `harbour` "", `market` → `SubdomainSqidShaped`, `marketx` "" (7 letters), `dev`/`edge`/`www` → `SubdomainReserved`, `ab--x` and `xn--a` → `SubdomainShape`, `-a` → `SubdomainShape`, `shop2` "".
+ - `TestNormalizeSubdomain`: `" Harbour "` → `("harbour", true)`; `"harbour.apps.test"` → `("", false)`.
+ - `TestAttachAccountNamespaceIsCreateOnly`: two attaches of `harbour` by `bdq` then `bcd` on `release.NewDirStore(t.TempDir())`: first `created=true`, second `created=false, err=nil`, `GetClaim` still says `bdq`; body has `Host "*.harbour.apps.test"`, `AccountNamespace true`, empty `App`, `Route`.
+ - `TestDetachAccountNamespaceNeedsEtagAndAccount`: wrong account → false; stale etag → false; right → true and claim gone.
+ - `TestAccountNamespacesSkipsPendingAndOtherKinds`: an instance catch-all on another parent and a pending namespace claim are not in either map.
+ - `TestOldBinaryShapeDerivesNothing`: decode a namespace claim into a struct copy without the field (or assert `Route==""`, `!Instances`, `!Wildcard`) — documents §4.1's additive rule.
+- [ ] **Step 2: Run** `go test ./internal/domains -run 'Subdomain|AccountNamespace|OldBinaryShape'` — expect FAIL (undefined).
+- [ ] **Step 3: Implement.** Model the attach on `claimRawAttachInstanceCatchall` (`claims.go:448`): `getClaimETag`, `s.Put(ctx, ClaimKey(host), body, "")`, no retry needed beyond its CAS handling. Detach models `claimRawDetachClaimAt` (`claims.go:840`) with `release.DeleteIfMatch`. Exported wrappers call `release.WithAppMutation(ctx, s, account, "", "domains.AttachAccountNamespace", …)`; confirm the console's `RunAppMutation` accepts an empty app (add a test if it branches on it).
+- [ ] **Step 4: Add the two new `claimRaw*` writers to both census inventories** with their digests (the census tests fail and print the digest; review the source before pinning it).
+- [ ] **Step 5: Run** the Step 2 command plus `go test ./internal/provision -run 'Census'` — expect PASS.
+- [ ] **Step 6: Commit** `domains: account namespace claim (#subdomains T2)`.
+
+### Task 3: Boxes derive the names
+
+**Files:**
+- Modify: `internal/domains/aliases.go` (`AliasReport`, `ReconcileAliasesReport`)
+- Create: `internal/domains/namespacealiases.go` (`deriveNamespaceAliases`)
+- Modify: `internal/registry/registry.go` (new table `account_namespaces`)
+- Modify: `internal/host/agent.go` (`aliasPassReportingComplete` ~:1480: set `AliasReport.AppsDomain` from `PLATFORM_APPS_DOMAIN`, the same source as `domainsTickConfig` ~:3835)
+- Test: `internal/domains/namespacealiases_test.go`, `internal/registry/registry_test.go`
+
+**Interfaces:**
+- Consumes: Task 2's `AccountNamespaces`, `NamespaceHost`.
+- Produces:
+ - `AliasReport.AppsDomain string` (input).
+ - registry: table `account_namespaces(name TEXT PRIMARY KEY, account TEXT NOT NULL)`, `func (r *Registry) SetAccountNamespaces(m map[string]string) error` (replace whole set), `func (r *Registry) ListAccountNamespaces() (map[string]string, error)`. Follow the `wildcard_domains` pattern (`registry.go:837-861`).
+ - `func deriveNamespaceAliases(held map[string]string, appsDomain string, routes []registry.Route, byHost map[string]registry.Route, deploymentRoutes map[string]bool, exact map[string]bool, desired map[string]bool, reg *registry.Registry, now func() time.Time, rep *AliasReport) (incomplete bool)`.
+
+Rules (§4.4), in this order:
+1. Before the claim loop (~:455) build `held` (name→sqid) from the listed claims. In the loop, before `deriveHAIngressAliases` (~:499), skip any claim whose host is `<x>.<name>.<apps>` or `<name>.<apps>` for a held name with a different `Account`; log once per claim (reuse the `sayInstanceCatchallOnce` pattern).
+2. After `deriveInstanceAliases` (~:782-789) and before the removal sweep (~:790), call `deriveNamespaceAliases`. Eligible route: `(rt.Provisioned || rt.Platform) && !rt.IsSidecar() && !rt.Replica && release.RouteAccount(rt) == sqid` and host ends `"." + sqid + "." + appsDomain` with a non-empty prefix. Derived name: prefix + `"." + name + "." + appsDomain`.
+3. Skip a derived name that has an exact claim (listed, any holder), a local route, or a deployment route.
+4. For each HA route in `rep.HAIngressRoutes` of the account under the sqid, add `rep.AliasIngress[derived] = rt` unless the name is taken (same checks as `deriveHAIngressAliases`'s `add`).
+5. Cap: share `maxInstanceAliases` by counting into the same budget (return the count from `deriveInstanceAliases` or pass a pointer); overflow logged.
+6. `reg.SetAccountNamespaces(held)` once per pass; on a listing failure keep existing rows and the existing table (return incomplete).
+7. Empty `appsDomain`: derive nothing, write nothing, not incomplete.
+
+- [ ] **Step 1: Write failing tests** (helpers from `instancecatchall_test.go` and `aliases_test.go`: `aliasRegWith`, `putClaim`, `addInstance`, `aliasMap`, `reconcile`):
+ - `TestNamespaceDerivesEveryAccountRoute`: routes `shop.bdq.apps.test` (Provisioned), `site.bdq.apps.test` (Platform only), `team1.bdq.apps.test` (instance) → aliases `shop/site/team1.harbour.apps.test` pointing at their sqid hosts.
+ - `TestNamespaceSkipsOtherAccountsSidecarsReplicas`: route `x.bcd.apps.test`, a sidecar and a replica row under `bdq` → no alias.
+ - `TestNamespaceExactClaimAndRoutesWin`: exact claim `shop.harbour.apps.test` by `bdq` on another app → that claim's row, not the derived one; a real route at a derived name → no alias.
+ - `TestForeignClaimUnderHeldNameIsInert`: claim `x.harbour.apps.test` by `bcd` with a Route → no alias row, no HA ingress entry, no wildcard row, no path rows.
+ - `TestNamespaceNoRoutesThenFirstRoute` (Review Focus 1).
+ - `TestNamespaceHAIngress` (Review Focus 2): HA route `shop.bdq.apps.test` in `rep.HAIngressRoutes` → `rep.AliasIngress["shop.harbour.apps.test"]` set.
+ - `TestNamespaceWithoutAppsDomain` (Review Focus 4).
+ - `TestNamespaceRemovedDropsRows`: delete claim, reconcile → rows gone, `ListAccountNamespaces` empty.
+ - `TestNamespaceKeepsRowsWhenListingFails` (use `listFailStore`).
+ - `TestCanaryHostIsMirrored`: `c1.shop.bdq.apps.test` → `c1.shop.harbour.apps.test`.
+ - registry: `TestAccountNamespacesRoundTrip` (set, list, replace with smaller set).
+- [ ] **Step 2: Run** `go test ./internal/domains -run 'Namespace|ForeignClaimUnderHeld|CanaryHostIsMirrored'` and `go test ./internal/registry -run AccountNamespaces` — expect FAIL.
+- [ ] **Step 3: Implement** as specified above.
+- [ ] **Step 4: Run** the Step 2 commands plus `go test ./internal/domains -run 'InstanceCatchall|Alias'` — expect PASS (existing catch-all and alias tests unchanged).
+- [ ] **Step 5: Commit** `domains: boxes derive account subdomain aliases (T3)`.
+
+### Task 4: Edge wildcard parents for names
+
+**Files:**
+- Modify: `internal/edge/wildcard.go` (`parentsFor`, `refresh`), `internal/edge/edge.go` (wire the reader beside `ListWildcardDomains` ~:939)
+- Test: `internal/edge/wildcard_parents_test.go`
+
+**Interfaces:**
+- Consumes: Task 3's `Registry.ListAccountNamespaces`.
+- Produces: `func parentsFor(staticAndDelegated []string, appsDomain string, hosts []string, names map[string]string) []string`, where `names` maps sqid → name.
+
+`hosts` comes from `deploymentHosts`, which excludes attached aliases, so the derived hosts are not in it. Name parents therefore come from the sqid hosts: for each host `<app>.<sqid>.<apps>` that yields a sqid parent, also add `<name>.<apps>` when `names[sqid]` is set. Invert `ListAccountNamespaces` (name → sqid) at the call site.
+
+- [ ] **Step 1: Write failing tests** in `wildcard_parents_test.go`:
+ - `TestParentsForAddsHeldName`: hosts `shop.bdq.apps.test`, names `{bdq: harbour}` → parents include `bdq.apps.test` and `harbour.apps.test`.
+ - `TestParentsForNoNameNoExtraParent`: names empty → only `bdq.apps.test`.
+ - `TestParentsForNameWithoutRoutes`: names `{bdq: harbour}`, no `bdq` hosts → no `harbour` parent (no certificate for an empty namespace).
+ - `TestRefreshKeepsLastGoodNamesOnReadError` (mirror the delegated last-good test).
+- [ ] **Step 2: Run** `go test ./internal/edge -run 'ParentsFor|RefreshKeepsLastGoodNames'` — FAIL.
+- [ ] **Step 3: Implement**; update every `parentsFor` caller and test call.
+- [ ] **Step 4: Run** Step 2 plus `go test ./internal/edge -run 'Wildcard'` — PASS.
+- [ ] **Step 5: Commit** `edge: wildcard certificate for account subdomains (T4)`.
+
+### Task 5: Console namespace policy
+
+**Files:**
+- Create: `internal/console/subdomains.go`
+- Modify: `internal/console/domainpolicy.go` (`appsNamespace`, `otherAccountsNamespace`, `domainProofExempt`, `firstRouteOutsideNamespace`)
+- Test: `internal/console/subdomains_test.go`, extend `domainproof_test.go`
+
+**Interfaces:**
+- Consumes: Task 2's `AccountNamespaces`, `SubdomainRuleRefusal`, `NormalizeSubdomain`.
+- Produces:
+ - `func (s *Server) accountSubdomains(ctx context.Context) (byName, byAccount map[string]string, err error)` from `s.claims.List(ctx, s.cfg.Releases)`.
+ - `appsNamespace(host)` returns the sqid for a held name label too. On a list error it returns the label unchanged when sqid-shaped and "" otherwise; callers that refuse on lookup failure keep doing so (`otherAccountsNamespace` refuses a non-sqid label under the apps domain when the list failed).
+ - `func (s *Server) subdomainRefusal(ctx context.Context, account, name string) (reason domains.SubdomainRefusal, conflicts []string)` adding the store rules: `SubdomainHeld` (any account sqid via `AccountAnyBySqid`, or another namespace claim), `SubdomainInfrastructure` (`domainHostPolicy` says `hostReserved` for `<name>.<apps>` or `probe.<name>.<apps>`, evaluated with `reservedDomains(true)`/`platformDomains(true)` so the blanket apps-domain entry is skipped and every other entry kept), `SubdomainOccupied` with `conflicts` = hosts of other accounts' claims and any deployment routes at or under `<name>.<apps>`, `SubdomainAccountHasOne`.
+
+- [ ] **Step 1: Write failing tests** (use `attachFixture` for store-backed cases, `platformFixture` for policy):
+ - `TestSubdomainRefusalRules`: table over every reason above plus allowed `harbour`.
+ - `TestSubdomainRefusalWithReservePlatformDomains`: `ReservePlatformDomains: true` → `harbour` allowed; `edge` refused; a `DenyDomains` entry `harbour.oncarlos.com` → `SubdomainInfrastructure`.
+ - `TestOtherAccountsNamespaceCoversHeldName`: `bdq` holds `harbour`; attach of `x.harbour.oncarlos.com` by another account → `hostReserved`; by `bdq` → allowed and proof-exempt.
+ - `TestRemovedNameStopsProtecting`: detach, reset cache → other account's attach is no longer refused by the namespace rule.
+ - `TestFirstRouteUnderHeldName`: a first-route attach of `blog.harbour.oncarlos.com` by another account → refused; by `bdq` → allowed.
+- [ ] **Step 2: Run** `go test ./internal/console -run 'SubdomainRefusal|OtherAccountsNamespaceCoversHeldName|RemovedNameStopsProtecting|FirstRouteUnderHeldName|AppsDomainNamespaces|DomainHostPolicyMatrix'` — new ones FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** Step 2 — all PASS (existing matrix and namespace tests unchanged).
+- [ ] **Step 5: Commit** `console: account subdomains are the account's namespace (T5)`.
+
+### Task 6: Console door and canonical URLs
+
+**Files:**
+- Create: `internal/console/apisubdomain.go`
+- Modify: `internal/console/routedecls.go` (three entries beside `POST /api/cli/accounts/{account}/plan` ~:982, `Kind: kindCLI, Allow: svcrole.Set{}`)
+- Modify: route fixtures: `internal/console/testdata/claim-routes.txt`, `claim_invariant_fixtures_test.go`, `claim_invariant_probes_{read,nonapp}_test.go`, `svcroutes_test.go`
+- Create: `internal/console/canonical.go`
+- Modify display sites: `server.go` ~:6860 (`appRow.URL`), `ladder.go` :154/:252, `flow.go` :203, `instancepage.go` :293-314, `apilinks.go` :126, `homelink.go` :152, `demo_claim_page.go` :179, `demo_claim_auth.go` :502, `demo_claim_status_page.go` :42, `templates/account_settings.html` (Identity table), `app_instance.html`, `app_overview.html`
+- Modify API answers the CLI prints: add `PublicHost string json:"public_host,omitempty"` beside `Host` at `apiinstances.go` ~:1575, `apiroutes.go` ~:53, `apistatusinstances.go` ~:74
+- Test: `internal/console/apisubdomain_test.go`, `internal/console/canonical_test.go`
+
+**Interfaces:**
+- Consumes: Task 2 attach/detach, Task 5 `subdomainRefusal`, `accountSubdomains`.
+- Produces:
+ - Doors `GET|POST|DELETE /api/cli/accounts/{account}/subdomain`. Gate: `cliUser` (person), then `platformOperator(addr)` (not `store.IsOperator`), then `AccountBySqid`, 404 otherwise, like `accountPlanDoor` (`apiaccountplan.go:45`). POST body `{"name": "..."}`; answers `{"name": "...", "host": "*.harbour.<apps>", "foreign": [...]}`. After a successful write, re-list claims under the name and return any foreign ones in `foreign` (§4.2 race). DELETE refuses with `conflicts` while the account holds exact claims or routes under the name (§4.3). `s.claims.Reset()` after either write.
+ - `func (s *Server) canonicalHost(ctx context.Context, host string) string` (§4.8 rule; unchanged host on any error).
+ - `mailPushURL` (`mailpush.go:648`) and probe URLs stay on the identity host.
+
+- [ ] **Step 1: Write failing tests:**
+ - `TestSubdomainDoorOperatorOnly`: member owner of `bdq` → 404; app token → refused; ops owner → 200; `CARLOS_SYSTEM_OPERATORS` address → 200.
+ - `TestSubdomainDoorSetShowRemove`: set, show, set again → `SubdomainAccountHasOne`, remove, show empty.
+ - `TestSubdomainDoorReportsForeignClaim`: a foreign claim written under the name between check and write (inject via a store wrapper) → 200 with it in `foreign`.
+ - `TestSubdomainRemoveRefusedWhileHandAttached`.
+ - `TestCanonicalHost`: `shop.bdq.oncarlos.com` → `shop.harbour.oncarlos.com`; `c1.shop.bdq…` → `c1.shop.harbour…`; custom domain unchanged; account without a name unchanged.
+ - `TestAppsPageLinksToName`: render the apps page for `bdq` with a name; the link is the name URL and the sqid URL appears as the approved "permanent address" label.
+ - `TestInstanceAnswerCarriesPublicHost`.
+ - `TestRemovedNameFlipsDisplayBack` (Review Focus 5).
+- [ ] **Step 2: Run** `go test ./internal/console -run 'SubdomainDoor|SubdomainRemove|CanonicalHost|AppsPageLinksToName|PublicHost|FlipsDisplayBack|ClaimConsoleMutationInvariant|SvcRoutes'` — FAIL.
+- [ ] **Step 3: Implement**, using approved copy IDs from Task 1.
+- [ ] **Step 4: Run** Step 2 — PASS.
+- [ ] **Step 5: Commit** `console: subdomain door; name URL is canonical (T6)`.
+
+### Task 7: CLI
+
+**Files:**
+- Create: `accounts_subdomain.go`, `accounts_subdomain_test.go` (repo root)
+- Modify: `accounts.go` :85-88 (add `raw("subdomain", op, runAccountsSubdomain)`), `testdata/clireg-golden.jsonl`
+- Modify display sites to print `public_host` when present and keep probing `host`: `deploy.go` :1684/:1752, `deploywatch.go` :584-595, `canary.go` :661, `instances_import.go` :469
+
+**Interfaces:**
+- Consumes: Task 6 doors and `public_host`.
+- Produces: `carlos accounts subdomain set --account <sqid> <name>`, `remove --account <sqid>`, `show --account <sqid>`, modelled on `accounts_plan.go` (`requirePlanAPISession`, `sess.getJSON`/`postJSON`/`deleteJSON`). `set` then polls `https://<derived host of any one app>/` with a TLS handshake every 5 s for up to 120 s; prints the approved success line, or the approved still-issuing line at timeout (exit 0).
+
+- [ ] **Step 1: Write failing tests** with an `httptest` console: `TestAccountsSubdomainSet`, `TestAccountsSubdomainSetRefusalPrintsReason`, `TestAccountsSubdomainRemoveListsConflicts`, `TestAccountsSubdomainShow`, `TestDeployWatchPrintsPublicHostProbesHost`, golden update via the golden test's update flag.
+- [ ] **Step 2: Run** `go test . -run 'AccountsSubdomain|DeployWatchPrintsPublicHost|CliregGolden'` — FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** Step 2 — PASS. Also `GOOS=darwin go vet .` and `GOOS=windows go vet .` (cross-compile gate).
+- [ ] **Step 5: Commit** `cli: carlos accounts subdomain (T7)`.
+
+### Task 8: Review, merge, dev witness
+
+- [ ] **Step 1:** Whole-branch review by Astra and Fable (security gate, namespace trust boundary), round budget per AGENTS.md stopping rules.
+- [ ] **Step 2:** Push, CI green on amadan, squash merge with `-message` and `-expect`.
+- [ ] **Step 3:** Release and dev roll only with Paul's go. Witness on dev (§6): set a name on a test account; load an existing app and an instance through it; create a new app and load it through the name; confirm `*.<name>` certificate; second account's attach of `x.<name>…` refused; console and `carlos instances` show the name URL; remove; names stop serving and pages flip back.
+- [ ] **Step 4:** Record the witness on the branch discussion; update memory.
diff --git a/docs/superpowers/specs/2026-11-11-account-subdomains-design.md b/docs/superpowers/specs/2026-11-11-account-subdomains-design.md
index 15a0ded01..39766f7de 100644
--- a/docs/superpowers/specs/2026-11-11-account-subdomains-design.md
+++ b/docs/superpowers/specs/2026-11-11-account-subdomains-design.md
@@ -155,7 +155,7 @@ accounts are named after an email address.
### 4.3 The door
-`POST /api/accounts/<sqid>/subdomain` (set) and `DELETE` (remove), allowed
+`POST /api/cli/accounts/{account}/subdomain` (set), `GET` (show) and `DELETE` (remove), beside the plan door in `routedecls.go`, allowed
only to a platform operator (`platformOperator`: an owner of the ops
account or an address on `CARLOS_SYSTEM_OPERATORS`), and only from a
person, never an app token. The CLI is