carlos / platform Public

plan: platform accounts slice 1, pre-flight rulings

Applies the controller's rulings on the 17 pre-flight conflicts:

- C1: test seams and the platform lock in one platformSeams struct,
  embedded in Server with one line in server.go; the global lock hook
  is the accepted exception.
- C2: Task 8 lists and commits platform_store.go, applocks.go,
  platform_seams.go and server.go.
- C3: Task 8 restores and runs the management test's GET assertion.
- C4: ended-generation tests un-revoke the swept row with raw SQL;
  false "no cli_tokens row was touched" comment fixed.
- C5: credential mint reply carries the customer name.
- C6: Task 13 lists and commits its copy files; root test for the
  platform plan source.
- C7: each task lists and commits the copy files it changes.
- C8: Task 15's root test run is anchored; no e2e locally.
- C9: platform:<sqid>/<name> actor for kind platform credentials only.
- C10: each write door answers its own failure row; door.rate,
  cred.role mapped.
- C11: db-no-context ratchet in Global Constraints, *Context forms.
- C12: grant reply carries generation; time fields are *time.Time.
- C13: revoke counts only unexpired credentials.
- C14: closed-door pin raised from 103 to 106.
- C15: accounts.platform_mint; count skips materialized pending mints;
  store and restart tests.
- C16: credential door comment states its bounds.
- C17: copy rows and mocks for no-catalog create and no-plan grant.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 2ff79539928c75052f8994afa48b7a502ea810d5 parent 0f9c1e8
1 file changed, +139 −64
  • docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md +139 −64

Intent

Attributed to this commit: 9.78 g CO₂e (1,167,763 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 6d1046e9e..24890747c 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 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.
+**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 `accounts` columns (`platform`, `platform_ref`, and the mint id `platform_mint`, pre-flight C15) 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`).
@@ -33,6 +33,28 @@ Round 3 (Astra, findings `docs/superpowers/plans/ASTRA-FINDINGS-platform-account
- **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.
+### Pre-flight rulings (controller)
+
+A read-only pre-flight scan at `0f9c1e81` found 17 conflicts (`.superpowers/sdd/2026-11-19-platform-accounts-1-platform-layer/preflight.md`); the controller ruled on each and the plan marks every change "(pre-flight Cn)".
+
+- **C1.** Test seams and the platform lock live in one `platformSeams` struct in the new `internal/console/platform_seams.go`, embedded in `Server` with one line in `server.go` (listed in Task 8). The package-global `lifetimeLockHook` used for lock events is the accepted exception to the Server-field seam rule.
+- **C2.** Task 8's Files and commit now name `platform_store.go`, `applocks.go`, `platform_seams.go` and `server.go`.
+- **C3.** Task 8 gains a step that restores the GET assertion in `TestRevokedPlatformCredentialIsGoneFromManagement` and runs it.
+- **C4.** The ended-generation tests (Tasks 7 and 10) un-revoke the swept row with raw SQL after the re-grant and still expect 401; Task 10's false "no cli_tokens row was touched" comment is corrected.
+- **C5.** The credential mint reply carries the customer's `name`; Task 11's fake and JSON test include it.
+- **C6.** Task 13 lists and commits `plancaps_copy.go`, `domainbuy_copy.go` and `accounts_plan_copy.go` (home of `cliPlanCopySourcePlatform`), with a root test for the platform source line.
+- **C7.** Each task adds its own copy rows: Task 7 lists and commits `platform_copy.go`; Tasks 9 and 10 list every file they commit.
+- **C8.** Task 15's root test run is anchored so it runs no e2e test.
+- **C9.** `auditActor` renders `platform:<sqid>/<name>` for kind `platform` (per-customer) credentials only; the platform-role credential stays `service:<sqid>/<name>` (Task 4's fixture stands).
+- **C10.** Each write door answers its own failure row; `allowWrite` is 429 `door.rate`, `ErrPlatformCredentialRole` is 400 `cred.role`, store errors are the door's `*.failed` row.
+- **C11.** Global Constraints gain the db-no-context ratchet: new queries use the `*Context` forms, including in `Store.DeleteAccount` and `claimRawNewServicePrincipalScoped`.
+- **C12.** The grant reply carries `generation`, and its time fields are `*time.Time`.
+- **C13.** `RevokePlatformGrant` revokes every live row but returns only unexpired ones, so "credentials stopped working" counts what did.
+- **C14.** Task 6 raises the closed-door pin in `TestEveryClosedDoorRefusesAServiceCredential` from 103 to 106 and names the three grant doors in its message.
+- **C15.** Materialization records the manifest's `platform_mint` on the account row; `LinkedCustomerCount` skips pending mints already materialized. New tests: a store-level count test (Task 4) and a restart list test (Task 8).
+- **C16.** The credential door's comment states its bounds instead of claiming it is narrower than its minter in every dimension.
+- **C17.** New copy rows for a create on a console with no plan catalog (`CreatedNoPlan`) and a grant with no plans (`audit.grant_no_plans`); those outputs omit the plan lines, and Task 1 mocks them for the UX pass.
+
## Global Constraints
House rules (from the brief, verbatim where they are rules):
@@ -58,10 +80,11 @@ From the spec and AGENTS.md:
- Lock order (Astra r2-1): platform lifecycle → account/plan (`lockAccount`, `planLock`) → billing hold. Nothing takes a lock earlier in this list while holding a later one.
- One live account per (platform, ref), and a pending mint uses capacity until it is finished (Astra r1-1).
- A refused request writes nothing: no manifest, no audit row, no serial bump (Astra r1-4).
-- Test seams are unexported `Server` func fields, nil in production, the `lapseBeforeConverge` precedent (`plangracepass.go:177`).
+- Test seams are unexported func fields, nil in production, the `lapseBeforeConverge` precedent (`plangracepass.go:177`). This plan's seams (and the platform lifecycle lock) are fields of one `platformSeams` struct in `internal/console/platform_seams.go`, embedded in `Server` (pre-flight C1). The one exception is the existing package-global `lifetimeLockHook` (`lifetimes.go:171-179`), which Task 9's lock events reuse.
+- The code-health ratchet's db-no-context rule (`.amadan/code-health.tsv`) counts non-context database calls per function. Every new query uses the `*Context` form (`QueryRowContext`, `ExecContext`, `QueryContext`, `BeginTx`); in a function with no ctx parameter (`Store.DeleteAccount`) pass `context.Background()` with a one-line comment (pre-flight C11).
- Linked accounts never get a Stripe customer: `holdBilling` refuses them, domain purchase refuses them, and they do not count towards anyone's free-account cap.
- Ordinary security gate order holds (AGENTS.md): session, CSRF, owner (byte-identical 404), `requireFreshAuth` last. A caller who cannot see an account gets the stdlib `404 page not found`.
-- Files: no Go file past 3,000 code lines and no function past 300 grows (`make code-health`). Do not add code to `internal/console/server.go`, `apimode.go`, or the bodies of `(*Store).migrate`, `runDeploy` or `handleAPIInstanceCreate`. New code goes in the new files named in each task.
+- Files: no Go file past 3,000 code lines and no function past 300 grows (`make code-health`). Do not add code to `internal/console/server.go` (except the one `platformSeams` embedding line in `Server`, pre-flight C1), `apimode.go`, or the bodies of `(*Store).migrate`, `runDeploy` or `handleAPIInstanceCreate`. New code goes in the new files named in each task.
- Every new `carlos` command gets a `docs/site/cli.md` heading and a `parity/parity.tsv` row in this branch; run `make parity-doc` after editing either.
- The root binary's sources change (`internal/domains`, `internal/svcrole`, the root package), so Task 15 runs the census card flow (AGENTS.md "The census").
@@ -87,6 +110,7 @@ Create:
- `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.
- `internal/console/platform_copy.go`: console copy, from the copy table.
+- `internal/console/platform_seams.go`: the `platformSeams` struct (the platform lifecycle lock and this plan's test seams), embedded in `Server` (pre-flight C1).
- Tests beside each: `platform_store_test.go`, `platform_credentials_test.go`, `apiplatformgrant_test.go`, `apiplatformcustomers_test.go`, `apiplatformhost_test.go`, `platformlinked_test.go`.
- Root: `accounts_platform.go`, `platform_cli.go`, `deploy_platformhost.go`, `platform_copy.go`, with `accounts_platform_test.go`, `platform_cli_test.go`, `platform_e2e_test.go`, and in Task 15 `approved_platform_accounts_copy_test.go`.
@@ -95,6 +119,7 @@ Modify (refs checked at `06603e71`):
- `internal/domains/mint.go` (manifest `:26-70`, `MintAccount :219`, `TombstoneAccount :268`).
- `internal/svcrole/svcrole.go` (`catalogue :83`, `Allow :125`, `Exactly :169`), its tests.
- `internal/console/store.go` (`migrate :167`; the feature-migration calls `:721-793`).
+- `internal/console/server.go` (`type Server struct :1025`): one line embedding `platformSeams` (pre-flight C1).
- `internal/console/authstore.go` (kinds `:390-395`, `CLITokensContext :861`).
- `internal/console/svcprincipal.go` (`Principal :58`, `CLIPrincipalContext :112`, mint rules `:355`).
- `internal/console/apicli.go` (`auditActor :118`).
@@ -152,6 +177,19 @@ token <the secret, shown once>
use it as CARLOS_SERVICE_TOKEN with --account bdf
```
+On a console with no plan catalog (decision D8; pre-flight C17), a grant has no plans and a customer gets no plan row, so these outputs omit the plan lines. They are part of this UX pass:
+
+```
+$ carlos accounts platform --account bcd
+bcd is a platform account
+ status on
+ customers 3 of 50
+ granted by ops@example.com on 19 November 2026: agreed by email
+
+$ carlos platform customers create --platform bcd --name shop --ref 4812
+created shop (bdf)
+```
+
- [ ] **Step 2: Fix what reads badly in the mocks and the copy table rows they use; record each change in a short "UX pass" note under this task.** Expected: every mock leads with its state line; no line needs a second read.
- [ ] **Step 3: Commit**
@@ -299,12 +337,12 @@ var (
func (s *Store) migratePlatformAccounts() error
func (s *Store) PlatformGrant(ctx context.Context, accountID int64) (*PlatformGrant, error) // nil, nil: none
func (s *Store) PutPlatformGrant(ctx context.Context, g PlatformGrant, now time.Time) error // upsert, state active, revoke fields cleared
-func (s *Store) RevokePlatformGrant(ctx context.Context, accountID int64, by, reason string, now time.Time) (credentials int, err error) // credentials: rows it marked revoked
+func (s *Store) RevokePlatformGrant(ctx context.Context, accountID int64, by, reason string, now time.Time) (credentials int, err error) // credentials: unexpired rows it marked revoked (pre-flight C13)
func (s *Store) AccountPlatform(ctx context.Context, accountID int64) (platformSqid, ref string, err error) // "" when unlinked or unknown
func (s *Store) LinkedCustomers(ctx context.Context, platformSqid string) ([]LinkedCustomer, error) // live only, by id
func (s *Store) LinkedCustomer(ctx context.Context, platformSqid, customerSqid string) (*LinkedCustomer, error) // nil when not this platform's
func (s *Store) LinkedCustomerByRef(ctx context.Context, platformSqid, ref string) (*LinkedCustomer, error)
-func (s *Store) LinkedCustomerCount(ctx context.Context, platformSqid string) (int, error) // live customers PLUS pending mints (Astra r1-1)
+func (s *Store) LinkedCustomerCount(ctx context.Context, platformSqid string) (int, error) // live customers PLUS pending mints not yet materialized (Astra r1-1, pre-flight C15)
// PendingMint is a customer create the console has promised and not finished (Astra r1-1).
type PendingMint struct {
MintID, Platform, Ref, Name, Plan, PlanReason, By string // MintID: 32 hex, crypto/rand
@@ -322,7 +360,7 @@ type NewLinkedAccount struct {
// row in place of a default one) and deletes the pending mint. Finishing twice is a no-op.
func (s *Store) CreateLinkedAccount(ctx context.Context, a NewLinkedAccount, now time.Time) error
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) EnsureLinkedAccount(id int64, sqid, name, platformSqid, ref, mintID string, created time.Time) (added bool, err error) // mintID: the manifest's platform_mint, kept on the row (pre-flight C15)
func (s *Store) RenameAccount(ctx context.Context, accountID int64, name string) error
```
@@ -343,6 +381,7 @@ CREATE TABLE IF NOT EXISTS platform_pending_mints (
CREATE UNIQUE INDEX IF NOT EXISTS platform_pending_mints_ref ON platform_pending_mints (platform, ref) WHERE ref != '';
ALTER TABLE accounts ADD COLUMN platform TEXT NOT NULL DEFAULT ''; -- platform account sqid
ALTER TABLE accounts ADD COLUMN platform_ref TEXT NOT NULL DEFAULT '';
+ALTER TABLE accounts ADD COLUMN platform_mint TEXT NOT NULL DEFAULT ''; -- the manifest's platform_mint (pre-flight C15)
ALTER TABLE cli_tokens ADD COLUMN platform_account_id INTEGER NOT NULL DEFAULT 0;
ALTER TABLE cli_tokens ADD COLUMN platform_generation INTEGER NOT NULL DEFAULT 0; -- Astra r1-2
CREATE INDEX IF NOT EXISTS accounts_platform ON accounts (platform) WHERE platform != '';
@@ -359,8 +398,10 @@ The link column holds the platform's sqid, not its id, so materialization (Task
func TestPlatformGrantRoundTrip(t *testing.T) // Put, read back every field; second Put re-grants (state active, revoke fields "", generation unchanged)
func TestRevokePlatformGrantEndsItsGeneration(t *testing.T) { // (Astra r1-2, r2-2)
// grant gen 1; rows: kind 'platform' platform_account_id=P (2), kind 'service' role 'platform' account_id=P (1),
- // kind 'service' role 'publish' account_id=P (1), kind 'platform' platform_account_id=Q (1).
- // RevokePlatformGrant(P) returns 3, generation 2, state "revoked"; exactly those three rows have revoked_at != 0.
+ // kind 'service' role 'publish' account_id=P (1), kind 'platform' platform_account_id=Q (1),
+ // kind 'platform' platform_account_id=P already expired (1; pre-flight C13).
+ // RevokePlatformGrant(P) returns 3, generation 2, state "revoked"; those three rows and the expired one
+ // have revoked_at != 0 (the expired row is revoked but not counted); the publish and Q rows are untouched.
// PlatformGenerationLive(P, 1) false; PutPlatformGrant again: (P, 2) true, (P, 1) still false.
}
func TestPendingMintsCountAndHoldTheirRef(t *testing.T) { // (Astra r1-1)
@@ -372,6 +413,11 @@ func TestCreateLinkedAccountFinishesOverAMaterializedRow(t *testing.T) { // (Ast
// EnsureLinkedAccount made the row (default plan row from EnsureDefaultPlans); CreateLinkedAccount with the
// same sqid and platform: plan row now source platform, pending mint gone, still one account.
}
+func TestLinkedCustomerCountSkipsAMaterializedPendingMint(t *testing.T) { // (pre-flight C15)
+ // ReservePlatformMint(mintA, ref 4812) -> count 1; EnsureLinkedAccount(..., mintA, ...) (the restart birth)
+ // -> count still 1, not 2; CreateLinkedAccount(mintA) -> count 1, pending mints empty.
+ // A ref-less pending mint (ref "") materialized the same way also counts once.
+}
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.
@@ -388,12 +434,14 @@ func TestMigrateIsIdempotentWithPlatformTables(t *testing.T) // Open, Close, Ope
- [ ] **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.
- [ ] **Step 4: Implement the store.** Points the signatures leave open:
- - `CreateLinkedAccount` (Astra r1-1): one transaction. If a live row with this id, sqid and platform exists (materialized first), keep it and only replace a `default`-source plan row; otherwise insert the `accounts` row with `platform`, `platform_ref`. When `Plan != ""`, the plan row through `accountPlanUpsertSQL`/`accountPlanUpsertArgs` with `PlanSourcePlatform`. Then `DELETE FROM platform_pending_mints WHERE mint_id = ?`. No membership. No `sponsorOnInsertTx`: a linked account's plan is its platform's (decision D9).
+ - Every query in this file and every query added to an existing function uses the `*Context` forms (Global Constraints, pre-flight C11).
+ - `LinkedCustomerCount` (pre-flight C15): live accounts with `platform = ?` plus pending mints of that platform whose `mint_id` is not the `platform_mint` of a live account, so a mint materialized after a restart and not yet finished counts once.
+ - `CreateLinkedAccount` (Astra r1-1): one transaction. If a live row with this id, sqid and platform exists (materialized first), keep it and only replace a `default`-source plan row; otherwise insert the `accounts` row with `platform`, `platform_ref`, `platform_mint`. When `Plan != ""`, the plan row through `accountPlanUpsertSQL`/`accountPlanUpsertArgs` with `PlanSourcePlatform`. Then `DELETE FROM platform_pending_mints WHERE mint_id = ?`. No membership. No `sponsorOnInsertTx`: a linked account's plan is its platform's (decision D9).
- `ReservePlatformMint`: one transaction: a non-empty ref held by a live linked account of that platform or by another pending mint is `ErrPlatformRefTaken`; otherwise insert. The partial unique index backs it.
- `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).
- - `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.
+ - `EnsureLinkedAccount`: `EnsureAccount`'s body (share an unexported helper) plus the three columns (`platform`, `platform_ref`, `platform_mint`); 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). The function takes no ctx, so the new queries are `tx.QueryRowContext(context.Background(), ...)` with a one-line comment; the existing non-context calls stay as they are, so the ratchet's counts for it do not grow (pre-flight C11).
+ - `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 = ?))`. It returns only the rows that were still working: count, in the same transaction and before the update, those rows with `expires_at = 0 OR expires_at > now` (pre-flight C13). Expired rows are revoked too but not counted, because "credentials stopped working" must count what did. 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.
@@ -413,7 +461,7 @@ git commit -m "console: platform grants, pending mints and customer links"
- Test: `internal/console/materialize_test.go` (append)
**Interfaces:**
-- Consumes: `domains.AccountManifest.Platform/PlatformRef` (Task 2), `Store.EnsureLinkedAccount` (Task 4).
+- Consumes: `domains.AccountManifest.Platform/PlatformRef/PlatformMint` (Task 2), `Store.EnsureLinkedAccount` (Task 4).
- Produces: nothing new; behaviour only.
- [ ] **Step 1: Write the failing tests**
@@ -426,13 +474,14 @@ func TestMaterializeNeverLinksAnAccountAfterBirth(t *testing.T)
func TestMaterializeRefusesASelfOrOpsLink(t *testing.T)
// platform == own sqid, == Sqid(1), or not ValidSqid -> materialized unlinked (row exists, AccountPlatform "")
func TestMaterializeAdoptsAStrandedLinkedMint(t *testing.T)
- // domains.MintLinkedAccount with no console row, then MaterializeAccounts -> LinkedCustomers("bcd") contains it
+ // domains.MintLinkedAccount with no console row, then MaterializeAccounts -> LinkedCustomers("bcd") contains it,
+ // and its row's platform_mint is the manifest's (pre-flight C15)
func TestLinkedOwnerlessAccountReachesNobody(t *testing.T)
// after birth: AccountsFor(any address) never returns it; GET /a/<sqid>/ as a signed-in person is the stdlib 404
```
- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestMaterializeCarries|TestMaterializeNeverLinks|TestMaterializeRefusesASelf|TestMaterializeAdoptsAStranded|TestLinkedOwnerlessAccountReachesNobody' -count=1`. Expected: FAIL on the first four.
-- [ ] **Step 3: Implement.** In the birth branch only: when `m.Platform != ""` and it passes the same checks as `MintLinkedAccount` plus `m.Platform != m.Sqid`, call `EnsureLinkedAccount`; when it fails them, log one line naming the manifest and call `EnsureAccount` (unlinked and ownerless: unreachable, which is the safe side). The `a != nil` branch stays "settled": no link is ever adopted after birth, for the same reason `materializeOwner` runs once (its comment `:204-249` is the argument; add one sentence there saying the link follows the same rule).
+- [ ] **Step 3: Implement.** In the birth branch only: when `m.Platform != ""` and it passes the same checks as `MintLinkedAccount` plus `m.Platform != m.Sqid`, call `EnsureLinkedAccount` with `m.PlatformMint` (pre-flight C15); when it fails them, log one line naming the manifest and call `EnsureAccount` (unlinked and ownerless: unreachable, which is the safe side). The `a != nil` branch stays "settled": no link is ever adopted after birth, for the same reason `materializeOwner` runs once (its comment `:204-249` is the argument; add one sentence there saying the link follows the same rule).
- [ ] **Step 4: Run** the Step 2 command plus `-run 'TestMaterialize'`. Expected: PASS.
- [ ] **Step 5: Commit**
@@ -456,11 +505,11 @@ git commit -m "console: materialize the platform link at an account's birth only
`GET /api/cli/accounts/{account}/platform` → `handleAPIPlatformGrantGet`;
`PUT /api/cli/accounts/{account}/platform` → `handleAPIPlatformGrantPut`;
`POST /api/cli/accounts/{account}/platform/revoke` → `handleAPIPlatformGrantRevoke`.
- - Wire: `type platformGrantReply struct { Account string; Platform bool; State string; MaxCustomers, Customers int; Plans []string; DefaultPlan, Reason, GrantedBy string; GrantedAt time.Time; RevokedBy, RevokeReason string; RevokedAt time.Time }` (JSON snake_case, time fields `omitempty` via pointers); `type putPlatformGrantRequest struct { MaxCustomers int; Plans []string; DefaultPlan, Reason string }`; revoke body `{ "reason": string }`, reply `platformGrantReply` plus `"credentials_ended": int` (live credentials of the generation the revoke ended; Astra r1-2).
+ - Wire: `type platformGrantReply struct { Account string; Platform bool; State string; Generation int64; MaxCustomers, Customers int; Plans []string; DefaultPlan, Reason, GrantedBy string; GrantedAt *time.Time; RevokedBy, RevokeReason string; RevokedAt *time.Time }` (JSON snake_case; `generation` is the grant's current generation; the time fields are pointers with `omitempty`, pre-flight C12); `type putPlatformGrantRequest struct { MaxCustomers int; Plans []string; DefaultPlan, Reason string }`; revoke body `{ "reason": string }`, reply `platformGrantReply` plus `"credentials_ended": int` (unexpired credentials of the generation the revoke ended; Astra r1-2, pre-flight C13).
- `func (s *Server) platformGrantDoor(w http.ResponseWriter, r *http.Request) (addr string, acct *Account, ok bool)`: `accountPlanDoor`'s gate (`apiaccountplan.go:45`) without the catalog requirement: `cliUser`, `IsOperator` else stdlib 404, `AccountBySqid` else 404.
- CLI: `func runAccountsPlatformWithSession(ctx context.Context, sess *apiSession, args []string, out io.Writer) error`; `raw("platform", op, runAccountsPlatform)` in `accountsCommand`; session methods `platformGrant`, `putPlatformGrant`, `revokePlatformGrant` in `accounts_platform.go`.
-Rules the handler enforces, in order, on PUT: write budget (`allowWrite`) → reason non-empty (`grant.reason`) → `acct.ID == OpsAccountID` is 409 `grant.ops` → linked account (`AccountPlatform != ""`) is 409 `grant.linked` → `1 <= max_customers <= 10000` else 400 `grant.max` → with a catalog: `plans` non-empty, each in `cat.Plans`, `default_plan` among them, else 400 `grant.plans`; without one: `plans` and `default_plan` empty, else 400 `grant.no_catalog` → `PutPlatformGrant`, audit on the platform account (`platform-grant`, copy `audit.grant`). Revoke: reason required, no grant is 409 `grant.not_platform`, else `RevokePlatformGrant` and audit (`audit.revoke`). GET on an account with no grant answers 200 `{"platform": false}`.
+Rules the handler enforces, in order, on PUT: write budget (`allowWrite`) → reason non-empty (`grant.reason`) → `acct.ID == OpsAccountID` is 409 `grant.ops` → linked account (`AccountPlatform != ""`) is 409 `grant.linked` → `1 <= max_customers <= 10000` else 400 `grant.max` → with a catalog: `plans` non-empty, each in `cat.Plans`, `default_plan` among them, else 400 `grant.plans`; without one: `plans` and `default_plan` empty, else 400 `grant.no_catalog` → `PutPlatformGrant`, audit on the platform account (`platform-grant`, copy `audit.grant`, or `audit.grant_no_plans` for a grant with no plans, pre-flight C17). Revoke: reason required, no grant is 409 `grant.not_platform`, else `RevokePlatformGrant` and audit (`audit.revoke`). A store error on PUT or revoke is 500 `grant.failed` (pre-flight C10). GET on an account with no grant answers 200 `{"platform": false}`.
- [ ] **Step 1: Write the failing console tests** (`newConsoleFixture`, `planOperatorToken`, `examplePlanCatalog` from the existing tests)
@@ -469,16 +518,17 @@ func TestPlatformGrantDoorIsOperatorOnly(t *testing.T) // owner token
func TestPlatformGrantDoorRefusesOpsAndCustomerAccounts(t *testing.T) // 409 with platformCopy["grant.ops"], ["grant.linked"]
func TestPlatformGrantValidatesPlansAgainstTheCatalog(t *testing.T) // unknown plan, default not in plans, max 0 and 10001 -> 400s
func TestPlatformGrantWithoutACatalog(t *testing.T) // max only -> 200; plans set -> 400 grant.no_catalog
-func TestPlatformRevokeAndRegrant(t *testing.T) // revoke -> state revoked, credentials_ended counted, generation +1; PUT again -> active under the new generation
+func TestPlatformRevokeAndRegrant(t *testing.T) // revoke -> state revoked, credentials_ended counted, reply generation +1; PUT again -> active, reply generation unchanged from the revoke's
func TestPlatformGrantDoorsAreClosedToEveryRole(t *testing.T) // serviceToken(Admin) at each door -> the closed-door 403
```
- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestPlatformGrant|TestPlatformRevokeAndRegrant|TestEveryCLIDoorNamesItsRoles|TestEveryClosedDoorRefusesAServiceCredential' -count=1`. Expected: FAIL.
-- [ ] **Step 3: Implement the doors** in `apiplatformgrant.go`; add the three declarations beside the plan doors (`routedecls.go:996-997`) and the three patterns to `closedDoors` with a comment: "Granting platform status is an operator's act; no credential reaches it."
+- [ ] **Step 3: Implement the doors** in `apiplatformgrant.go`; add the three declarations beside the plan doors (`routedecls.go:996-997`) and the three patterns to `closedDoors` with a comment: "Granting platform status is an operator's act; no credential reaches it." In `TestEveryClosedDoorRefusesAServiceCredential` (`svcroutes_test.go:1761`) raise the pinned count from 103 to 106 and add "three platform grant doors" to its message (pre-flight C14).
- [ ] **Step 4: Write the failing CLI tests** (`accounts_platform_test.go`, the `accounts_plan_test.go` pattern: an `httptest` console fake and `runAccountsPlatformWithSession`)
```go
func TestAccountsPlatformShowPrintsTheGrant(t *testing.T) // output lines equal the Task 1 mock with the copy constants
+func TestAccountsPlatformShowWithoutPlans(t *testing.T) // reply with no plans: the Task 1 no-catalog mock, no plans or "new accounts start on" line (pre-flight C17)
func TestAccountsPlatformShowNotAPlatform(t *testing.T) // cliPlatformCopyNotPlatform
func TestAccountsPlatformGrantSendsTheGrant(t *testing.T) // PUT body {max_customers:50, plans:["free","personal"], default_plan:"free", reason:"r"}
func TestAccountsPlatformFlagRefusals(t *testing.T) // --grant with --revoke; --plans without --grant; --grant without --reason -> errors, nothing sent
@@ -498,7 +548,7 @@ git commit -m "accounts platform: operator grants and revokes platform status"
### Task 7: The platform credential through the services door
**Files:**
-- Modify: `internal/console/svcprincipal.go`, `internal/console/apiservices.go`, `internal/console/svcpage.go`
+- Modify: `internal/console/svcprincipal.go`, `internal/console/apiservices.go`, `internal/console/svcpage.go`, `internal/console/platform_copy.go` (the `svc.*` rows; pre-flight C7)
- Test: `internal/console/platform_credentials_test.go` (create)
**Interfaces:**
@@ -519,8 +569,9 @@ func TestPlatformCredentialTakesNoApp(t *testing.T) // {role:"platfor
func TestPlatformRoleRowWithAnAppDoesNotResolve(t *testing.T) // raw row kind service role platform app "x" -> CLIPrincipal ok == false
func TestRowWithAPlatformAccountIDOnlyResolvesAsPlatformKind(t *testing.T) // kind service role publish + platform_account_id 5 -> refused
func TestPlatformCredentialFromAnEndedGenerationIsRefused(t *testing.T) { // (Astra r1-2)
- // mint P under gen 1; RevokePlatformGrant; PutPlatformGrant (gen 2, active): P -> 401 at a platform door;
- // a fresh mint now resolves with PlatformGeneration 2.
+ // mint P under gen 1; RevokePlatformGrant; PutPlatformGrant (gen 2, active): P -> 401 at a platform door.
+ // Then un-revoke P's row with raw SQL (UPDATE cli_tokens SET revoked_at = 0 WHERE credential_id = ?), so only
+ // the generation check can refuse it: P -> still 401 (pre-flight C4). A fresh mint now resolves with PlatformGeneration 2.
}
func TestRevokedPlatformCredentialIsGoneFromManagement(t *testing.T) { // (Astra r2-2)
// owner mints "cms" (role platform); RevokePlatformGrant; PutPlatformGrant. Then, in order:
@@ -531,13 +582,13 @@ func TestRevokedPlatformCredentialIsGoneFromManagement(t *testing.T) { // (Astra
func TestBrowserMintFormDoesNotOfferPlatform(t *testing.T) // servicePane's ServiceRoles has no "platform"
```
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestServicesDoorMintsAPlatform|TestPlatformCredentialTakesNoApp|TestPlatformRoleRowWithAnApp|TestRowWithAPlatformAccountID|TestPlatformCredentialFromAnEndedGeneration|TestRevokedPlatformCredentialIsGoneFromManagement|TestBrowserMintFormDoesNotOfferPlatform' -count=1`. Expected: FAIL. (The management test needs Task 8's customer list door; until Task 8 lands, assert the new token's resolution instead of the GET, and Task 8's Step 4 re-runs it.)
-- [ ] **Step 3: Implement.** In `claimRawNewServicePrincipalScoped` (`svcprincipal.go:355`), beside the Service rule: Platform with an app is `ErrAppScopedPlatform`; inside the existing transaction, read the grant: missing or not active is `ErrNotPlatform`; otherwise insert with that generation (Astra r1-2). The services door is person-only, so a mint paused across a revoke and re-grant takes the generation current at its insert, which is the authority its owner holds then. Map both in `handleAPIServiceCreate` (`apiservices.go:256-299`) to 400 and 409 with the copy rows. Add `platform_account_id` and `platform_generation` to the `CLIPrincipalContext` SELECT and the checks above. `servicePane` skips `svcrole.Platform` when building `ServiceRoles`.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestServicesDoorMintsAPlatform|TestPlatformCredentialTakesNoApp|TestPlatformRoleRowWithAnApp|TestRowWithAPlatformAccountID|TestPlatformCredentialFromAnEndedGeneration|TestRevokedPlatformCredentialIsGoneFromManagement|TestBrowserMintFormDoesNotOfferPlatform' -count=1`. Expected: FAIL. (The management test needs Task 8's customer list door; until Task 8 lands, assert the new token's resolution instead of the GET; Task 8's Step 5 puts the GET back and runs it, pre-flight C3.)
+- [ ] **Step 3: Implement.** In `claimRawNewServicePrincipalScoped` (`svcprincipal.go:355`), beside the Service rule: Platform with an app is `ErrAppScopedPlatform`; inside the existing transaction, read the grant with `tx.QueryRowContext` (the function is on the db-no-context ratchet, pre-flight C11): missing or not active is `ErrNotPlatform`; otherwise insert with that generation (Astra r1-2). The services door is person-only, so a mint paused across a revoke and re-grant takes the generation current at its insert, which is the authority its owner holds then. Map both in `handleAPIServiceCreate` (`apiservices.go:256-299`) to 400 and 409 with the copy rows. Add `platform_account_id` and `platform_generation` to the `CLIPrincipalContext` SELECT and the checks above. `servicePane` skips `svcrole.Platform` when building `ServiceRoles`.
- [ ] **Step 4: Run** the Step 2 command plus `-run 'TestServiceCreate|TestCLIPrincipal'`. Expected: PASS.
- [ ] **Step 5: Commit**
```bash
-git add internal/console/svcprincipal.go internal/console/apiservices.go internal/console/svcpage.go internal/console/platform_credentials_test.go
+git add internal/console/svcprincipal.go internal/console/apiservices.go internal/console/svcpage.go internal/console/platform_copy.go internal/console/platform_credentials_test.go
git commit -m "console: mint platform credentials on granted accounts only"
```
@@ -546,8 +597,8 @@ git commit -m "console: mint platform credentials on granted accounts only"
### Task 8: The platform gate, customer create, list and show
**Files:**
-- Create: `internal/console/apiplatformcustomers.go`, `internal/console/apiplatformcustomers_test.go`
-- Modify: `internal/console/routedecls.go`, `internal/console/platform_copy.go`, `internal/console/platform_store.go` (`LinkedCustomerPlans`)
+- Create: `internal/console/apiplatformcustomers.go`, `internal/console/apiplatformcustomers_test.go`, `internal/console/platform_seams.go`
+- Modify: `internal/console/routedecls.go`, `internal/console/platform_copy.go`, `internal/console/platform_store.go` (`LinkedCustomerPlans`), `internal/console/applocks.go` (`lockPlatformLifecycle`), `internal/console/server.go` (one line embedding `platformSeams` in `Server`; pre-flight C1, C2), `internal/console/platform_credentials_test.go` (Step 5, pre-flight C3)
**Interfaces:**
- Consumes: Tasks 2, 4, 7.
@@ -587,20 +638,25 @@ git commit -m "console: mint platform credentials on granted accounts only"
// finishPendingMints finishes every pending mint of the platform, oldest first: MintLinkedAccount
// with the mint's id (idempotent, Task 2), startNewAccountAnalytics, CreateLinkedAccount. The caller
// holds s.lockPlatformLifecycle(platform.Sqid). It stops at the first failure and returns it (Astra r1-1).
- // 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
+ // platform_seams.go (pre-flight C1): one struct, embedded in Server with a single line in server.go.
+ // Tasks 9 and 10 add their seams to it; nothing else of this plan becomes a Server field.
+ type platformSeams struct {
+ platformLocks keyedLocks // the platform lifecycle lock's table
+ // Test seam, nil in production: called with "lock" just before create takes the platform lock,
+ // "mint" before MintLinkedAccount and "finish" before CreateLinkedAccount; a non-nil error is
+ // treated as that step failing. A test may block in it to interleave.
+ platformMintStep func(step string) error
+ }
+ // lockPlatformLifecycle is the platform lifecycle lock (Astra r2-1), in applocks.go over
+ // platformSeams.platformLocks, 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 (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,
- // "mint" before MintLinkedAccount and "finish" before CreateLinkedAccount; a non-nil error is
- // treated as that step failing. A test may block in it to interleave.
- platformMintStep func(step string) error // field on Server
```
- List reply `{"platform": sqid, "max_customers": n, "count": n, "customers": [...]}`; create reply 201 `{"created": true, "customer": view}` or 200 `{"created": false, "customer": view}` on a ref hit.
-`platformGate` order: `apiPrincipalAccount` (service binding or membership; the family's 404) → a person who is not an owner gets 403 `door.not_owner` → `PlatformGrant` missing is 403 `door.not_platform`, revoked is 403 `door.revoked` (a service principal of an ended generation never gets here: resolution refused it, Task 7) → when the platform has pending mints, take `s.lockPlatformLifecycle(platform.Sqid)`, run `finishPendingMints`, and release the lock before the handler runs (the lock is not re-entrant; create takes it again in its step 2); on a read door a failure is logged and the request goes on, on a write door it is 502 `create.failed` (Astra r1-1). One indexed query when there are none. `platformCustomer`: `LinkedCustomer(platform.Sqid, PathValue("customer"))` nil is the stdlib 404, whatever the reason.
+`platformGate` order: `apiPrincipalAccount` (service binding or membership; the family's 404) → a person who is not an owner gets 403 `door.not_owner` → `PlatformGrant` missing is 403 `door.not_platform`, revoked is 403 `door.revoked` (a service principal of an ended generation never gets here: resolution refused it, Task 7) → when the platform has pending mints, take `s.lockPlatformLifecycle(platform.Sqid)`, run `finishPendingMints`, and release the lock before the handler runs (the lock is not re-entrant; create takes it again in its step 2); on a read door a failure is logged and the request goes on, on a write door it is 502 with that door's own failure row: `create.failed` for create, `update.failed` for update (Task 9), `cred.failed` for the credential mint (Task 10) (Astra r1-1, pre-flight C10). The gate takes the row from its caller. One indexed query when there are none. `platformCustomer`: `LinkedCustomer(platform.Sqid, PathValue("customer"))` nil is the stdlib 404, whatever the reason.
Create, in order. The invariant (Astra r1-1): **one live account per (platform, ref), and a promised account uses capacity from the moment it is promised until it exists.** It holds because the promise (`ReservePlatformMint`) is written before the bucket is touched, the bucket write is idempotent on the promise's id, and every path finishes promises before it reads capacity or refs.
@@ -651,6 +707,12 @@ func TestCustomerCreateConvergesAcrossARestart(t *testing.T) { // (Astra r1-1)
// (startup runs MaterializeAccounts, Task 5). GET .../customers -> exactly one customer, ref "4812",
// plan_source "platform" (the gate finished the mint over the materialized row); pending mints empty.
}
+func TestCustomerListCountsAMaterializedMintOnceAfterARestart(t *testing.T) { // (pre-flight C15)
+ // platformMintStep fails "finish": 502. Restart as above, with platformMintStep still failing "finish", so the
+ // gate's finish fails and the read door goes on: GET .../customers -> count 1 (not 2), one customer, ref "4812";
+ // the pending mint is still there. Clear the seam: a create with ref 4813 under max_customers 2 -> 201 (the
+ // materialized mint used one slot, not two).
+}
func TestCustomerCreateRechecksThePlatformUnderTheLock(t *testing.T) { // (Astra r1-3)
// the test holds s.lockPlatformLifecycle(p), starts a create and waits for platformMintStep("lock"), deletes the
// platform with Store.DeleteAccount (it has no customers yet), and releases: the create answers the stdlib 404
@@ -664,13 +726,14 @@ func TestCustomerDoorsHideOtherPlatformsCustomers(t *testing.T) // platform A's
func TestPlatformCredentialRefusedAtOrdinaryDoors(t *testing.T) // GET /api/cli/apps/<platform>, POST /api/cli/services/<platform> -> role refusal, not 200
```
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestPlatformDoor|TestAdminCredentialIsRefusedAtPlatformDoors|TestCustomerCreate|TestCustomerListAndShow|TestCustomerDoorsHide|TestPlatformCredentialRefusedAtOrdinaryDoors' -count=1`. Expected: FAIL. (The restart test opens a second `Server`; it needs no sockets, but if any fixture does, use `TMPDIR=/tmp/g`.)
-- [ ] **Step 3: Implement** `apiplatformcustomers.go` and the three declarations (a block after the services family, `routedecls.go:943-946`, with a comment naming spec §6.1 and that Admin is out on purpose).
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestPlatformDoor|TestAdminCredentialIsRefusedAtPlatformDoors|TestCustomerCreate|TestCustomerListAndShow|TestCustomerListCountsAMaterializedMint|TestCustomerDoorsHide|TestPlatformCredentialRefusedAtOrdinaryDoors' -count=1`. Expected: FAIL. (The restart test opens a second `Server`; it needs no sockets, but if any fixture does, use `TMPDIR=/tmp/g`.)
+- [ ] **Step 3: Implement** `platform_seams.go` (the `platformSeams` struct) and its one embedding line in `Server` (`server.go:1025`), `lockPlatformLifecycle` in `applocks.go`, `LinkedCustomerPlans` in `platform_store.go`, then `apiplatformcustomers.go` and the three declarations (a block after the services family, `routedecls.go:943-946`, with a comment naming spec §6.1 and that Admin is out on purpose).
- [ ] **Step 4: Run** the Step 2 command plus `-run 'TestEveryCLIDoorNamesItsRoles|TestNoRoleReachesAMintFleetOrPolicyDoor|TestRouteDeclsMatchRegistrations'`. Expected: PASS.
-- [ ] **Step 5: Commit**
+- [ ] **Step 5: Finish Task 7's management test (pre-flight C3).** In `TestRevokedPlatformCredentialIsGoneFromManagement` (`platform_credentials_test.go`), replace the interim resolution assertion with the GET `/api/cli/platform/<p>/customers` assertions the test specifies (new token 200, old token 401). Run `go test ./internal/console/ -run 'TestRevokedPlatformCredentialIsGoneFromManagement' -count=1`. Expected: PASS.
+- [ ] **Step 6: Commit**
```bash
-git add internal/console/apiplatformcustomers*.go internal/console/routedecls.go internal/console/platform_copy.go
+git add internal/console/apiplatformcustomers*.go internal/console/routedecls.go internal/console/platform_copy.go internal/console/platform_store.go internal/console/applocks.go internal/console/platform_seams.go internal/console/server.go internal/console/platform_credentials_test.go
git commit -m "console: platform doors to create, list and show customer accounts"
```
@@ -679,7 +742,7 @@ git commit -m "console: platform doors to create, list and show customer account
### 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)
+- 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), `internal/console/platform_seams.go` (the two deletion seams), `internal/console/platform_copy.go` (the `update.*` and `delete.*` rows; pre-flight C7)
- Test: `internal/console/apiplatformcustomers_test.go`, `internal/console/platformlinked_test.go` (create)
**Interfaces:**
@@ -690,15 +753,15 @@ git commit -m "console: platform doors to create, list and show customer account
- `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)`.
+Update: write budget (`allowWrite`, else 429 `door.rate`); nothing to change is 400 `update.empty`; a store or bucket error is 502 `update.failed` (pre-flight C10); 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)`.
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. 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.
+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, fields of `platformSeams` (pre-flight C1): `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.
+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. That package global is the accepted exception to the Server-field seam rule (Global Constraints, pre-flight C1).
- [ ] **Step 1: Write the failing tests**
@@ -754,7 +817,7 @@ func TestLockOrderLifecycleAccountBilling(t *testing.T) { // (Astra r2-1)
- [ ] **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 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_seams.go internal/console/platform_copy.go
git commit -m "console: platforms rename and re-plan customers; guard platform deletion"
```
@@ -764,7 +827,7 @@ git commit -m "console: platforms rename and re-plan customers; guard platform d
**Files:**
- Create: `internal/console/platform_credentials.go`, `internal/console/apiplatformcredentials.go`
-- Modify: `internal/console/authstore.go`, `internal/console/svcprincipal.go`, `internal/console/apicli.go`, `internal/console/routedecls.go`
+- Modify: `internal/console/authstore.go`, `internal/console/svcprincipal.go`, `internal/console/apicli.go`, `internal/console/routedecls.go`, `internal/console/platform_seams.go` (the mint seam), `internal/console/platform_copy.go` (the `cred.*` and `audit.credential` rows), `internal/console/svcroutes_test.go` (the `mintDoors` comment), `AGENTS.md` (Step 5) (pre-flight C7)
- Test: `internal/console/platform_credentials_test.go`
**Interfaces:**
@@ -797,19 +860,19 @@ git commit -m "console: platforms rename and re-plan customers; guard platform d
func (s *Store) platformLinkLive(ctx context.Context, q dbQuerier, customerID, platformAccountID, generation int64) (platformSqid string, ok bool)
var ErrPlatformAuthorityEnded = errors.New("console: the platform's grant or the minter's authority ended during the request")
// Test seam, nil in production: called after the door's checks, before the insert transaction begins.
- platformCredentialBeforeInsert func() // field on Server
+ platformCredentialBeforeInsert func() // field of platformSeams (pre-flight C1)
```
- - Door: `POST /api/cli/platform/{account}/customers/{customer}/credentials`, `Exactly(Platform)`, handler `handlePlatformCredentialMint`, body `{role, app, rungs, ttl_seconds}`, reply 201 `{"token", "account", "role", "app", "rungs", "expires_at"}`.
+ - Door: `POST /api/cli/platform/{account}/customers/{customer}/credentials`, `Exactly(Platform)`, handler `handlePlatformCredentialMint`, body `{role, app, rungs, ttl_seconds}`, reply 201 `{"token", "account", "name", "role", "app", "rungs", "expires_at"}` (`name` is the customer account's name, for the CLI's `Minted` line; pre-flight C5).
Rules. The invariant (Astra r1-2): **a per-customer credential is valid only under the grant generation it was minted in, and it is only ever written while that generation is current and its minter still holds authority under it.** Both halves ask `PlatformGenerationLive` (Task 4), so resolution and minting cannot disagree.
-- Mint, shape: role Publish needs app "" and no rungs; role Deploy needs an app the customer holds (`HasAppIn`, else stdlib 404) and rungs through `canonicalRungs` (stable refused as today); anything else is `ErrPlatformCredentialRole`. TTL outside [1 min, 24 h] is `ErrPlatformCredentialTTL`.
+- Mint, shape: role Publish needs app "" and no rungs; role Deploy needs an app the customer holds (`HasAppIn`, else stdlib 404) and rungs through `canonicalRungs` (stable refused as today); anything else is `ErrPlatformCredentialRole`. TTL outside [1 min, 24 h] is `ErrPlatformCredentialTTL`. The door maps `ErrPlatformCredentialRole` to 400 `cred.role`, `ErrPlatformCredentialTTL` to 400 `cred.ttl`, an `allowWrite` refusal to 429 `door.rate`, and any other store error to 500 `cred.failed` (pre-flight C10).
- Mint, authority, **inside the insert transaction** (Astra r1-2): `platformLinkLive(tx, CustomerID, PlatformAccountID, Generation)` must hold; a service minter's own row (by `Minter.CredentialID`) must still be unrevoked, role platform, with `platform_generation == Generation`; a person minter must still hold `owner` on the platform account. Any failure is `ErrPlatformAuthorityEnded` and nothing is written. Row: `kind 'platform'`, `account_id` customer, `platform_account_id`, `platform_generation = Generation`, `address = MintedBy`, `name = Name`, `role`, `app`, `rungs`, fresh `credential_id`, `expires_at = now + TTL`. The door maps `ErrPlatformAuthorityEnded` to 403 `door.revoked`.
- Resolve (`CLIPrincipalContext`, new `case cliKindPlatform`): `expires != 0 && now <= expires` (0 is refused, never "never"); role Publish with app "" and rungs "", or Deploy with app and readable rungs; commands and scope empty; `platformLinkLive(db, account_id, platform_account_id, platform_generation)` true. `platformLinkLive` is `PlatformGenerationLive` plus the customer row live with `platform` equal to the returned platform sqid: one query. Anything else is `Principal{}, false`, the unknown-token 401.
-- `auditActor` (`apicli.go:118`): `p.Platform != ""` renders `"platform:" + p.Platform + "/" + p.Name`.
+- `auditActor` (`apicli.go:118`): a principal resolved from a kind `platform` (per-customer) row renders `"platform:" + p.Platform + "/" + p.Name`; test it as `p.Platform != "" && p.Role != svcrole.Platform`. The platform-role credential also carries `p.Platform` (Task 7) but keeps rendering `"service:" + acct.Sqid + "/" + p.Name`, so customer creation's `Actor` and the plan row's `UpdatedBy` stay `service:bcd/cms` (Task 4's fixture) (pre-flight C9).
- `principalKey` is unchanged: `service:<customer id>/<name>`, so each customer has its own budgets.
- Door: platform gate, `platformCustomer`, write budget, `platformCredentialBeforeInsert`, then the mint with `Generation: caller.Grant.Generation` and `Minter: caller.P`, then audit on the customer (`audit.credential`).
- `CLITokensContext` (`authstore.go:861`) excludes kind platform as it excludes link: these are the customer account's credentials, not the minter's terminals. `ServicePrincipals` stays `kind IN (service, app)`; `RevokeAccountToken` already reaches them by id (decision D10).
-- The door is a credential mint reached by a credential. It is the one deliberate exception to "a credential may never mint a credential" (`svcroutes_test.go:35-91`): what it mints is narrower than its minter in every dimension (one account, Publish at most, expiring, refused when the link or grant ends, and kind platform reaches no mint door). Say so in the declaration's comment.
+- The door is a credential mint reached by a credential. It is the one deliberate exception to "a credential may never mint a credential" (`svcroutes_test.go:35-91`). What it mints is bounded, not narrower in every dimension (it can create apps and deploy, which the platform role cannot): one customer account linked to that platform, Publish at most, at most 24 hours, refused when the link or the grant generation ends, and kind platform reaches no mint door. Say exactly that in the declaration's comment (pre-flight C16).
- [ ] **Step 1: Write the failing tests**
@@ -823,8 +886,10 @@ 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 Store.DeleteAccount on the customer -> 401 (the link check)
+ // RevokePlatformGrant -> 401 (the revoke also swept its row, Task 4); re-grant -> still 401. Then un-revoke its
+ // row with raw SQL (UPDATE cli_tokens SET revoked_at = 0 WHERE credential_id = ?), so only the generation check
+ // can refuse it: still 401 (pre-flight C4). 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.
@@ -850,7 +915,7 @@ func TestPersonalTokenListOmitsCustomerCredentials(t *testing.T)
- [ ] **Step 6: Commit**
```bash
-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 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_seams.go internal/console/platform_copy.go
git commit -m "console: short-lived per-customer credentials minted by a platform"
```
@@ -866,18 +931,20 @@ git commit -m "console: short-lived per-customer credentials minted by a platfor
- 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` (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` 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. The mint's `Minted` line takes the customer name from the reply's `name` (pre-flight C5); a create whose view has no plan prints `CreatedNoPlan` (pre-flight C17).
- [ ] **Step 1: Write the failing tests** (an `httptest` console fake recording requests)
```go
func TestPlatformCustomersCreateSendsAndPrints(t *testing.T) // POST body {name:"shop", ref:"4812"}; prints cliPlatformCopyCreated
+func TestPlatformCustomersCreateWithoutAPlan(t *testing.T) // reply view with plan "": prints cliPlatformCopyCreatedNoPlan, no plan words (pre-flight C17)
func TestPlatformCustomersCreateRefHitPrintsExisting(t *testing.T)
func TestPlatformCustomersListTable(t *testing.T) // columns and the usage summary word per worst cap
func TestPlatformCustomersListEmpty(t *testing.T)
func TestPlatformCustomersRefLookup(t *testing.T) // show --ref 4812 -> GET ?ref=4812 then GET .../customers/bdf; unknown ref -> cliPlatformCopyNoRef
func TestPlatformCustomerFlagsNeedExactlyOneHandle(t *testing.T)
-func TestPlatformCredentialsMintJSON(t *testing.T) // --json output parses; token field equals the fake's
+func TestPlatformCredentialsMintJSON(t *testing.T) // --json output parses; token and name fields equal the fake's (pre-flight C5)
+func TestPlatformCredentialsMintPrints(t *testing.T) // human output: cliPlatformCopyMinted with the reply's name and account, as the Task 1 mock
func TestPlatformCredentialsMintSendsTTL(t *testing.T) // --ttl 2h -> ttl_seconds 7200
func TestPlatformCommandsNeedAConsole(t *testing.T) // CARLOS_DEPLOYMENT_DIR set -> cliPlatformCopyNeedsConsole
```
@@ -953,8 +1020,8 @@ git commit -m "deploy: a Publish credential can give a static app its first host
### Task 13: Linked accounts in plans, billing and notices (§8)
**Files:**
-- Modify: `internal/console/platformlinked.go`, `internal/console/plancaps.go`, `internal/console/billinghold.go`, `internal/console/planexempt.go`, `internal/console/billingpage_copy.go`, `internal/console/domainbuy.go`, `internal/console/plangracepass.go`, `internal/console/platform_copy.go`, `internal/console/plancaps_copy.go`, `accounts_plan.go`
-- Test: `internal/console/platformlinked_test.go`
+- Modify: `internal/console/platformlinked.go`, `internal/console/plancaps.go`, `internal/console/billinghold.go`, `internal/console/planexempt.go`, `internal/console/billingpage_copy.go`, `internal/console/domainbuy.go`, `internal/console/domainbuy_copy.go`, `internal/console/plangracepass.go`, `internal/console/platform_copy.go`, `internal/console/plancaps_copy.go`, `accounts_plan.go`, `accounts_plan_copy.go` (`cliPlanCopySourcePlatform`, beside the other `cliPlanCopy*` constants) (pre-flight C6)
+- Test: `internal/console/platformlinked_test.go`, `accounts_plan_test.go`
**Interfaces:**
- Consumes: `Store.AccountPlatform`, `Server.linkedPlatform` (Tasks 4, 9).
@@ -981,15 +1048,19 @@ func TestPlanNoticesForLinkedAccountsGoToPlatformOwners(t *testing.T)
// fake mail: customer storage over; deliveries only to the platform's owners; subject from email.platform.subject
func TestPlatformOwnerNoticeCountsForAfterGraceDue(t *testing.T)
// after delivery NoticeAt set; at GraceEnds + 72h afterGraceDue true; with no platform owners NoticeAt stays zero
+// root (pre-flight C6)
+func TestAccountsPlanPrintsThePlatformSource(t *testing.T)
+ // fake plan door reply with source "platform", reason "platform bcd": the source line is cliPlanCopySourcePlatform
+ // formatted with the reason
```
- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestLinkedAccountsDoNotCount|TestBillingHoldRefusesLinked|TestBillingDoorsShowThePlatformNotice|TestDomainBuyRefusedOnLinked|TestPlanNoticesForLinked|TestPlatformOwnerNoticeCounts' -count=1`. Expected: FAIL.
- [ ] **Step 3: Implement.**
-- [ ] **Step 4: Run** the Step 2 command plus `-run 'TestCheckNewFreeAccount|TestBillingHold|TestPlanGrace|TestNotifyPlanOwners|TestDomainBuy|TestPlanExempt'` and `go test . -run 'TestAccountsPlan' -count=1`. Expected: PASS.
+- [ ] **Step 4: Run** the Step 2 command plus `-run 'TestCheckNewFreeAccount|TestBillingHold|TestPlanGrace|TestNotifyPlanOwners|TestDomainBuy|TestPlanExempt'` and `go test . -run 'TestAccountsPlan' -count=1` (includes `TestAccountsPlanPrintsThePlatformSource`). Expected: PASS.
- [ ] **Step 5: Commit**
```bash
-git add internal/console/platformlinked*.go internal/console/plancaps.go internal/console/billinghold.go internal/console/planexempt.go internal/console/billingpage_copy.go internal/console/domainbuy.go internal/console/plangracepass.go internal/console/platform_copy.go accounts_plan.go
+git add internal/console/platformlinked*.go internal/console/plancaps.go internal/console/plancaps_copy.go internal/console/billinghold.go internal/console/planexempt.go internal/console/billingpage_copy.go internal/console/domainbuy.go internal/console/domainbuy_copy.go internal/console/plangracepass.go internal/console/platform_copy.go accounts_plan.go accounts_plan_copy.go accounts_plan_test.go
git commit -m "console: linked accounts skip billing and send notices to the platform"
```
@@ -1047,18 +1118,18 @@ git commit -m "witness: a platform deploys a customer's static site end to end"
### Task 15: Copy review, census, ratchet, parity; ready for branch review
**Files:**
-- Modify: `internal/console/platform_copy.go`, `platform_copy.go`, `internal/console/billingpage_copy.go`, `internal/console/plancaps_copy.go`, `internal/console/domainbuy_copy.go`, `docs/site/cli.md`
+- Modify: `internal/console/platform_copy.go`, `platform_copy.go`, `accounts_plan_copy.go`, `internal/console/billingpage_copy.go`, `internal/console/plancaps_copy.go`, `internal/console/domainbuy_copy.go`, `docs/site/cli.md`
- Create: `approved_platform_accounts_copy_test.go`, the census overlay and card `make census-propose` writes
- [ ] **Step 1: Copy review.** Run the `copy-review` skill over the copy table below, rendered in the layouts it ships in (the Task 1 mocks, the email body, the browser flashes). Apply the edits verbatim to the copy files and to this table. Expected: every row approved; no string in the diff that is not in the table (`git diff main -- '*.go' | grep '^+.*"' ` read by hand against the table).
- [ ] **Step 2: Pin the approved copy.** `approved_platform_accounts_copy_test.go` in the shape of `approved_domains_buy_copy_test.go`: one row per table id, its file, and the approved text. Run `go test . -run TestApprovedPlatformAccountsCopy -count=1`. Expected: PASS.
- [ ] **Step 3: Census.** `make census-card`, write CLAIMS for each changed unit in scope (`internal/domains/mint.go`, `internal/svcrole/svcrole.go`, root package files: new commands, the deploy fallback; no unit gains a root read), then `make census-propose NAME=platform-accounts-1 CLAIMS=<file>`. Expected: the proposal writes its overlay and card and reports the census clean. The reviewer's verdict is part of branch review.
- [ ] **Step 4: Ratchet and generated files.** `make code-health` (expect PASS; then `make code-health-record` to lower the record for `(*Store).migrate`), `make parity-doc` (expect no diff after), `gofmt -l .` (expect empty).
-- [ ] **Step 5: Targeted run over everything this branch touched:** `go test ./internal/domains/ ./internal/svcrole/ -count=1`; `go test ./internal/console/ -run 'Platform|Customer|Linked|Materialize|ClosedDoor|EveryCLIDoor|NoRoleReaches|ServiceCreate|CLIPrincipal|DeleteAccount|BillingHold|PlanNotice|DomainBuy|FreeAccount|PublishCredential' -count=1`; `go test . -run 'Platform|AccountsPlatform|MintPlatformHost|ApprovedPlatform|CLIProjection' -count=1`; `go test ./internal/parity/ ./internal/docsite/ -count=1`. Expected: PASS.
+- [ ] **Step 5: Targeted run over everything this branch touched:** `go test ./internal/domains/ ./internal/svcrole/ -count=1`; `go test ./internal/console/ -run 'Platform|Customer|Linked|Materialize|ClosedDoor|EveryCLIDoor|NoRoleReaches|ServiceCreate|CLIPrincipal|DeleteAccount|BillingHold|PlanNotice|DomainBuy|FreeAccount|PublishCredential' -count=1`; `go test . -run '^Test(Platform|AccountsPlatform|AccountsPlan|MintPlatformHost|ApprovedPlatform|CLIProjection)' -count=1` (anchored, so no `TestE2E...` test runs locally; pre-flight C8); `go test ./internal/parity/ ./internal/docsite/ -count=1`. Expected: PASS.
- [ ] **Step 6: Commit**
```bash
-git add internal/console/*copy*.go platform_copy.go approved_platform_accounts_copy_test.go docs/site/cli.md .amadan/code-health.tsv
+git add internal/console/*copy*.go platform_copy.go accounts_plan_copy.go approved_platform_accounts_copy_test.go docs/site/cli.md .amadan/code-health.tsv
git add <the overlay, chain line and card paths make census-propose printed>
git commit -m "platform accounts: approved copy, census overlay, ratchet record"
```
@@ -1135,6 +1206,7 @@ Every row is pending copy review (Task 15). `%s`/`%d` are filled as named. CLI e
| id | text |
|---|---|
| audit.grant | made this a platform account: up to %d customer accounts, plans %s, new ones on %s. reason: %s |
+| audit.grant_no_plans | made this a platform account: up to %d customer accounts. reason: %s (a grant with no plans, on a console with no plan catalog; pre-flight C17, Task 1 UX pass) |
| audit.revoke | turned off platform access, %d credentials stopped working. reason: %s |
| audit.customer_create | created customer account %s (%s) |
| audit.customer_created_by | created by platform account %s |
@@ -1198,13 +1270,16 @@ Every row is pending copy review (Task 15). `%s`/`%d` are filled as named. CLI e
| UsageOverLimit | over the limit, grace until %s |
| CapPDF | PDFs a month |
| Created | created %s (%s) on the %s plan |
+| CreatedNoPlan | created %s (%s) (on a console with no plan catalog; pre-flight C17, Task 1 UX pass) |
| Exists | %s (%s) already exists for reference %s |
| Renamed | %s (%s) is now called %s |
| Replanned | %s (%s) is now on the %s plan |
| Minted | minted a %s credential for %s (%s), valid until %s |
| MintedToken | token |
| MintedUse | use it as CARLOS_SERVICE_TOKEN with --account %s |
-| accounts plan: cliPlanCopySourcePlatform | set by its platform account: %s |
+| accounts plan: cliPlanCopySourcePlatform | set by its platform account: %s (lives in `accounts_plan_copy.go` with the other `cliPlanCopy*` constants; pre-flight C6) |
+
+A grant with no plans (no plan catalog) prints no `LabelPlans` or `LabelDefault` line in `carlos accounts platform`; see the Task 1 no-catalog mocks (pre-flight C17).
Cap names in usage reuse the approved `cliPlanCopyLimit*` labels (apps and instances, object storage, emails a day, bandwidth a month, awake hours a month); `CapPDF` is the one new label.
@@ -1223,7 +1298,7 @@ Cap names in usage reuse the approved `cliPlanCopyLimit*` labels (apps and insta
## Decisions this plan makes that the spec does not pin
- D1. Platform doors use `/api/cli/platform/{account}/...`, not `{platform}`, so `apiPrincipalAccount`'s binding and membership resolution apply unchanged.
-- D2. The grant lives in its own `platform_grants` table; the link is `accounts.platform` (the platform's sqid) and `accounts.platform_ref`; per-customer rows carry `cli_tokens.platform_account_id`.
+- D2. The grant lives in its own `platform_grants` table; the link is `accounts.platform` (the platform's sqid) and `accounts.platform_ref`, with `accounts.platform_mint` recording the pending-mint id the account was born from (pre-flight C15); per-customer rows carry `cli_tokens.platform_account_id`.
- D3. §6.3: Publish on the instance list plus one narrow `platform-host` door that writes no manifest (Astra r1-4), not the domains route (blocked on reserve consoles) and not opening `instances-manifest` (pinned by `policyDoors`).
- D4. The manifest also carries `platform_ref`, so ref idempotency survives a console rebuild.
- D5. Ref grammar: 1-64 of `A-Z a-z 0-9 . _ : -`, case-sensitive, unique per platform among live accounts.
@@ -1259,7 +1334,7 @@ Slice 2 (claim and leave) needs from slice 1:
- 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).
+- Leave/release: clear `accounts.platform`, `platform_ref` and `platform_mint`, 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`.
- The platform doors gain `POST .../customers/{customer}/claim-links` through `platformGate` and `platformCustomer`.