carlos / platform Public

plan: platform accounts slice 1, Paul's round 3 rulings

r3-1: customer deletion moves to slice 2; the DELETE door, its CLI verb,
store method, copy and tests are removed, and the hand-off says what the
slice 2 delete must hold. Platform-account deletion stays guarded.
r3-2: the deadlock witness starts empty and pauses where the old account
lock was taken, so restoring that lock fails it.
Task 10 writes the credential-mints-credential exception into AGENTS.md.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 0f9c1e8193a97e28d295167c40d03cd73d361962 parent b0c0a64
1 file changed, +61 −52
  • docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md +61 −52

Intent

Attributed to this commit: 16.9 g CO₂e (1,774,466 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-platform-accounts, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md b/docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md
index 43312dfbe..6d1046e9e 100644
--- a/docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md
+++ b/docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md
@@ -4,7 +4,7 @@
**Goal:** An operator grants an account platform status; that account's `platform` service credential (or an owner of it) creates ownerless customer accounts linked to it, lists and changes them within the grant, mints short-lived per-customer credentials, and deploys a static site into a customer account to serving, with no person signing in.
-**Architecture:** The grant is a console table read on every platform request. The link is a `platform` field (plus `platform_ref`) in the customer's bucket manifest, written in the create-only mint and mirrored in two `accounts` columns that `MaterializeAccounts` fills at birth only. The platform credential is a new svcrole outside Admin's union that reaches only six new `/api/cli/platform/{account}/...` doors; per-customer credentials are a new `cli_tokens` kind that resolves to an ordinary one-account Publish or Deploy principal, but only while the link and the grant are live.
+**Architecture:** The grant is a console table read on every platform request. The link is a `platform` field (plus `platform_ref`) in the customer's bucket manifest, written in the create-only mint and mirrored in two `accounts` columns that `MaterializeAccounts` fills at birth only. The platform credential is a new svcrole outside Admin's union that reaches only five new `/api/cli/platform/{account}/...` doors (customer deletion is slice 2, Paul r3); per-customer credentials are a new `cli_tokens` kind that resolves to an ordinary one-account Publish or Deploy principal, but only while the link and the grant are live.
**Tech Stack:** Go; the console's SQLite store (`internal/console`); `release.Store` for the bucket; the `carlos` CLI (`clireg`, `apiSession`).
@@ -27,6 +27,12 @@ Round 2 (Astra, findings `docs/superpowers/plans/ASTRA-FINDINGS-platform-account
- **r2-1 (P1), account and billing locks have one acquisition order.** Confirmed: `startDomainPurchase` takes `planLock` (`domainbuy.go:131`), which with plans on is `lockAccount`, and then `holdBilling` (`:165`); the deletion path holds the billing hold across `deleteAccountNow` (`ownership.go:139-144`), so r1-3's account lock inside `deleteAccountNow` could deadlock with a purchase. Fix: r1-3's serialization moves off the account lock onto a **dedicated platform lifecycle lock** (`s.lockPlatformLifecycle(sqid)`), taken by customer creation (including finishing pending mints), by account deletion (platform and customer) and by nothing else. Deletion takes it in `handleDeleteAccount` before `retireForDeletion`'s billing hold, and `deleteAccountNow` takes no account lock. The global order, written into the lock comments: **platform lifecycle → account/plan → billing**. `startDomainPurchase` already takes account/plan before billing, and deletion takes lifecycle, then billing, and no account lock, so no two paths take any pair in opposite orders. The coordinator's steer gave the tail as "billing, then account/plan"; the code takes them the other way round (`domainbuy.go:131` then `:165`), so the plan records the order the code actually has. Tasks 8, 9.
- **r2-2 (P2), credential management agrees with authentication.** Confirmed: `ServicePrincipals` filters on `revoked_at = 0` only (`svcprincipal.go:456-465`), rotation matches the same rows and keeps the generation (`:486-505`), and name reservation counts live rows (`:422`, backed by `authstore.go:326`). Fix: the generation check stays the authorization rule (it is what refuses an in-flight mint), and `RevokePlatformGrant` additionally marks every platform-role and per-customer row of the platform revoked **in the same transaction** that ends the generation. Listing, rotation and name reuse then see what authentication sees. Tasks 4, 7.
+Round 3 (Astra, findings `docs/superpowers/plans/ASTRA-FINDINGS-platform-accounts-1-r3.md`, reviewed at `a63af377`): NOT READY, one P1 and one P2. Round 3 is the last under the stopping rule; Paul ruled on 2026-11-19. No further plan review; the per-task reviews during the build take over.
+
+- **r3-1 (P1), an account cannot be tombstoned while a concurrent create adds an app (Paul r3).** Confirmed: app creation takes only `planLock` (`apicli.go:555`), so r2-1's move of customer deletion onto the lifecycle lock let an app create land between the customer delete's app check and its tombstone, and a restart then reaps the account with its app rows (`materialize.go:125`, `store.go:1887`). Ruling: **customer deletion moves to slice 2.** Removed from this plan: the platform `DELETE .../customers/{customer}` door, `carlos platform customers delete`, `DeleteUnclaimedCustomer`, `ErrCustomerClaimed`, `ErrCustomerHasApps`, their copy rows and tests. Kept: a platform account cannot be deleted while it has linked customers (pending mints included), the lifecycle lock shared by customer create and account deletion, and the r2-1 deadlock fix. The slice 2 hand-off carries what customer deletion must do.
+- **r3-2 (P2), the deadlock witness must reach the conflicting acquisitions (Paul r3).** Confirmed: the witness started with an app, and `deletionRefused` (`ownership.go:136`, `:167`) refused before the billing hold was taken. Fix: the witness starts from an empty account and pauses deletion after billing is held, at the first line of `deleteAccountNow` where round 1 put the account-lock acquisition. Then it creates the app and starts the domain purchase. On resume, deletion refuses without tombstoning, releases billing, and the purchase finishes. Putting the round 1 lock back at that line makes the test fail. Task 9.
+- **The credential-mints-credential exception (Paul r3): accepted.** Task 10 gains a step that writes the rule and its one exception into AGENTS.md: platform role only, one customer account, at most 24 h, the minted credential can never mint, checked against the grant generation on every request. AGENTS.md does not state the rule today; it lives in code comments (`apicli.go:342`, `svcroutes_test.go:133`, `routedecls.go:762`, `:934`), which the step points at the new entry.
+
## Global Constraints
House rules (from the brief, verbatim where they are rules):
@@ -73,10 +79,10 @@ From the spec and AGENTS.md:
Create:
-- `internal/console/platform_store.go`: grant table, link columns, linked-customer queries, linked account create/ensure/rename/delete, `migratePlatformAccounts`.
+- `internal/console/platform_store.go`: grant table, link columns, linked-customer queries, linked account create/ensure/rename, `migratePlatformAccounts`.
- `internal/console/platform_credentials.go`: per-customer credential mint, the live-link check, kind constants.
- `internal/console/apiplatformgrant.go`: the operator grant doors.
-- `internal/console/apiplatformcustomers.go`: the platform gate and the customer doors (create, list, show, update, delete).
+- `internal/console/apiplatformcustomers.go`: the platform gate and the customer doors (create, list, show, update). Customer deletion is slice 2 (Paul r3).
- `internal/console/apiplatformcredentials.go`: the per-customer credential door.
- `internal/console/apiplatformhost.go`: the Publish-reachable first static host door (§6.3).
- `internal/console/platformlinked.go`: linked-account policy used by billing, domain purchase, the free cap, deletion and notices.
@@ -289,8 +295,6 @@ type LinkedCustomer struct {
var (
ErrNotPlatform = errors.New("console: this account is not a platform account") // no grant row, or not active
ErrPlatformHasCustomers = errors.New("console: this platform account still has customer accounts")
- ErrCustomerClaimed = errors.New("console: someone owns this customer account")
- ErrCustomerHasApps = errors.New("console: this customer account still holds apps")
)
func (s *Store) migratePlatformAccounts() error
func (s *Store) PlatformGrant(ctx context.Context, accountID int64) (*PlatformGrant, error) // nil, nil: none
@@ -320,7 +324,6 @@ func (s *Store) CreateLinkedAccount(ctx context.Context, a NewLinkedAccount, now
func (s *Store) PlatformGenerationLive(ctx context.Context, q dbQuerier, platformAccountID, generation int64) (platformSqid string, ok bool) // the one check (Astra r1-2)
func (s *Store) EnsureLinkedAccount(id int64, sqid, name, platformSqid, ref string, created time.Time) (added bool, err error)
func (s *Store) RenameAccount(ctx context.Context, accountID int64, name string) error
-func (s *Store) DeleteUnclaimedCustomer(ctx context.Context, customerID int64, platformSqid string, now time.Time) error
```
Schema (in `migratePlatformAccounts`, idempotent, "duplicate column" forgiven like the ALTER lists):
@@ -373,18 +376,14 @@ func TestCreateLinkedAccountHasNoMembersAndAPlatformPlan(t *testing.T) {
// Members(id) empty; AccountPlatform == ("bcd", "4812"); AccountPlan(id).Source == PlanSourcePlatform,
// Plan == "personal", UpdatedBy == "service:bcd/cms"; no launch sponsorship row even with a rule recorded.
}
-func TestLinkedCustomerRefIsUniquePerPlatform(t *testing.T) // same ref on bcd twice: second CreateLinkedAccount errors; same ref on bcf is fine; after DeleteUnclaimedCustomer the ref is free again
+func TestLinkedCustomerRefIsUniquePerPlatform(t *testing.T) // same ref on bcd twice: second CreateLinkedAccount errors; same ref on bcf is fine; after Store.DeleteAccount on the customer the ref is free again
func TestLinkedCustomersListsOnlyThisPlatformsLiveAccounts(t *testing.T)
func TestEnsureLinkedAccountDropsAConflictingRef(t *testing.T) // a second birth with a taken ref is added with Ref ""
func TestDeleteAccountRefusesAPlatformWithCustomers(t *testing.T) // errors.Is(err, ErrPlatformHasCustomers) for a live customer and for a pending mint alone (Astra r1-3); after both are gone it succeeds
-func TestDeleteUnclaimedCustomerRefusals(t *testing.T) {
- // owner membership -> ErrCustomerClaimed; an app row -> ErrCustomerHasApps;
- // wrong platform sqid -> ErrAccountGone; success marks deleted_at (its credentials then fail the link check, Task 10).
-}
func TestMigrateIsIdempotentWithPlatformTables(t *testing.T) // Open, Close, Open the same file: no error
```
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestPlatformGrantRoundTrip|TestRevokePlatformGrant|TestPendingMints|TestCreateLinkedAccount|TestLinkedCustomer|TestEnsureLinkedAccount|TestDeleteAccountRefusesAPlatform|TestDeleteUnclaimedCustomer|TestMigrateIsIdempotentWithPlatform' -count=1`. Expected: FAIL.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestPlatformGrantRoundTrip|TestRevokePlatformGrant|TestPendingMints|TestCreateLinkedAccount|TestLinkedCustomer|TestEnsureLinkedAccount|TestDeleteAccountRefusesAPlatform|TestMigrateIsIdempotentWithPlatform' -count=1`. Expected: FAIL.
- [ ] **Step 3: Make room in `migrate` first.** `(*Store).migrate` is 389 code lines, held by the ratchet. Replace the run of feature calls from `migrateCLIAuth` to `migrateDomains` (`store.go:721-793`) with one `migrateFeatures()` method that iterates an ordered `[]func() error{s.migrateCLIAuth, s.migrateLinks, ...}` in the same order, carrying each call's comment onto its element, and append `s.migratePlatformAccounts` last. No reordering, nothing else changed. `migrate` shrinks; nothing grows.
@@ -394,7 +393,6 @@ func TestMigrateIsIdempotentWithPlatformTables(t *testing.T) // Open, Close, Ope
- `PlatformGenerationLive` (Astra r1-2): `SELECT p.sqid FROM platform_grants g JOIN accounts p ON p.id = g.account_id WHERE g.account_id = ? AND g.state = 'active' AND g.generation = ? AND p.deleted_at = 0`. `dbQuerier` is the `QueryRowContext` interface both `*sql.DB` and `*sql.Tx` satisfy, so the resolver and the mint transactions ask the identical question.
- `EnsureLinkedAccount`: `EnsureAccount`'s body (share an unexported helper) plus the two columns; inside its transaction, a ref already held by a live account of the same platform is dropped to `""` before the insert, so the unique index can never turn a birth into an ignored insert. No sponsorship either.
- `DeleteAccount` (`ownership.go:790`): inside its transaction, before the deletes, count live accounts whose `platform` is this account's sqid plus its pending mints; non-zero is `ErrPlatformHasCustomers` (Astra r1-3).
- - `DeleteUnclaimedCustomer`: one transaction: the row must be live with `platform = platformSqid` (else `ErrAccountGone`); owner count 0 (else `ErrCustomerClaimed`); `apps` count 0, unfiltered like `AppCount` (else `ErrCustomerHasApps`); then the same statements as `DeleteAccount`. No token sweep: a deleted account fails the link check every credential resolution makes (Task 10).
- `RevokePlatformGrant` (Astra r1-2, r2-2): one transaction: set state revoked and `generation = generation + 1`, and `UPDATE cli_tokens SET revoked_at = ? WHERE revoked_at = 0 AND ((kind = 'platform' AND platform_account_id = ?) OR (kind = 'service' AND role = 'platform' AND account_id = ?))`, returning that count. Two rules, two jobs: the generation check is **authorization** (every resolution and every mint asks `PlatformGenerationLive`, so a mint in flight across the revoke is refused even though its row did not exist when the sweep ran); the sweep is **bookkeeping**, so listing, rotation and name reservation, which read `revoked_at`, agree with authentication. A missing grant is `ErrNotPlatform`. `PutPlatformGrant` never changes the generation, so a re-grant after a revoke runs under the new one.
- [ ] **Step 5: Run** the Step 2 command, then the existing migration and deletion tests: `go test ./internal/console/ -run 'TestOpen|TestMigrate|TestDeleteAccount|TestEnsureAccount' -count=1`. Expected: PASS.
@@ -558,7 +556,7 @@ git commit -m "console: mint platform credentials on granted accounts only"
`POST /api/cli/platform/{account}/customers` → `handlePlatformCustomerCreate`;
`GET /api/cli/platform/{account}/customers` → `handlePlatformCustomerList` (optional `?ref=`);
`GET /api/cli/platform/{account}/customers/{customer}` → `handlePlatformCustomerShow`;
- `PATCH` and `DELETE` on the same path → Task 9; `POST .../customers/{customer}/credentials` → Task 10.
+ `PATCH` on the same path → Task 9; `POST .../customers/{customer}/credentials` → Task 10. No `DELETE` in slice 1 (Paul r3).
- ```go
type platformCaller struct {
P Principal
@@ -592,7 +590,7 @@ git commit -m "console: mint platform credentials on granted accounts only"
// lockPlatformLifecycle is the platform lifecycle lock (Astra r2-1): a keyedLocks field platformLocks on
// Server, in applocks.go, emitting lockEvent("platform", sqid, ...) like lockHostname does. Its comment
// states the order: platform lifecycle -> account/plan -> billing hold. Taken by customer creation, pending-mint
- // finishing and account deletion, and nothing else.
+ // finishing and account deletion (handleDeleteAccount), and nothing else.
func (s *Server) lockPlatformLifecycle(sqid string) func()
func (s *Server) finishPendingMints(ctx context.Context, platform *Account) error
// Test seam, nil in production: called with "lock" just before create takes the platform lock,
@@ -678,7 +676,7 @@ git commit -m "console: platform doors to create, list and show customer account
---
-### Task 9: Customer update and delete; platform accounts keep their customers
+### Task 9: Customer update; platform accounts keep their customers
**Files:**
- Modify: `internal/console/apiplatformcustomers.go`, `internal/console/routedecls.go`, `internal/console/ownership.go`, `internal/console/applocks.go`, `internal/console/billinghold.go` (lock events only), `internal/console/platformlinked.go` (create)
@@ -688,20 +686,17 @@ git commit -m "console: platform doors to create, list and show customer account
- Consumes: Tasks 2, 4, 8.
- Produces:
- `PATCH /api/cli/platform/{account}/customers/{customer}` → `handlePlatformCustomerUpdate`, body `{name?, plan?, reason?}`, reply the view.
- - `DELETE /api/cli/platform/{account}/customers/{customer}` → `handlePlatformCustomerDelete`, reply `{"deleted": true, "account": sqid}`.
- `var errPlanSetByOperator = errors.New("console: an operator set this account's plan")` in `apiplatformcustomers.go`.
- `func (s *Server) applyPlatformPlan(ctx context.Context, cust *Account, plan, reason, by string, now time.Time) error`: `transitionAccountPlan` (`planlapse.go:131`) with a write closure that refuses an old row whose source is operator or sponsored (`errPlanSetByOperator`) and otherwise does what `applyAccountPlan`'s closure does with `PlanSourcePlatform`, so lapse and grace work as for an owner's change.
- `platformlinked.go`: `func (s *Server) linkedPlatform(ctx context.Context, acct *Account) (*Account, error)` (nil when unlinked).
Update: write budget; nothing to change is 400 `update.empty`; a name runs `ValidAccountName`, then `domains.RenameAccountManifest` (bucket first), then `RenameAccount`, audit `audit.customer_rename`; a plan must be in `Grant.Plans` (`create.plan`), then `applyPlatformPlan` (`update.operator_plan` on refusal), audit `audit.customer_plan`. Empty reason becomes `fmt.Sprintf("platform %s", platform.Sqid)`.
-Delete: write budget; take `s.lockPlatformLifecycle(customer.Sqid)` for the rest (Astra r2-1: deletion takes the lifecycle lock, never the account lock); `LinkedCustomer.Owners > 0` is 409 `delete.claimed`; `AppCount > 0` is 409 `delete.apps`; then `tombstoneAccount` (bucket first, `ownership.go:672`), `s.manifestSeen.Delete`, `DeleteUnclaimedCustomer`, `auditAccountDeleted`. A bucket failure is 502 `delete.failed` and nothing is deleted. If `DeleteUnclaimedCustomer` refuses after the tombstone (an owner added box-side by `console member` in that window), log one line naming the account and answer 409 `delete.claimed`: the same accepted hazard `deleteAccountNow` documents (`ownership.go:196-201`), and the lock is what slice 2's claim must take to close it for claims.
-
Platform account deletion: `deletionRefused` (`ownership.go:161`) adds, before the app count, a refusal when `LinkedCustomerCount(acct.Sqid) > 0` (live customers and pending mints; flash `delete.platform_has_customers`), and a refusal for a linked account deleted by a person in the browser (flash `delete.linked`): until slice 2's leave, a linked account's end is its platform's door (decision D11).
Serializing deletion with creation (Astra r1-3, r2-1). The invariant: **no customer, pending or live, can appear between the deletion's last check and its tombstone.** `handleDeleteAccount` (`ownership.go:101`) takes `s.lockPlatformLifecycle(acct.Sqid)` right after the typed-name check (`:123-127`) and holds it to the end of the request, so on both paths (billing on: `deletionRefused`, `retireForDeletion`, `deleteAccountNow`, `ownership.go:136-147`; billing off: `requireFreshAuth`, `deleteAccountNow`) the re-run of `deletionRefused`, the tombstone and `DeleteAccount` all happen while customer create (same lock, Task 8 step 2) cannot run; a create that was waiting re-reads the platform afterwards and finds it gone. It is taken for every account, platform or not: the key is the account being deleted, so unrelated deletions never contend.
-Lock order (Astra r2-1), stated in `lockPlatformLifecycle`'s comment and beside the billing branch of `handleDeleteAccount`: **platform lifecycle → account/plan → billing hold.** Deletion takes lifecycle, then billing (`retireForDeletion`, `billingretire.go:228`), and no account/plan lock: `deleteAccountNow` and its callees take none. `startDomainPurchase` takes account/plan (`domainbuy.go:131`), then billing (`:165`), and never lifecycle. Customer creation takes lifecycle only. So no two paths take a pair of these locks in opposite orders. The test seam `deleteBeforeTombstone func()` (nil in production) is called after `deleteAccountNow`'s re-check, before `tombstoneAccount`; it runs while lifecycle and (billing on) the billing hold are held.
+Lock order (Astra r2-1), stated in `lockPlatformLifecycle`'s comment and beside the billing branch of `handleDeleteAccount`: **platform lifecycle → account/plan → billing hold.** Deletion takes lifecycle, then billing (`retireForDeletion`, `billingretire.go:228`), and no account/plan lock: `deleteAccountNow` and its callees take none. `startDomainPurchase` takes account/plan (`domainbuy.go:131`), then billing (`:165`), and never lifecycle. Customer creation takes lifecycle only. So no two paths take a pair of these locks in opposite orders. Two test seams, nil in production: `deleteNowEnter func()` is the **first statement of `deleteAccountNow`**, before its re-run of `deletionRefused` (the second app check), which is exactly where round 1 put `s.lockAccount` (Astra r3-2); `deleteBeforeTombstone func()` is called after that re-check, before `tombstoneAccount`. Both run while the lifecycle lock and (billing on) the billing hold are held.
To let the test observe the interleaving without sleeps, `holdBilling` (`billinghold.go:81`) and `lockAccount` (`applocks.go`) emit `lockEvent("billing"|"account", sqid, lockWaiting|lockHeld|lockReleased)` around their acquisition, the existing `lifetimeLockHook` seam (`lifetimes.go:171-179`); with no hook installed this is one atomic load.
@@ -712,8 +707,6 @@ func TestCustomerRenameRewritesTheManifest(t *testing.T) // row and mani
func TestCustomerPlanChangeGoesThroughTheTransition(t *testing.T) // personal -> free with a lapse cap over: MarkLapse set, plan row source platform
func TestCustomerPlanChangeStaysInsideTheGrant(t *testing.T) // plan dropped from the grant -> 400 create.plan
func TestCustomerPlanChangeRefusesOperatorRows(t *testing.T) // operator SetAccountPlan source operator -> 409 update.operator_plan, row unchanged
-func TestCustomerDeleteTombstonesAnUnclaimedAccount(t *testing.T) // manifest Deleted(); AccountBySqid nil; LinkedCustomers empty
-func TestCustomerDeleteRefusesClaimedOrAppHolding(t *testing.T) // AddMember owner -> 409 delete.claimed; CreateAppIn -> 409 delete.apps; manifest untouched
func TestPlatformAccountDeletionRefusedWithCustomers(t *testing.T) // browser POST delete on the platform account -> flash delete.platform_has_customers, manifest not tombstoned
func TestLinkedAccountBrowserDeletionRefused(t *testing.T) // console member owner of a customer -> flash delete.linked
func TestPlatformDeletionWaitsForAnInFlightCreate(t *testing.T) { // (Astra r1-3): creation first
@@ -727,19 +720,25 @@ func TestCreateWaitsForAnInFlightPlatformDeletion(t *testing.T) { // (Astra r1-3
// waits; release the delete -> platform deleted; the create answers the stdlib 404; no customer manifest and
// no pending mint exist.
}
-func TestDeletionAndDomainPurchaseDoNotDeadlock(t *testing.T) { // (Astra r2-1), the reviewer's interleaving
- // Fixture with billing on (the domain-buy test fake billing and registrar), plans on (so planLock is lockAccount),
- // an account with one app. lifetimeLockHook records events onto a channel.
- // 1. Browser delete of the account runs in a goroutine; deleteBeforeTombstone blocks it. It now holds the
- // lifecycle lock and the billing hold.
- // 2. startDomainPurchase for the same account runs in a goroutine. Wait for ("account", sqid, held) and then
- // ("billing", sqid, waiting) from it: it holds the account lock and is waiting on billing, the reviewer's state.
- // 3. Release the delete. Its done channel closes: it never emitted ("account", sqid, waiting).
- // (With the r1-3 placement it would have waited on the account lock here, forever.)
- // 4. The purchase's done channel closes: it got the billing hold after the delete released it and answers a
- // refusal (the account is gone), with no purchase row and no billing customer.
- // Every wait is a select on the event or done channel against one 10 s guard timer, so a deadlock fails the
- // test instead of hanging it; there is no sleep. Run it 20 times in a loop inside the test.
+func TestDeletionAndDomainPurchaseDoNotDeadlock(t *testing.T) { // (Astra r2-1, r3-2), the reviewer's interleaving
+ // Fixture with billing on (the domain-buy test fake billing and registrar) and plans on (so planLock is
+ // lockAccount). The account starts EMPTY, so deletion passes its first deletionRefused and takes the billing hold.
+ // lifetimeLockHook records events onto a channel.
+ // 1. Browser delete of the account runs in a goroutine; deleteNowEnter blocks it. It now holds the lifecycle
+ // lock and the billing hold, and has not reached deleteAccountNow's second app check.
+ // 2. Create an app in the account through the CLI create door (apicli.go:555 takes planLock, which the deletion
+ // does not hold): it completes. The account now holds an app.
+ // 3. startDomainPurchase for that app runs in a goroutine. Wait for ("account", sqid, held) and then
+ // ("billing", sqid, waiting) from it: it holds the account lock and waits on billing.
+ // 4. Release deleteNowEnter. The deletion's done channel closes: its re-run of deletionRefused sees the app and
+ // refuses; the manifest is NOT tombstoned (domains manifest has no DeletedAt); the account row is live; it
+ // never emitted ("account", sqid, waiting); its deferred release frees the billing hold.
+ // 5. The purchase's done channel closes: it took the billing hold and finished (an answer from the fake billing,
+ // not a lock timeout).
+ // Every wait is a select on an event or done channel against one 10 s guard timer, so a deadlock fails the test
+ // instead of hanging it; there is no sleep. Run the sequence 20 times inside the test.
+ // Mutation check, recorded in the task report: put `defer s.lockAccount(acct.Sqid)()` back as the line after
+ // deleteNowEnter in deleteAccountNow; the test must fail at step 4's guard. Then remove it again.
}
func TestLockOrderLifecycleAccountBilling(t *testing.T) { // (Astra r2-1)
// Drive one request at a time (sequentially, so every event on a sqid belongs to that request): a customer
@@ -749,14 +748,14 @@ func TestLockOrderLifecycleAccountBilling(t *testing.T) { // (Astra r2-1)
}
```
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestCustomerRename|TestCustomerPlanChange|TestCustomerDelete|TestPlatformAccountDeletionRefused|TestLinkedAccountBrowserDeletionRefused|TestPlatformDeletionWaitsForAnInFlightCreate|TestCreateWaitsForAnInFlightPlatformDeletion|TestDeletionAndDomainPurchaseDoNotDeadlock|TestLockOrderLifecycleAccountBilling' -count=1`. Expected: FAIL.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestCustomerRename|TestCustomerPlanChange|TestPlatformAccountDeletionRefused|TestLinkedAccountBrowserDeletionRefused|TestPlatformDeletionWaitsForAnInFlightCreate|TestCreateWaitsForAnInFlightPlatformDeletion|TestDeletionAndDomainPurchaseDoNotDeadlock|TestLockOrderLifecycleAccountBilling' -count=1`. Expected: FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4: Run** the Step 2 command plus `-run 'TestDeleteAccount|TestHandleDeleteAccount|TestAccountPlan|TestDomainBuy|TestBillingRetire|TestBillingHold'`. Expected: PASS.
- [ ] **Step 5: Commit**
```bash
git add internal/console/apiplatformcustomers*.go internal/console/routedecls.go internal/console/ownership.go internal/console/applocks.go internal/console/billinghold.go internal/console/platformlinked*.go internal/console/platform_copy.go
-git commit -m "console: platforms rename, re-plan and delete unclaimed customers"
+git commit -m "console: platforms rename and re-plan customers; guard platform deletion"
```
---
@@ -825,7 +824,7 @@ func TestCustomerCredentialRefusedOnASecondCustomer(t *testing.T) { // (Astra r1
func TestCustomerCredentialExpiryBoundary(t *testing.T) // default TTL 1h; at expires_at ok; +1s refused; ttl 25h -> 400 cred.ttl; 30s -> 400
func TestCustomerCredentialRefusedAfterRevokeAndLinkGone(t *testing.T)
// RevokePlatformGrant -> 401; re-grant -> still 401 (its generation ended; no cli_tokens row was touched);
- // a fresh credential (new generation) works, then DeleteUnclaimedCustomer -> 401
+ // a fresh credential (new generation) works, then Store.DeleteAccount on the customer -> 401 (the link check)
func TestCustomerCredentialMintPausedAcrossRevokeAndRegrant(t *testing.T) { // (Astra r1-2)
// platformCredentialBeforeInsert blocks; while the mint (by platform credential P, gen 1) waits: RevokePlatformGrant,
// PutPlatformGrant (gen 2, active). Release: 403 door.revoked; no kind 'platform' row exists for the customer.
@@ -843,10 +842,15 @@ func TestPersonalTokenListOmitsCustomerCredentials(t *testing.T)
- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestCustomerCredential|TestUnknownTokenKindStillRefused|TestPersonalTokenListOmitsCustomerCredentials' -count=1`. Expected: FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4: Run** the Step 2 command plus `-run 'TestCLIPrincipal|TestServicePrincipal|TestPlatformDoorsTakeOnlyThePlatformRole|TestNoRoleReachesAMintFleetOrPolicyDoor'`. Expected: PASS.
-- [ ] **Step 5: Commit**
+- [ ] **Step 5: Write the rule and its one exception into AGENTS.md (Paul r3).** AGENTS.md does not state the rule today; it lives in code comments. Add a bullet to "Rules this repo has paid for":
+
+ > **A credential never mints a credential, with one exception.** The services, instance-token, door-key and email-credential doors are closed to every role (`closedDoors`, `mintDoors` in `internal/console/svcroutes_test.go`), so no credential can mint, rotate or revoke one. The one exception is the platform door `POST /api/cli/platform/{account}/customers/{customer}/credentials` (platform accounts spec §6.2, accepted by Paul 2026-11-19). Its limits: only the `platform` role reaches it; what it mints is bound to one customer account linked to that platform; it lives at most 24 hours; the minted credential (role Publish or Deploy, kind `platform`) can never reach any mint door; and it is checked against the platform's grant generation on every request, so revoking the grant ends it. Widening any of these needs Paul.
+
+ Point the four code comments that state the rule (`apicli.go:342`, `svcroutes_test.go:133`, `routedecls.go:762`, `routedecls.go:934`) at that AGENTS.md entry with one line each, and add `TestCustomerCredentialNeverReachesPersonOrMintDoors` to the comment beside `mintDoors` as the exception's pin. Expected: `go test ./internal/console/ -run 'TestNoRoleReachesAMintFleetOrPolicyDoor|TestCustomerCredentialNeverReachesPersonOrMintDoors' -count=1` PASS.
+- [ ] **Step 6: Commit**
```bash
-git add internal/console/platform_credentials*.go internal/console/apiplatformcredentials.go internal/console/authstore.go internal/console/svcprincipal.go internal/console/apicli.go internal/console/routedecls.go internal/console/platform_copy.go
+git add AGENTS.md internal/console/platform_credentials*.go internal/console/apiplatformcredentials.go internal/console/authstore.go internal/console/svcprincipal.go internal/console/apicli.go internal/console/routedecls.go internal/console/svcroutes_test.go internal/console/platform_copy.go
git commit -m "console: short-lived per-customer credentials minted by a platform"
```
@@ -860,9 +864,9 @@ git commit -m "console: short-lived per-customer credentials minted by a platfor
**Interfaces:**
- Consumes: the wire shapes of Tasks 8-10 (mirror them as root-package types, as `accounts_plan.go` mirrors the plan door).
-- Produces: `func platformCommand() *clireg.Node` (Audience `clireg.Customer`) with children `customers` → `create`, `list`, `show`, `update`, `delete`, and `credentials` → `mint`; each leaf `raw(name, cust, runPlatformX)` calling `runPlatformXWithSession(ctx, sess *apiSession, args []string, out io.Writer) error`. Session methods on `*apiSession` in `platform_cli.go`: `platformCustomers(ctx, platform, ref string)`, `platformCustomer`, `createPlatformCustomer`, `updatePlatformCustomer`, `deletePlatformCustomer`, `mintPlatformCredential`.
+- Produces: `func platformCommand() *clireg.Node` (Audience `clireg.Customer`) with children `customers` → `create`, `list`, `show`, `update` (no `delete` in slice 1, Paul r3), and `credentials` → `mint`; each leaf `raw(name, cust, runPlatformX)` calling `runPlatformXWithSession(ctx, sess *apiSession, args []string, out io.Writer) error`. Session methods on `*apiSession` in `platform_cli.go`: `platformCustomers(ctx, platform, ref string)`, `platformCustomer`, `createPlatformCustomer`, `updatePlatformCustomer`, `mintPlatformCredential`.
-Flags: every verb takes `--platform <sqid>` (required) and `--console`; `show`, `update`, `delete` and `credentials mint` take `--customer <sqid>` or `--ref <ref>` (exactly one; `--ref` resolves through `GET ...customers?ref=`); `create` takes `--name` (required), `--ref`, `--plan`; `update` takes `--name`, `--plan`, `--reason`; `mint` takes `--role` (publish|deploy, default publish), `--app`, `--rungs`, `--ttl` (Go duration, default 1h); `list`, `show`, `create`, `mint` take `--json` (prints the door's JSON reply, indented). Sessions come from `resolveMode`, so `CARLOS_SERVICE_TOKEN` with `CARLOS_CONSOLE` works with no login. Human output is the Task 1 mocks, built from the copy constants.
+Flags: every verb takes `--platform <sqid>` (required) and `--console`; `show`, `update` and `credentials mint` take `--customer <sqid>` or `--ref <ref>` (exactly one; `--ref` resolves through `GET ...customers?ref=`); `create` takes `--name` (required), `--ref`, `--plan`; `update` takes `--name`, `--plan`, `--reason`; `mint` takes `--role` (publish|deploy, default publish), `--app`, `--rungs`, `--ttl` (Go duration, default 1h); `list`, `show`, `create`, `mint` take `--json` (prints the door's JSON reply, indented). Sessions come from `resolveMode`, so `CARLOS_SERVICE_TOKEN` with `CARLOS_CONSOLE` works with no login. Human output is the Task 1 mocks, built from the copy constants.
- [ ] **Step 1: Write the failing tests** (an `httptest` console fake recording requests)
@@ -879,7 +883,7 @@ func TestPlatformCommandsNeedAConsole(t *testing.T) // CARLOS_DEPLOYM
```
- [ ] **Step 2: Run** `go test . -run 'TestPlatformCustomers|TestPlatformCustomerFlags|TestPlatformCredentialsMint|TestPlatformCommandsNeedAConsole' -count=1`. Expected: FAIL.
-- [ ] **Step 3: Implement**; register `platformCommand()` after `servicesCommand()` in `commands.go:155`. Parity rows: `platform-customers-list platform gap platform customers list ; platform customers show wp-platform-customers ` plus a `packages.tsv` row `wp-platform-customers The platform account's Customers section (platform accounts slice 3) `; `platform-customers-manage platform cli-only platform customers create ; platform customers update ; platform customers delete ; platform credentials mint A platform's own servers act through the API and CLI; v1 has no pages that act in a customer account.` Adjust to `internal/parity`'s rules if it refuses a column. Docs: `### carlos platform customers` and `### carlos platform credentials`. Run `make parity-doc`.
+- [ ] **Step 3: Implement**; register `platformCommand()` after `servicesCommand()` in `commands.go:155`. Parity rows: `platform-customers-list platform gap platform customers list ; platform customers show wp-platform-customers ` plus a `packages.tsv` row `wp-platform-customers The platform account's Customers section (platform accounts slice 3) `; `platform-customers-manage platform cli-only platform customers create ; platform customers update ; platform credentials mint A platform's own servers act through the API and CLI; v1 has no pages that act in a customer account.` Adjust to `internal/parity`'s rules if it refuses a column. Docs: `### carlos platform customers` and `### carlos platform credentials`. Run `make parity-doc`.
- [ ] **Step 4: Run** `go test . -run 'TestPlatform|TestCLIProjection|TestCLIGolden' -count=1` and `go test ./internal/parity/ ./internal/docsite/ -count=1`. Expected: PASS. If `TestCLIGolden` asks for a record, follow its header (`clireg_golden_test.go:30`).
- [ ] **Step 5: Commit**
@@ -1095,15 +1099,12 @@ Every row is pending copy review (Task 15). `%s`/`%d` are filled as named. CLI e
| create.ref | a customer reference is 1 to 64 letters, digits, dots, colons, hyphens or underscores |
| create.plan | this platform can put customer accounts on these plans: %s |
| create.no_catalog_plan | this console has no plan catalog, so leave out the plan |
-| create.cap | this platform has %d customer accounts, the most its grant allows. delete one, or ask the operator for more |
+| create.cap | this platform has %d customer accounts, the most its grant allows. ask the operator for more |
| create.rate | too many customer accounts were created today. try again tomorrow, or ask the operator |
| create.failed | could not create the customer account. try again |
| update.empty | nothing to change. pass a new name, a new plan, or both |
| update.operator_plan | an operator set this account’s plan. ask them to change it |
| update.failed | could not change the customer account. try again |
-| delete.claimed | someone owns this customer account now, so it can’t be deleted from here |
-| delete.apps | this customer account still has %d apps. delete them first |
-| delete.failed | could not delete the customer account, and nothing was deleted. try again |
| cred.role | a customer credential is publish for the whole account, or deploy for one app with its rungs |
| cred.ttl | a customer credential lasts from 1 minute to 24 hours |
| cred.failed | could not mint the credential. try again |
@@ -1117,7 +1118,7 @@ Every row is pending copy review (Task 15). `%s`/`%d` are filled as named. CLI e
| billing notice.platform | billingpage_copy.go | Your plan is managed by %s. |
| billing notice.platform_generic | billingpage_copy.go | This account’s plan is managed by the platform account that runs it. |
| domainbuy platform | domainbuy_copy.go | buying a domain isn’t available on an account run by %s. attach a domain registered elsewhere instead |
-| delete.platform_has_customers | platform_copy.go | This account runs %d customer accounts. Delete them first. |
+| delete.platform_has_customers | platform_copy.go | This account runs %d customer accounts, so it can’t be deleted. |
| delete.linked | platform_copy.go | This account is run by %s. Ask them to delete it. |
**Email to a platform's owners** (`plancaps_copy.go`, `planNoticeCopy`; the per-cap lines reuse the approved `email.warn`, `email.over`, `email.lapse_grace`, `email.lapse_off`)
@@ -1200,7 +1201,6 @@ Every row is pending copy review (Task 15). `%s`/`%d` are filled as named. CLI e
| Exists | %s (%s) already exists for reference %s |
| Renamed | %s (%s) is now called %s |
| Replanned | %s (%s) is now on the %s plan |
-| Deleted | deleted %s (%s) |
| Minted | minted a %s credential for %s (%s), valid until %s |
| MintedToken | token |
| MintedUse | use it as CARLOS_SERVICE_TOKEN with --account %s |
@@ -1213,7 +1213,7 @@ Cap names in usage reuse the approved `cliPlanCopyLimit*` labels (apps and insta
| id | text |
|---|---|
| docs.accounts_platform | `### carlos accounts platform`, then: Shows an account’s platform grant, or changes it. A platform account can create customer accounts and deploy into them for its own customers. It is a deployment-operator command. Then the three examples: show, `--grant --max-customers 50 --plans free,personal --default-plan free --reason "agreed by email"`, `--revoke --reason "..."`. Then: "Turning platform access off stops the platform’s credentials at once. Its customers’ sites keep serving." |
-| docs.platform_customers | `### carlos platform customers`, then: Creates and manages the customer accounts a platform account runs. Each customer account is a full account of its own, with nobody signed in to it. Examples with `--platform bcd`: create `--name shop --ref 4812`, list, show `--ref 4812`, update `--customer bdf --plan personal`, delete `--customer bdf`. Then: "`--ref` is your own id for the customer. Creating again with the same ref returns the same account. An account someone owns, or one that still has apps, can’t be deleted here." |
+| docs.platform_customers | `### carlos platform customers`, then: Creates and manages the customer accounts a platform account runs. Each customer account is a full account of its own, with nobody signed in to it. Examples with `--platform bcd`: create `--name shop --ref 4812`, list, show `--ref 4812`, update `--customer bdf --plan personal`. Then: "`--ref` is your own id for the customer. Creating again with the same ref returns the same account." |
| docs.platform_credentials | `### carlos platform credentials`, then: Mints a short-lived credential for one customer account, for deploying into it. Example: `carlos platform credentials mint --platform bcd --customer bdf --json`. Then: "It lasts an hour unless you pass `--ttl`, up to 24 hours. It works only in that one account, and stops working when the platform’s access is turned off. Use it as `CARLOS_SERVICE_TOKEN`." |
(The docs rows describe the prose; the heading lines are fixed by `internal/docsite`. Write the paragraphs from these sentences without adding claims, and put them through the same copy review.)
@@ -1230,7 +1230,7 @@ Cap names in usage reuse the approved `cliPlanCopyLimit*` labels (apps and insta
- D6. Revoking a grant ends its generation; every platform-role and per-customer credential is bound to the generation it was minted in, so a re-grant restores no old credential (Astra r1-2). The same transaction marks those rows revoked so credential management agrees (Astra r2-2).
- D14. Customer creation records a pending mint before touching the bucket; pending mints count against `max_customers` and hold their ref until finished (Astra r1-1).
- D15. Platform deletion and customer creation serialize on a dedicated platform lifecycle lock; the order is lifecycle → account/plan → billing (Astra r1-3, r2-1).
-- D7. Budgets: customer create spends `allowCreate` (service 100 a day, person 10) except a ref hit, which spends nothing; update, delete and credential mint spend `allowWrite`.
+- D7. Budgets: customer create spends `allowCreate` (service 100 a day, person 10) except a ref hit, which spends nothing; update and credential mint spend `allowWrite`.
- D8. TTL bounds 1 minute to 24 hours; `max_customers` 1 to 10000. Without a plan catalog a grant has no plans and customers get no plan row.
- D9. Linked accounts never take the launch sponsorship.
- D10. Per-customer credentials are not listed in the customer's services list or the minter's tokens page in slice 1; an owner can still revoke one by id.
@@ -1240,6 +1240,8 @@ Cap names in usage reuse the approved `cliPlanCopyLimit*` labels (apps and insta
## Spec gaps and contradictions found
+- §6.1 lists `DELETE .../customers/{customer}` and §11 puts it in slice 1. Paul moved it to slice 2 on 2026-11-19 (Astra r3-1); see the hand-offs.
+
- §3 and §6.3: `carlos deploy` with a Publish credential fails before the first-host step (`GET instances` excludes Publish), and the `domains kind:"static"` route cannot mint an app's platform host where `CONSOLE_RESERVE_PLATFORM_DOMAINS=true`. See D3.
- §5.1/§5.2: the link survives a console rebuild, but the grant (and every account's plan row) is console-only, so a rebuilt console keeps links with no grant: the platform is refused until the operator grants again. Accepted for v1; noted for the operator runbook. Without D4, idempotent create would break on rebuild too.
- §6.1/AGENTS.md: the per-customer credential door is a credential mint reached by a credential, against the standing "a credential may never mint a credential" cut. The spec's A2 intends it; the plan names it as the one exception and pins it narrower than its minter.
@@ -1249,7 +1251,14 @@ Cap names in usage reuse the approved `cliPlanCopyLimit*` labels (apps and insta
## Slice 2/3 hand-offs
Slice 2 (claim and leave) needs from slice 1:
-- `AccountPlatform`, `LinkedCustomer.Owners` (claimed = owners > 0), `DeleteUnclaimedCustomer`'s owner check, and `ErrCustomerClaimed`. Accepting a claim must hold `s.lockPlatformLifecycle(customer.Sqid)`, the lock the platform's delete door holds across its owner check and tombstone, or a claim can land between them; and it must take it before any account/plan lock or billing hold (the r2-1 order).
+- `AccountPlatform`, `LinkedCustomer.Owners` (claimed = owners > 0), `PendingPlatformMints`, and `lockPlatformLifecycle` with its order: **platform lifecycle → account/plan → billing hold** (Astra r2-1).
+- **Customer deletion moved here from slice 1 (Paul r3, because of Astra r3-1).** Slice 1 has no door that deletes a customer account; `handleDeleteAccount` refuses a linked account (D11) and refuses a platform account with customers. The platform `DELETE .../customers/{customer}` door, `carlos platform customers delete` and the store's delete-unclaimed method are slice 2's to build, and the design must close r3-1: an account must never be tombstoned while a concurrent create adds an app to it. So:
+ - retirement and app creation share **one exclusion**. Today app creation takes only `planLock` (`apicli.go:555`), which is the account lock only when plans are on, so the design must hold with and without a plan catalog;
+ - app creation **re-checks that the account is live** after taking that exclusion and before it writes;
+ - the order stays **lifecycle → account → billing**. Taking the account lock while holding billing is the r2-1 deadlock (`domainbuy.go:131` then `:165`);
+ - the delete refuses an account with any owner membership (claimed) or any app row, re-checked inside the transaction that marks it deleted, and tombstones the bucket manifest only after the checks pass under the exclusion;
+ - accepting a claim takes the same exclusion as the delete door, or a claim can land between the owner check and the tombstone;
+ - witnesses: both interleavings (app create during the delete's checks, and the delete during an app create), with and without a plan catalog, plus the claim interleaving.
- Leave/release: clear `accounts.platform` and `platform_ref`, rewrite the manifest without `platform`/`platform_ref`/`platform_mint` keeping `owner` (a `domains` CAS helper beside `RenameAccountManifest`), revoke kind-platform rows for the account, set the plan row to the catalog default, and lift D11's browser deletion refusal and Task 13's billing refusal for the account (both read `AccountPlatform`, so clearing the column is enough).
- Claim must write `owner` into the manifest and teach materialization to adopt a late owner for linked accounts only (spec §7.4); `materializeOwner`'s birth-only rule is untouched by slice 1.
- How per-customer credentials appear to a claimed customer (D10): `ServicePrincipals` would add `cliKindPlatform`.