carlos / platform Public

plans 6b: revision 5 after Astra's round 4. Retirement finishes outstanding work before judging subscriptions; admission uses present paid capacity and never reduces; one outstanding predicate (sending, unresolved, pending) for index, revocation and resends, revocation inlined; every write a prepared request of the adapter's exact bytes, persisted and resent verbatim; budget counts the read before each resend; late restore after renewal stated as a risk with invoice-based detection, clock skew capped; the plan inlines all earlier binding text

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 84d70c2fb52303d715e0008d48123464fa28b280 parent 98fc42c
1 file changed, +1,084 −504
  • docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md +1,084 −504

CI failed — run details

diff --git a/docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md b/docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md
index 8a345fcc2..5a60fa2b5 100644
--- a/docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md
+++ b/docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md
@@ -12,7 +12,15 @@
A static pricing page links to one stable console URL, which takes a signed-out visitor through sign-in or sign-up first.
-**Revision 4 (2026-10-25)** answers Astra's round 3 (`plans6b-plan-review-r3.md`, at `c2e313e3`) and records Paul's ruling on Call 17. Its unclear-outcome handling now rests on **Stripe's documented idempotency guarantees** (cited in "Provider facts" below), not on elapsed time. Revision 3's "never resend" was an overcorrection. The rule now is: never send different parameters under a key, and never send a step whose context has gone stale for the first time. Subscription schedules were considered for deferred reductions and **not adopted** (see "Provider facts"). "Review record" maps every finding.
+**Revision 5 (2026-10-25)** answers Astra's round 4 (`plans6b-plan-review-r4.md`, at `98fc42c8`), which accepted the idempotency design.
+- The resend unit is now an **opaque prepared request**: the exact bytes the adapter sends, persisted before the first send.
+- One predicate decides "outstanding" everywhere.
+- Admission uses available paid capacity before anything is reduced.
+- Retirement finishes outstanding work before it judges subscriptions.
+- The residual risk of a late restore has detection.
+- This file is **self-contained**: everything earlier revisions bound by reference is inlined.
+
+"Review record" maps every finding. Paul's seventeen calls stand as ruled.
## Provider facts this plan relies on
@@ -22,380 +30,663 @@ Read with `stripe docs` on 2026-10-25. API v1, which is what the 6a client calls
- "Stripe saves the status code and body of the first request made with a given idempotency key after endpoint execution begins. Retries with the same key return the saved response, including 500 errors." (`/api/idempotent_requests`)
- "The idempotency layer compares incoming parameters to those of the original request and errors if they're not the same." (same page)
2. **Not executed.** "If incoming parameters fail validation, or the request conflicts with another request that's executing concurrently, we don't save the idempotent result because no API endpoint initiates the execution. You can retry these requests." (same page)
-3. **In flight.** "If a 409 indicates that another request with the same key is still executing, wait and retry with that key and the same parameters. A new key can start a second operation." (`/error-low-level`, Content errors)
-4. **No response.** "When a connection fails, you might not know whether Stripe received or executed the request. Retry with the same idempotency key and parameters within the first 24 hours after the original request." (`/error-low-level`, Network errors)
-5. **Server errors.** "Treat the outcome of a request that returns 500 as indeterminate … Don't retry with a new idempotency key until you've resolved the original outcome. Retrieve the relevant object, inspect the request in the Dashboard, and use webhook events to reconcile what happened." And: "Stripe caches 500 responses from POST requests that use an idempotency key. Retrying with the same key returns the cached response." (`/error-low-level`, Server errors) **So a resend cannot resolve a 500.**
-6. **Key lifetime.** "Stripe retains keys for at least 24 hours and can remove them after that. Reusing a key after it's removed can execute a new request." And: "If the outcome is still unknown after that window, don't retry with either the old key or a new one. Retrieve the relevant object, inspect the request in the Dashboard, and use webhook events to reconcile the outcome." (`/error-low-level`, POST requests)
-7. **Replay marker.** "To identify a previously executed response that's being replayed from the server, look for the header `Idempotent-Replayed: true`." (`/error-low-level`)
-8. **Pending updates never cross a period.**
- - "A pending update's expires_at time matches the first occurrence of either the trial end or the earliest items.current period end … if either time is within 23 hours of the update request. Otherwise, the expiration is 23 hours from the update request." (`/billing/subscriptions/pending-updates`)
- - Supported attributes include `proration_date`, and items with `quantity` (same page).
-9. **Schedules and direct updates.**
- - With a schedule attached, "any modifications you make directly to the subscription might be overwritten by the subscription schedule when the next phase is entered", and Stripe advises using the Subscription Schedule API instead of the Subscriptions API (`/billing/subscriptions/subscription-schedules`).
- - "A schedule phase change discards a pending update and voids the associated invoice." (pending-updates page)
-10. **`proration_date` is not a precondition.** The docs describe it only as the time prorations are "calculated as though" the update happened (`/api/subscriptions/update`). No documented guarantee refuses an update outside the current period, so it cannot fence a request to a period.
-
-**Suggestion A (idempotency keys as the finality primitive): adopted.**
-- Facts 1 to 4 give a definite outcome for no-response, 409 and pre-execution failures, by resending the byte-identical request with the same key inside the key's lifetime (fact 6).
-- Fact 5 is the exception: a cached 500 stays indeterminate, so it goes to an operator.
-
-**Suggestion B (subscription schedules): not adopted.**
-- Fact 9 means attaching a schedule moves every later change (packs, seats, upgrades) onto the Schedule API, where direct updates may be overwritten.
-- A phase transition discards a pending update and voids its invoice. That breaks 6a Call 8's "charged now with `pending_if_incomplete`, granted once paid".
-- It would add a second state machine beside 6a's held packs, more requests per change, and a new census surface.
-
-Finding 2 is fixed instead by refusing restores near the period end (Invariant 4). Because of fact 8, no pending charge can cross a period either.
+3. **In flight.** "If a 409 indicates that another request with the same key is still executing, wait and retry with that key and the same parameters. A new key can start a second operation." (`/error-low-level`)
+4. **No response.** "Retry with the same idempotency key and parameters within the first 24 hours after the original request." (`/error-low-level`, Network errors)
+5. **Server errors.** "Treat the outcome of a request that returns 500 as indeterminate … Retrieve the relevant object, inspect the request in the Dashboard, and use webhook events to reconcile what happened." And "Stripe caches 500 responses from POST requests that use an idempotency key. Retrying with the same key returns the cached response." (`/error-low-level`)
+6. **Key lifetime.** "Stripe retains keys for at least 24 hours and can remove them after that. Reusing a key after it's removed can execute a new request." After that window, "don't retry with either the old key or a new one." (`/error-low-level`)
+7. **Replay marker:** the `Idempotent-Replayed: true` response header. (`/error-low-level`)
+8. **Pending updates** expire at the earliest current period end when that is within 23 hours of the update request, otherwise 23 hours after it. Supported attributes include `proration_date` and items with `quantity`. (`/billing/subscriptions/pending-updates`)
+9. **Schedules:** direct changes to a scheduled subscription "might be overwritten" at the next phase (`/billing/subscriptions/subscription-schedules`), and "A schedule phase change discards a pending update and voids the associated invoice" (pending-updates page). **Schedules are not adopted.** They would move every change onto the Schedule API and break "charged now, granted once paid".
+10. **`proration_date` is not a precondition.** Prorations are calculated "as though" the update happened at that time (`/api/subscriptions/update`). No documented guarantee refuses an update outside the current period.
+
+**Not guaranteed by any of these:** a bound on server processing time. A request sent in one period could, in principle, first apply in the next. See "Risks".
## Invariants
1. **Finality comes from the provider.** It comes from an idempotent result or a positive read, never from elapsed time or a negative read.
- - An operation is one provider request, persisted **exactly** before its first send, together with its key and its resend window: the subscription id and its period end, item id or absence, price id, quantity, proration, proration timestamp, and idempotency key.
- - The only resend is that same byte-identical request with the same key, inside the window, preceded by a read. If the read already shows the target or a pending update, the outcome is recorded and nothing is resent.
- - The window closes at the earlier of `first send + 23 h` (fact 6, with an hour's margin) and `period end − 1 h`.
- - Never send different parameters under a key. Never send a stale step for the first time: a step not yet sent whose period, book, consent or intent has moved is abandoned.
- - New work is always computed fresh.
+ - Every write is a **prepared request**: the adapter's exact encoded body, path, method and idempotency key, with every parameter resolved (price ids, item ids, coupon id, URLs, metadata, proration timestamp, constants). It is persisted before its first send and never edited afterwards.
+ - The only resend is those stored bytes with the same key, preceded by a read wherever one exists (every subscription and session write; a customer create has no id to read, so its same-key resend is its own check). If the read shows the target or a pending update, the outcome is recorded and nothing is sent.
+ - The resend window closes at the earlier of `first send + 23 h` and `period end − 1 h`, both in provider time (Invariant 4). Facts 1 to 6 give it.
+ - Never send different bytes under a key. Never send a prepared request whose context has gone stale (a new period, book, consent or intent, or an invite no longer pending) for the first time.
+ - New work is computed fresh.
+ - **One exception, stated:** a Checkout create that ends indeterminate or out of its window is abandoned when the customer's exhaustive session list does not contain its intent id. That is safe because a late session is unusable (Risks, R2), not because it is final.
2. **Paid capacity is decided at admission, every time.**
- - An applied invite charge is a credit that the next admission may use.
- - No seat is reserved.
- - A seat authorisation is single use, and it is consumed **in the same store transaction as any transition of its operation to `applied`**.
-3. **Provider enumeration is exhaustive or it refuses.** Lists page to completion, up to `billing.MaxListPages` (10) pages of 100. Beyond that, `billing.ErrIncomplete`. This includes 6a's discovery, which is migrated (Task 5).
-4. **Refresh and allowance are separate, and restores keep away from the period end.**
- - `refreshLocked` is the plain sync of the recorded subscription. `allowanceLocked` also requires the paid period to match the read, and is used only for quantity changes and joins on a live, paid subscription.
- - A **restore** (a `ProrateNone` raise up to the period's paid quantity) is sent only when `periodEnd − now > restoreMargin` (25 h). Every attempt, including resends (at most 23 h after the first), then lands at least an hour before renewal.
- - Inside the margin, buying back is refused with `change.near_renewal`. After renewal it is an ordinary charged add.
-5. **Background passes never write to the provider.** No resend, no expiry, no change, no session creation. They read, record what reads show, and open billing problems. Every provider write happens inside an owner's or invitee's request: Checkout, change, renewal, join, removal, "confirm now", "match seats", deletion.
+ - Available paid capacity (`cur` and `paid`) is used first. Joins never reduce quantities.
+ - An applied invite charge is a credit for the next admission.
+ - A seat authorisation is single use, consumed in the same transaction as its operation's transition to `applied` (`Store.MarkOpApplied`).
+3. **Provider enumeration is exhaustive or it refuses.** Lists page to completion, up to 10 pages of 100, else `ErrIncomplete`. This includes discovery, which is migrated.
+4. **Refresh and allowance are separate; restores keep away from the period end.**
+ - `refreshLocked` is the plain sync. `allowanceLocked` also requires the paid period to match the read, and is used only for quantity changes and joins on a live, paid subscription.
+ - A restore (a `ProrateNone` raise up to the period's paid quantity) is first sent only when `periodEnd − providerTime > 25 h`, where `providerTime` is the `Date` header of the fresh read.
+ - No restore, and no resend of any request, is sent when the console clock and `providerTime` differ by more than 5 minutes (`change.clock`).
+ - Inside the margin, buying back is refused, and after renewal it is an ordinary charged add.
+5. **Background passes never write to the provider.** They read, record what reads show, and open billing problems. Every write happens inside an owner's or invitee's request.
6. **A terminal intent is history.** Checkout and retirement judge the account's subscriptions from an exhaustive list.
-
-**Architecture:**
-- **Team plans** (`internal/plans`): a `team` block on a plan. `Effective` takes a member count. `max_members` on non-team plans. Public export schema 3.
-- **Seats and membership** (`internal/console`): `account_plans.seats`; `membershipTransition` wraps 6a's `transitionAccountPlan`; every join is admitted under a member lock with in-lock re-checks.
-- **Provider writes** (`internal/billing`, `internal/billingstripe`): new `Provider` methods. The adapter classifies every write's outcome into definite, not executed, in flight, no response, or indeterminate (facts 1 to 5). Stripe status words stay in the adapter.
-- **Operations** (`internal/console`):
- - one provider request per `billing_operations` row, persisted exactly;
- - resolved by its idempotent result or by a positive read; one outstanding per subscription;
- - `finishOpLocked` is the only resend path, and it runs only inside a user's request;
- - customer creation, Checkout creation and session expiry use the same exact-request, same-key lifecycle.
-- **The console flow:** the billing page, `/upgrade`, Checkout (start, continue, replace, return), pack, plan and seat changes, renewal, the portal, "confirm now", "match seats", and a retirement gate.
-
-**Tech Stack:** Go, stdlib only; SQLite console store; `html/template`; `internal/plans`, `internal/billing`, `internal/billingstripe`, `internal/console`, `cmd/console`, `cmd/pricebook-export`, the `carlos` CLI.
+7. **One predicate decides "outstanding".**
+ - `opOutstanding(state)` is true for `sending`, `unresolved` and `pending`.
+ - The partial unique index, revocation, retry eligibility, admission, change refusal and the retirement gate all call it.
+ - A test asserts the index's state list equals the predicate's.
+
+## Risks
+
+- **R1. A restore first applying after renewal** (inherited finding 2, residual).
+ - The 25 h margin, the 5-minute skew cap and the `period end − 1 h` resend cut-off bound when restores are **sent**. Nothing documented bounds when Stripe **executes** them.
+ - Failure direction: a late restore gives the account free packs or seats for the new period, until an operator acts. **It never overcharges.**
+ - **Detection:** when any read applied under the hold shows a period change for a subscription that had a restore operation sent in the previous period (any state but `failed`), `lateRestoreCheckLocked` reads the renewal invoice. It compares each item's current quantity with the invoiced quantity for that price. A quantity above the invoiced one, not explained by an `applied` operation in the new period, opens a `restore_after_renewal` billing problem naming the item and both quantities.
+ - It writes nothing to the provider. The operator reduces the quantity or bills it in the Dashboard, then closes the problem.
+ - It needs Invoices read on the restricted key (6c).
+- **R2. A late Checkout session** after its create was abandoned (Invariant 1's exception).
+ - The session's URL was never shown, so nobody can pay it. Its `expires_at` is at most an hour after the create, so it is already past or close.
+ - If one were ever completed anyway, the live-subscription check (Checkout) and discovery would adopt the subscription, and a second purchase is refused.
+- **R3. An orphan Stripe customer** from a customer create retried under a new attempt key after an indeterminate result. It has no payment method or subscription and is never bound. Harmless.
+
+## Architecture
+
+- **Team plans** (`internal/plans`): a `team` block on a plan; `Effective` takes a member count; `max_members` on non-team plans; public export schema 3.
+- **Seats and membership** (`internal/console`):
+ - `account_plans.seats` is the paid seat count billing wrote; 0 means "count members now".
+ - `membershipTransition` wraps 6a's `transitionAccountPlan`.
+ - Every join is admitted under a member lock, with in-lock re-checks.
+- **Provider boundary** (`internal/billing`, `internal/billingstripe`):
+ - The adapter turns a neutral request into a `billing.Prepared` (opaque bytes), and sends a `Prepared`. Each answer is classified as definite, not executed, in flight, no response or indeterminate (facts 1 to 5).
+ - Reads report `ProviderTime`.
+ - Stripe status words stay in the adapter.
+- **Operations and prepared requests** (`internal/console`):
+ - A subscription change is a `billing_operations` row holding one `Prepared`.
+ - Customer creation, Checkout creation and session expiry store their `Prepared` on the billing row or the intent.
+ - `finishOpLocked` (and its siblings for customers, sessions and expiry) is the only resend path, and it runs only inside a user's request.
+- **The console flow:** the billing page, `/upgrade`, Checkout (start, continue, start over, return), pack, plan and seat changes, renewal, the portal, Confirm now, Match seats, and a retirement gate.
+
+**Tech Stack:** Go, stdlib only (no stripe-go); SQLite console store; `html/template`; `internal/plans`, `internal/billing`, `internal/billingstripe`, `internal/console`, `cmd/console`, `cmd/pricebook-export`, the `carlos` CLI at the repo root.
**Spec:** `docs/superpowers/specs/2026-10-20-plans-caps-packs-design.md`:
-- §9.1 (one annual subscription per account; packs prorated on add and granted once paid, reduced at renewal; Checkout in subscription mode; the locked portal; the console changes plans and quantities);
-- §9.2;
-- §9.6;
-- §10;
-- §3 (usd, eur and gbp; country default with an override; explicit unsold refused; no conversion; draft book refused when live; `rk_` keys);
-- §8.1.
+- §9.1:
+ - one annual subscription per account, in its currency: Personal ×1 plus one item per pack, with quantity;
+ - adding a pack mid-year prorates, and is granted once paid; reducing takes effect at renewal;
+ - upgrading from free is Checkout in subscription mode;
+ - payment method and invoices go through the customer portal, locked to those functions;
+ - the console changes plans and quantities, never the portal.
+- §9.2 (paid limits while Stripe retries; Plan 4d owns what falls).
+- §9.6 (the live setup: the 6c outline).
+- §10 (provider boundary).
+- §3: usd/eur/gbp, default by billing country with a visible override, an explicit unsold currency refused, nothing converted; a live console refuses a draft book; `rk_` keys in the EnvironmentFile.
+- §8.1 (one free account per person).
Also binding:
-- **Plan 6a** and its accepted Calls.
-- **Paul's team-plan ruling** (2026-10-25), amended by his acceptance of Call 7. Task 0 records it:
- - Community and Business are multiples of the same gates.
- - Prices per member per year, usd / eur / gbp: Community 6 / 5 / 4.50, Business 60 / 50 / 45. A minimum of 10 members.
- - Limits are Personal's × 0.2 (Community) or × 2 (Business) per member, pooled, for running things, awake hours, bandwidth, object storage and email.
- - **Disk is neither multiplied nor pooled.** Team plans keep Personal's 10 GB per running thing, so total disk grows only through the running-things count.
- - Flags as Personal. Business also gets 7-day history and priority support.
- - Every member who can access and ship counts. An add is charged at once, prorated. A leave comes off at renewal.
-- **Pricing-page ruling:** the page publishes only with checkout live, and links to `/upgrade` (Task 8).
+- **Plan 6a** (`docs/superpowers/plans/2026-10-25-plans-6a-checkout.md`) and all its accepted Calls.
+- **Paul's team-plan ruling** (2026-10-25), amended only by his acceptance of Call 7. Task 0 records it:
+ - Community and Business are "just different multiples of the same gates".
+ - Prices are per member per year, usd / eur / gbp: Community 6 / 5 / 4.50, Business 60 / 50 / 45. The account pays for at least 10 members.
+ - Limits are Personal's × 0.2 per member (Community) or × 2 per member (Business), pooled across the account, for running things, awake hours, bandwidth, object storage and email.
+ - **Disk is neither multiplied nor pooled** (Call 7, accepted). Team plans keep Personal's 10 GB per running thing, so total disk grows only through the running-things count.
+ - Flags (custom domains, the 15-minute idle window) are as Personal. Business also gets 7-day history and priority support.
+ - Every member who can access and ship counts. Adding a member charges the rest of the year at once, prorated to the day. A member who leaves comes off the bill at renewal.
+- **Pricing-page ruling:** the carloku.com pricing page publishes only when checkout is live, and its buttons go straight to the console's upgrade entry (Task 8).
## Base branch, order and 6a's names
-- Cut from `plans-6-checkout` at `f4ce6bda`. **Rebase onto main after 6a merges,** before Task 1. Until then, merge `origin/plans-6-checkout` and `origin/main`, build Tasks 0 to 2 only, and stop before Task 3.
-- **6a's merged names:**
- - `applyAccountPlan`, `applyBillingPlan`;
- - `transitionAccountPlan(ctx, acct, now, write)`;
- - `Store.SaveBillingSync(next, accountID, plan, markLapse, resetCaps, now)`;
- - `syncSubscription`, `applyBillingRead`;
- - `subscriptionMissing`, `endMissingSubscription`;
- - `billingDiscoveryPass`, `DiscoverableBillingAccounts`;
- - `billingReadyCheck`, `StartBillingSyncPass`;
- - `s.billing.locks`.
-- **6a's round-2 fix pass** is assumed to change discovery, pending-replacement adoption and the closing of `subscription_missing`, all under the billing lock. Use 6a's merged names where they differ, and note the ruling in the ledger.
+- Cut from `plans-6-checkout` (6a) at `f4ce6bda`. **Rebase onto main after 6a merges,** before Task 1. Until then, merge `origin/plans-6-checkout` and `origin/main`, build Tasks 0 to 2 only (they touch only `internal/plans`), and stop before Task 3.
+- **6a's merged names, which this plan uses:**
+
+ | Name | Notes |
+ | --- | --- |
+ | `applyAccountPlan` | |
+ | `applyBillingPlan` | |
+ | `transitionAccountPlan(ctx, acct, now, write func(old *AccountPlanRow) (bool, error))` | |
+ | `Store.SaveBillingSync(next, accountID, plan, markLapse, resetCaps, now)` | |
+ | `syncSubscription` | takes the billing lock |
+ | `applyBillingRead` | the caller holds it |
+ | `subscriptionMissing`, `endMissingSubscription` | |
+ | `billingDiscoveryPass`, `DiscoverableBillingAccounts` | |
+ | `billingReadyCheck`, `StartBillingSyncPass` | |
+ | `s.billing.locks` | `keyedLocks` by sqid |
+- **6a's round-2 fix pass** is assumed to change discovery, pending-replacement adoption and the closing of `subscription_missing`, all under the billing lock. Use its merged names where they differ, and note the ruling in the ledger. 6b only adds hooks:
+ - seats in `decideBilling`;
+ - operation settlement and the late-restore check after `applyBillingRead`;
+ - intent observation in discovery.
## Calls for Paul
-**Calls 1 to 16 ruled 2026-10-25: Paul accepted every recommendation as written.** Don't reopen them. Revisions 2 to 4 change only how Calls 6, 11 and 15 are made safe.
-
-1. **The upgrade URL and account choice:** owns one, its billing page; several, a picker; none, a not-owner page.
-2. **Default currency** from the visitor's GeoIP country, with an override. Checkout collects the address. An explicit unsold currency is refused.
-3. **Currency fixed after the first purchase.**
-4. **Paid-to-paid: upgrades only in 6b.**
-5. **A local estimate for quotes.**
-6. **A fresh sign-in proof** before charging a saved card, before opening the portal, and before recording a seat authorisation.
-7. **Disk not pooled.**
-8. **Ceilings scale with the team.**
-9. **Community: the latest copy only. Business: 7 days.**
-10. **The same packs on team plans, flat per account.**
-11. **A join charges at accept, before the membership is created.** On failure, the person waits and the invite stays valid. Authorisations are single use. Operator-added excess opens `seats_unpaid`.
-12. **A leave comes off at once with no proration.** The period's highest paid seats are kept. A rejoin within the period is free (subject to Invariant 4's margin).
-13. **Owners and members count; at least 10.**
-14. **`max_members` 3 on Free and Personal.**
-15. **Deleting a renewing account is refused; allowed once renewal is stopped,** checked by a retirement gate against provider truth.
-16. **No create-as-paid path.**
-17. **Unclear outcomes. Ruled 2026-10-25 by Paul: "auto first, then an operator."** The mechanism (revision 4):
+**Calls 1 to 16 were ruled on 2026-10-25: Paul accepted every recommendation as written. Call 17 was ruled the same day: "auto first, then an operator."** Don't reopen them.
+
+1. **The upgrade URL and which account it upgrades.** After sign-in, the console looks at the accounts the viewer owns:
+ - one: straight to its billing page;
+ - several: a short picker, the most recent first;
+ - none: a page saying only an owner can upgrade an account, with a link to create one.
+
+ A new sign-up owns the account minted on landing, so it goes straight through.
+2. **Default currency.**
+ - The page preselects by the visitor's country from the console's GeoIP database, falling back to the book's default.
+ - The buyer can override it with three radio buttons.
+ - Stripe Checkout collects the billing address (`billing_address_collection=required`) and computes tax from it.
+ - An explicit currency we do not sell is refused with a banner, and nothing is preselected.
+3. **An account's currency is fixed after its first purchase** (a Stripe customer can't hold two currencies). Changing it is an operator task.
+4. **Paid-to-paid switches: upgrades only in 6b.**
+ - An upgrade is a switch to a plan whose lowest yearly total in the configured book is higher. It swaps the plan item's price at once, charged now and granted once paid.
+ - A downgrade between paid plans is not self-serve.
+5. **The quote is a local estimate:** "about $X now for the rest of the year, plus any tax", from the book price × the days left / 365, rounded up.
+6. **A fresh sign-in proof** (`requireFreshAuth`) before charging a saved card (pack raises beyond the paid count, plan upgrades), before opening the portal, and before recording a seat authorisation. Checkout itself and stopping renewal don't need one.
+7. **Disk is not pooled.** Team plans keep Personal's 10 GB per running thing.
+8. **Ceilings scale with the team.** On a team plan, each pooled ceiling is multiplied by `multiple × billed members` when that factor is above 1.
+9. **Community's history:** the latest copy only. Business gets 7 days. Sidecars, memory tier, minimum schedule and fleets are as Personal for both.
+10. **Packs on team plans:** the same five, flat per account, at the same prices.
+11. **A join charges at accept, before the membership is created.**
+ - The owner confirms the cost when inviting someone who will need a new paid seat, and the authorisation is stored on the invite.
+ - On payment failure the person doesn't join, the invite stays valid, and the owners see the waiting payment.
+ - Authorisations are single use.
+ - Operator-added members are never charged; any excess opens `seats_unpaid`.
+12. **A member who leaves** comes off at once with no proration. The account keeps the period's highest paid seats until renewal. A rejoin within the period is free, subject to Invariant 4's margin.
+13. **Who counts:** owners and members. Not pending invites, not service credentials. The account is billed and limited at a minimum of 10.
+14. **`max_members` is 3 on Free and Personal,** checked when an invite is sent and when it is accepted. Nobody is removed, and sponsored accounts are exempt.
+15. **Deleting a renewing account is refused, and allowed once renewal is stopped.** It is checked by the retirement gate (Task 13) against provider truth.
+16. **No create-as-paid path for a second account.** The free-account refusal says to upgrade the free account first.
+17. **Unclear outcomes: auto first, then an operator.**
- **Auto:**
- - Within the handler, a no-response, 409 or 429 outcome is resent byte-identically with the same key, up to 3 times over about 7 s (facts 2 to 4).
- - If still unresolved, the operation stays outstanding, refusing other changes on the subscription. The owner sees "We're confirming a change" with a **Confirm now** button. That button, and any later owner or invitee request on the subscription, runs `finishOpLocked`: a read, then (with no positive evidence) the same resend, inside the window.
- - A positive read (the target is visible) settles it at any time, from any path, the passes included.
- - **Operator:** the observation pass opens `operation_unresolved` only for:
- - (a) an indeterminate outcome, meaning a cached 5xx (fact 5: resending returns the same 500);
- - (b) a window that closed with no definite outcome (fact 6).
-
- Changes on the account stay refused. The operator close door needs either a fresh read showing the target (recorded `applied`) or the operator's note stating what the Dashboard request log shows (fact 5's "inspect the request in the Dashboard"), recorded `applied` or `abandoned` with that note. A negative read alone never closes it.
- - **A known pending payment never escalates.** An operation in `pending` (a `PendingUpdate` was observed) follows the pending-payment lifecycle: applied when paid, abandoned when Stripe expires it, which is always before the period ends (fact 8).
+ - in the handler, up to 3 retries over about 7 s for no-response, 409 and 429 answers, each a read then the same `Prepared`;
+ - afterwards, **Confirm now** on the page, and any later owner or invitee request on the subscription, runs `finishOpLocked` inside the window;
+ - a positive read settles at any time, from any path.
+ - **Operator:** the pass opens `operation_unresolved` for a cached 5xx (fact 5) or a window that closed with no definite outcome (fact 6). Changes on the account stay refused. Closing it needs a fresh read showing the target, or the operator's note stating what the Dashboard request log shows. A negative read alone never closes it.
+ - **A known pending payment never escalates.** It follows Stripe's pending-update lifecycle (fact 8).
## Global Constraints
-- **Dormant unless configured.** `cfg.Billing == nil`: new routes 404, no nav link, no billing step in invites, the house door 409, no retirement gate. Team limits, `max_members`, the member lock and transitions work under a catalog alone.
-- **6a's rules hold:** the event body is never trusted; the plan follows fresh reads under the billing lock; billing-owned rows only; a draft book is refused when live; `rk_` keys only.
-- **Locks: member → billing → lapse → store.** The billing lock is taken via `holdBilling` only. `*Locked` helpers take a `billingHold` and never lock (an AST test). Timeout tests use 15 s, allowing for the in-handler resends.
-- **Granted once paid:** charges are `ProrateNow` (`always_invoice` + `pending_if_incomplete`); reductions and restores are `ProrateNone`.
-- **One outstanding operation per subscription:** a partial unique index over `sending`, `unresolved` and `pending`. A read with `PendingUpdate` counts as outstanding even with no row.
-- **Idempotency keys**, persisted with the exact request:
-
- | Request | Key | Notes |
- | --- | --- | --- |
- | operation | `op:<operation id>` | |
- | customer creation | `customer:<sqid>:<attempt>` | Invariant 1's lifecycle |
- | Checkout create | `checkout:<intent id>` | |
- | session expiry | `expire:<intent id>` | |
- | portal | `portal:<customer>:<16 random hex>` | no state; a lost portal response just gets a new session |
+- **Dormant unless configured.** `cfg.Billing == nil` means:
+ - every new web route answers `http.NotFound`;
+ - no billing nav link;
+ - no billing step in invites;
+ - the house door answers 409 `billingCopyOff`;
+ - no retirement gate.
+
+ Team limits, `max_members`, the member lock and `membershipTransition` work under a catalog alone. Without a catalog, `membershipTransition` is just the membership write.
+- **6a's rules hold:**
+ - the event body is never trusted;
+ - the plan follows only fresh reads applied under the billing lock;
+ - billing writes only `default` or `billing` plan rows;
+ - a live console refuses a draft book;
+ - `rk_` keys from the EnvironmentFile only.
+- **Locks: member → billing → lapse → store.**
+ - `s.memberLocks` is keyed by sqid.
+ - The billing lock is taken only through `holdBilling`.
+ - Functions named `*Locked` take a `billingHold` first and never lock; an AST test enforces it.
+ - Timeout tests use 15 s.
+- **Granted once paid.** Charges are `ProrateNow` (`always_invoice` + `pending_if_incomplete`). Reductions and restores are `ProrateNone`.
+- **Idempotency keys**, each stored inside its `Prepared`:
+
+ | Request | Key |
+ | --- | --- |
+ | operation | `op:<operation id>` |
+ | customer | `customer:<sqid>:<attempt>` |
+ | Checkout create | `checkout:<intent id>` |
+ | expiry | `expire:<intent id>` |
+ | portal | `portal:<customer>:<16 random hex>` (no state; a lost portal answer just means opening a new one) |
- **Changes use the subscription's own book and currency.** New purchases use `cfg.Book.Version`.
-- **Currencies:** exactly `usd`, `eur`, `gbp`. Any other explicit value is refused, never defaulted. A fixed currency is re-checked under the Checkout hold.
-- **Provider neutrality:** the console reads only `billing` facts. A scan test keeps Stripe status words out of `internal/console/billing*.go`.
+- **Currencies:** exactly `usd`, `eur` and `gbp`. Any other explicit value is refused, never defaulted. A fixed currency is re-checked under the Checkout hold.
+- **Provider neutrality:** the console reads only `billing` facts and treats `Prepared` as opaque. A scan test keeps Stripe status words out of `internal/console/billing*.go`.
- **Money moves only** on an owner's POST with CSRF, or on an accept covered by an unconsumed, matching seat authorisation.
-- **Redirect targets** are built from `s.cfg.Origin` and the sqid only.
+- **Redirect targets** come from `s.cfg.Origin` and the sqid only, and are frozen into the `Prepared`.
- **Request budget, by branch and cardinality.**
- Notation:
- - `L(n)`: one exhaustive list over `n` objects **examined in every status**, `max(1, ceil(n/100))` requests, at most 10, else `ErrIncomplete`.
- - `S`: a sync of one subscription, 1 read plus 1 when another recorded subscription is live, so 1 to 2.
- - `R`: in-handler resends after an unclear send, 0 to 3.
- - `F`: one `finishOpLocked`: 1 read, plus at most 1 resend.
+ - `L(n)`: an exhaustive list over `n` objects examined in every status, `max(1, ceil(n/100))` requests, at most 10, else `ErrIncomplete`.
+ - `S`: a subscription sync, 1 read plus 1 when another recorded subscription is live, so 1 to 2.
+ - `R`: in-handler retries, 0 to 3, each **a read and a resend**, so 2 requests per retry.
+ - `F`: one `finishOpLocked`, 1 read plus at most 1 resend.
| Operation | Branch | Stripe requests |
| --- | --- | --- |
- | Readiness | per attempt | 34 (35 with a house coupon); stops at the first failure. Back off 1, 2, 4, 8, 16, then every 30 min. |
+ | Readiness | per attempt | 34 (35 with a house coupon); stops at the first failure. Retries back off 1, 2, 4, 8, 16, then every 30 min. |
| Billing page view | any | 0 |
- | Confirm now | an unresolved operation | `F` + `S` |
- | Checkout start | first purchase | `S` (recorded subscription, if any) + `L(all subs)` + customer create (1 + `R`) + session create (1 + `R`) |
- | | prior intent open, same request (continue) | `S` + `L` + 1 session read |
- | | prior intent open, other request | `S` + `L` + 1 session read + expiry (1 + `R`; +1 read if refused) + create (1 + `R`) |
- | | prior intent unresolved (`creating`) | `S` + `L` + `F` on the create, then the branch it resolves to |
- | | a live subscription found | `S` + `L` + `S` per live id, then a refusal |
+ | Confirm now | unresolved op | `F` + `S` |
+ | Checkout start | first purchase | `S` (recorded subscription, if any) + `L(all subs)` + customer (1 + 2R) + create (1 + 2R) |
+ | | open intent, same request | `S` + `L` + 1 session read |
+ | | open intent, Start over | `S` + `L` + 1 session read + expiry (1 + 2R; +1 read if refused) + create (1 + 2R) |
+ | | creating intent | `S` + `L` + `F` on the create, then the branch it resolves to |
+ | | live subscription found | `S` + `L` + `S` per live id, then a refusal |
| Continue (GET) | open intent | 1 session read |
| Checkout return | any | 1 session read + `S` |
- | Pack or plan change | prior op unresolved | `F` first; if still unresolved, a refusal |
+ | Pack or plan change | prior op outstanding | `F`; still outstanding means a refusal |
| | no step | `S` |
- | | one step | `S` + (1 + `R`) + `S` |
- | | restore, then charge | `S` + (1 + `R`) + (1 + `R`) + `S` |
- | Renewal | any | `S` + (1 + `R`) + `S` |
+ | | one step | `S` + (1 + 2R) + `S` |
+ | | restore, then charge | `S` + 2 × (1 + 2R) + `S` |
+ | Renewal | any | `S` + (1 + 2R) + `S` |
| Portal | any | 1 |
| Join, billing team | free seat | `S` |
- | | restore or charge | `S` + (1 + `R`) + `S` |
- | | both | `S` + 2 × (1 + `R`) + `S` |
- | Match seats (owner) | drift | `S` + (1 + `R`) + `S` |
- | Deletion gate, per run (runs twice) | `k` live of `n` examined, `j` non-terminal intents, `u` unresolved ops | `L(n)` + `k` × `S` + `u` × `F` + per intent: 1 session read (+ expiry 1 + `R`) or `F` |
- | Hourly pass, per account | any | 6a's sync; discovery `L(n)` per recently bound customer (migrated); 1 session read per open intent; 1 read per unresolved op; 0 writes |
+ | | restore or charge | `S` + (1 + 2R) + `S` |
+ | | both | `S` + 2 × (1 + 2R) + `S` |
+ | Match seats | drift | `S` + (1 + 2R) + `S` |
+ | Deletion gate, per run | `u` outstanding ops, `j` non-terminal intents, `k` live of `n` examined | `u` × `F` + per intent (1 session read + expiry 1 + 2R, or `F`) + `L(n)` + `k` × `S` |
+ | Late-restore check | per observed renewal with a prior-period restore | 1 invoice read + `L(invoice lines)` |
+ | Hourly pass, per account | any | 6a's sync; discovery `L(n)` per recently bound customer; 1 session read per open intent; 1 read per outstanding op; late-restore checks; **0 writes** |
- S3: nothing polled. A limits publication is a GET plus a conditional PUT, with conflict retries. `transitionAccountPlan` adds 4d's inventory reads and convergence writes per change that moves limits.
- - **Call-count assertions:** every recovery, Checkout-branch, deletion and pass test asserts `Fake.CallsBy` against this table. Pass tests assert zero writes.
-- **No product name; no `Record` in helper names.**
-- **Copy:**
- - It lives in `billingpage_copy.go`, `plancaps_copy.go` and `billing_cli_copy.go`. Tests compare against the maps.
- - Draft strings marked "revision 2's" are in `git show c86d0692:docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md`, same task. The Luna pass replaces every draft, so none is load-bearing.
- - Where a task says "as revision 3" (accepted text not repeated here: Task 1 validation, Task 3 and Task 8 currencies, the `/upgrade` contract and the copy table), the full text is in `git show b505823d:docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md`, same task. It is binding as written there.
-- **Census:** route lines, fixtures and probes with each route-adding task; new tables `NonApp`; units derived from the final diff.
+ - **Call-count assertions:** recovery, Checkout-branch, deletion and pass tests assert `Fake.CallsBy`, reads included. Pass tests assert zero writes.
+- **No product name** in code, tests, copy or example data. **No `Record` in helper or type names.**
+- **Copy:** it lives in `internal/console/billingpage_copy.go` (`billingCopy`), `plancaps_copy.go` and `billing_cli_copy.go`. Tests compare against the maps, never literal text. House rules: no em dashes (a full stop and a new sentence), plain words, CLI lower case. Error fragments, diagnostics and JSON keys stay out. The Luna pass replaces every draft.
+- **Census:**
+ - route lines, fixtures and probes go with each route-adding task;
+ - new tables are `NonApp` in `claimSQLTables`;
+ - units and envelopes are derived from the final diff (Task 15).
- **Tests:**
- - TDD, no network; inject `now`.
+ - TDD, no network; inject `now`. Run touched packages with `-run`, niced; one `-run Claim` run per route-adding task.
- The Fake models:
- - per-key idempotency, including parameter mismatch, the replay marker and pruning after 24 h;
+ - per-key idempotency, including parameter mismatch, `Replayed` and pruning after 24 h;
- pending updates, later payment and expiry;
- - failure before delivery; lost responses after applying;
- - **completion after an uncertain return and after a later read**;
- - cached 5xx before and after applying;
- - 409 in flight; 429;
- - renewal across a period boundary; paging; Checkout races; call counts by method.
+ - failure before delivery; lost responses after applying; completion after an uncertain return and after a later read;
+ - cached 5xx before and after applying; 409 in flight; 429;
+ - renewal across a period boundary, with a renewal invoice;
+ - **a request that first applies after a renewal**;
+ - provider time and skew; paging; Checkout races; call counts by method.
## Review Focus
-1. **A stop-renewal request that times out while Stripe still processes it.** A later read showing renewal on must not release the exclusion. The resend with the same key returns the original result, and the owner's opposite request waits until it settles. Pinned in Task 7 (`TestTimeoutStillProcessingIsNotReleasedByANegativeRead`).
-2. **A restore racing renewal.** No restore is sent within 25 h of the period end, so P2 never gets unpaid capacity. Pinned in Task 10 (`TestRestoreRefusedNearRenewal`, `TestRestoreResendWindowEndsBeforeRenewal`) and Task 11 (`TestSeatRestoreRefusedNearRenewal`).
-3. **Invite A's applied charge, a crash, B's join, then A's retry.** The authorisation was consumed with the transition to `applied`, so A needs fresh consent. Pinned in Task 11 (`TestAppliedInviteChargeIsACreditNotAPass`, `TestConsumptionIsAtomicWithApplied`).
-4. **The hourly pass on an account with seat drift or an unresolved operation.** It sends nothing. Pinned in Task 7 (`TestPassesNeverWrite`) and Task 11 (`TestDriftPassOnlyObserves`).
-5. **A Checkout create response that was lost.** The owner reaches the same session from the page. Pinned in Task 9 (`TestLostCreateContinuedFromThePage`).
+1. **Deletion with an undelivered resume-renewal request and an already-fresh step-up proof.** The gate finishes the operation first, sees renewal on, and refuses. Pinned in Task 13 (`TestDeleteFinishesOpsBeforeChecksWithFreshProof`).
+2. **B accepts within the renewal margin while an already-paid eleventh seat is present.** B joins with no provider write. Pinned in Task 11 (`TestJoinUsesPresentPaidSeatInsideMargin`).
+3. **An unresolved seat request, then a revoke, then Confirm now.** The revoke is refused while the request is outstanding. A request whose invite is no longer pending is never resent. Pinned in Task 11 (`TestRevokeRefusedWhileUnresolved`, `TestConfirmNeverSendsForAGoneInvite`).
+4. **A house Checkout whose response is lost, then a coupon configuration change.** The resend carries the original bytes. Pinned in Task 9 (`TestCheckoutResendBytesSurviveConfigChange`, against the adapter's captured HTTP body).
+5. **A restore that first applies after renewal.** It is detected as `restore_after_renewal`, with no provider write. Pinned in Task 7 (`TestLateRestoreDetected`).
---
### Task 0: Record the rulings
**Files:** Modify `docs/superpowers/specs/2026-10-20-plans-caps-packs-design.md`:
-- §3: Paul's team-plan ruling, with the disk sentence (Call 7);
-- §4.1: team plans;
-- §4.2: Community and Business columns, with disk at "10 GB per running thing (not pooled)";
-- §9.1: the team plan item, quantity `max(members, 10)`;
-- a "Plan 6b rulings" list: Calls 1 to 16, and Call 17 as ruled ("auto first, then an operator"), with revision 4's mechanism and the provider facts it rests on.
+- §3: Paul's team-plan ruling (2026-10-25), worded as in the Spec block, including "Disk is neither multiplied nor pooled: team plans keep Personal's 10 GB per running thing, so total disk grows only through the running-things count (Call 7, accepted)".
+- §4.1: team plans (base plan, per-member multiple in thousandths, minimum, the five pooled fields, `max_members`).
+- §4.2: Community and Business columns and prices; disk "10 GB per running thing (not pooled)".
+- §9.1: the team plan is the plan item, with quantity `max(members, 10)`.
+- A "Plan 6b rulings" list: Calls 1 to 17 as ruled. Call 17 has its mechanism, the provider facts above, and Risks R1 to R3.
- [ ] **Step 1:** Make the edits.
- [ ] **Step 2: Commit** `spec: team plans and the Plan 6b rulings (Paul, 2026-10-25) in the plans and packs design (plans 6b)`.
### Task 1: Team plans and member caps in the catalog
-Accepted; unchanged from revision 3.
-
-**Files:** `internal/plans/team.go`, `team_test.go`, `catalog.go`, the example catalog (community, business, `max_members` 3) and the example book (community 600 / 500 / 450, business 6000 / 5000 / 4500). `Effective` callers pass `1` until Task 3.
+**Files:**
+- Create: `internal/plans/team.go`, `internal/plans/team_test.go`.
+- Modify:
+ - `internal/plans/catalog.go`;
+ - `internal/plans/testdata/example-catalog.json`: add `community` and `business`, and `max_members: 3` on `free` and `personal`;
+ - `internal/plans/testdata/example-pricebook.json`: community 600 / 500 / 450, business 6000 / 5000 / 4500;
+ - every `Effective` caller (`planlimits.go`, `apiaccountplan.go`, `planlapse.go`) passes `1` until Task 3.
**Interfaces:**
-- `Team{Base, PerMemberMilli, MinMembers}`, `Plan.Team`, `Plan.MaxMembers`, `MaxTeamMembers = 10000`, `ErrTeamMembers`;
-- `PooledLimits` = running things, awake hours, storage, email, bandwidth (no disk);
-- `Team.Billed`, `Team.PerMember`;
-- `Catalog.Effective(plan, packs, sponsored, members)`.
-
-Validation and the team `Effective` order are as revision 3: own limits including disk, then pooled multiplication with overflow checks, packs, scaled pooled ceilings (Call 8), and the sponsored merge.
+- Produces:
+ ```go
+ type Team struct {
+ Base string `json:"base"` // a paid, non-team plan whose pooled limits multiply
+ PerMemberMilli int `json:"per_member_milli"` // 200 = 0.2, 2000 = 2
+ MinMembers int `json:"min_members"` // billed and limited at no fewer
+ }
+ // Plan gains Team *Team `json:"team,omitempty"` and MaxMembers int `json:"max_members,omitempty"` (non-team only; 0 = no cap).
+ const MaxTeamMembers = 10000
+ var ErrTeamMembers = errors.New("team member count out of range")
+ var PooledLimits = []string{"running_things", "awake_hours_month", "storage_bytes", "email_per_day", "bandwidth_bytes_month"} // Call 7: no disk_bytes
+ func (t *Team) Billed(members int) int // max(members, MinMembers)
+ func (t *Team) PerMember() string // 200 "0.2", 2000 "2", 1250 "1.25"
+ func (c *Catalog) Effective(plan string, packs map[string]int, sponsored *Limits, members int) (Limits, error)
+ ```
+- Validation:
+ - `team.base` names a paid plan with no `team`;
+ - `per_member_milli` is 1 to 100000, and `min_members` is 1 to `MaxTeamMembers`;
+ - a team plan's own `limits` sets none of the `PooledLimits` fields;
+ - a team plan with `max_members` is refused;
+ - `max_members` ≥ 0.
+- Team `Effective`:
+ 1. Start from the team plan's own limits, its `disk_bytes` included.
+ 2. For each pooled field: `floor(base × PerMemberMilli × Billed(members) / 1000)`, overflow-checked with `math/bits` (an overflow is `ErrTeamMembers`).
+ 3. Add packs as today.
+ 4. Clamp to the ceilings. Only the pooled fields' non-zero ceilings scale by the same factor, when it is above 1 (Call 8). Idle and rate ceilings never scale.
+ 5. The sponsored merge.
+
+ Members outside 0 to `MaxTeamMembers` is `ErrTeamMembers`. On non-team plans, members is ignored.
+- Example team plans:
+ - `limits`: `sidecars_per_app` 5, `idle_seconds` 900, `memory_tier` default, `disk_bytes` 10737418240, `storage_self_serve`, `custom_domains`, `fleets`, `min_schedule_seconds` 60;
+ - `business` adds `history_days` 7;
+ - all five packs;
+ - `team`: community `{"base":"personal","per_member_milli":200,"min_members":10}`, business 2000.
-- [ ] **Step 1: Write the failing tests:**
- - `TestEffectiveCommunityAtMinimum` (4 members → 10: RunningThings 50, AwakeHoursMonth 3000, EmailPerDay 2000, StorageBytes 53687091200, BandwidthBytesMonth 107374182400, DiskBytes 10737418240, HistoryDays 0);
- - `TestEffectiveCommunityTwentyThree` (115, 6900, 4600, 123480309760, disk unchanged);
- - `TestEffectiveBusinessScalesCeilings` (12: 600, 24000, history 7);
- - `TestEffectiveTeamWithPacks` (apps 2: 60; disk 1: 21474836480);
- - `TestEffectiveIgnoresMembersOffTeam`, `TestEffectiveTeamMemberBounds`, `TestCatalogRefusesBadTeams`, `TestTeamBilledAndPerMember`.
-- [ ] **Steps 2 to 5:** run them (FAIL), implement, run with the console packages (PASS), commit `plans: team plans multiply a base plan's pooled limits per member, with a minimum; disk stays per running thing; max_members on other plans (plans 6b)`.
+- [ ] **Step 1: Write the failing tests**
+ ```go
+ func TestEffectiveCommunityAtMinimum(t *testing.T) // 4 -> 10: RunningThings 50, AwakeHoursMonth 3000, EmailPerDay 2000, StorageBytes 53687091200,
+ // BandwidthBytesMonth 107374182400, DiskBytes 10737418240, IdleSeconds 900, HistoryDays 0
+ func TestEffectiveCommunityTwentyThree(t *testing.T) // 23: RunningThings 115, AwakeHoursMonth 6900, EmailPerDay 4600, StorageBytes 123480309760, DiskBytes 10737418240
+ func TestEffectiveBusinessScalesCeilings(t *testing.T) // 12: RunningThings 600 (ceiling 200 x 24), EmailPerDay 24000, HistoryDays 7, DiskBytes 10737418240
+ func TestEffectiveTeamWithPacks(t *testing.T) // community 10 + apps 2: RunningThings 60; disk 1: DiskBytes 21474836480
+ func TestEffectiveIgnoresMembersOffTeam(t *testing.T) // personal with members 0, 1 and 50: identical
+ func TestEffectiveTeamMemberBounds(t *testing.T) // -1 and 10001: ErrTeamMembers
+ func TestCatalogRefusesBadTeams(t *testing.T) // base missing; base free; base a team; milli 0; min 0; team limits with running_things; team with max_members; max_members -1
+ func TestTeamBilledAndPerMember(t *testing.T) // Billed(3)=10, Billed(12)=12; "0.2", "2", "1.25"
+ ```
+- [ ] **Step 2: Run** `go test ./internal/plans/ -run 'Effective|Team|Catalog'`. Expected: FAIL.
+- [ ] **Step 3: Implement,** and fix the callers.
+- [ ] **Step 4: Run** `go test ./internal/plans/ ./internal/console/ -run 'Effective|Team|Catalog|PriceBook|AccountPlan|PlanLimits'`. Expected: PASS.
+- [ ] **Step 5: Commit** `plans: team plans multiply a base plan's pooled limits per member, with a minimum; disk stays per running thing; max_members on other plans (plans 6b)`.
### Task 2: Public export schema 3 and money formatting
-Accepted; unchanged.
+**Files:**
+- Modify: `internal/plans/export.go`, `export_test.go`, the regenerated golden `internal/plans/testdata/example-public-pricebook.json`, and the `cmd/pricebook-export` tests.
+- Create: `docs/superpowers/specs/2026-10-25-public-price-export-schema-3.md` (schema 2 plus these changes, and a "what changed" list for the website).
-- Schema 3: `publicPlan.Team` (base, `per_member`, `min_members`, `pooled` without disk) and `MaxMembers`; `FormatMinor`.
-- A team plan's `annual_minor` is per member, and its limits are shown at the minimum. Order: free, then `annual × max(1, min)`, then key.
-- Add the schema-3 document for the website.
-- **Tests:** `TestPublicExportSchema3Team`, `TestPublicExportGolden`, `TestFormatMinor`.
-- [ ] **Steps 1 to 5:** write the failing tests, run them, implement, regenerate the golden, run them again, commit `plans: public export schema 3 prices team plans per member, with minimum and multiple (plans 6b)`.
+**Interfaces:**
+- Produces:
+ ```go
+ // publicExport.Schema = 3. publicPlan gains:
+ Team *publicTeam `json:"team,omitempty"`
+ MaxMembers int `json:"max_members,omitempty"`
+ type publicTeam struct {
+ Base string `json:"base"`
+ PerMember string `json:"per_member"`
+ MinMembers int `json:"min_members"`
+ Pooled []string `json:"pooled"` // PooledLimits, in order; no disk
+ }
+ func FormatMinor(currency string, minor int64) string // "$28", "€24", "£4.50", "$0.07"
+ ```
+- A team plan's `annual_minor` is per member per year. Its export `limits` carry the pooled fields at `min_members`. Order: free first, then `annual_minor[default] × max(1, min_members)`, then key.
+
+- [ ] **Step 1: Write the failing tests**
+ ```go
+ func TestPublicExportSchema3Team(t *testing.T) // community team {personal, "0.2", 10, pooled 5}; annual usd 600; running_things 50; disk 10737418240; personal max_members 3;
+ // order free, personal, community, business
+ func TestPublicExportGolden(t *testing.T)
+ func TestFormatMinor(t *testing.T)
+ ```
+- [ ] **Step 2: Run** `go test ./internal/plans/ ./cmd/pricebook-export/ -run 'PublicExport|FormatMinor|Golden'`. Expected: FAIL.
+- [ ] **Step 3: Implement,** then regenerate the golden.
+- [ ] **Step 4: Run** again. Expected: PASS.
+- [ ] **Step 5: Commit** `plans: public export schema 3 prices team plans per member, with minimum and multiple (plans 6b)`.
### Task 3: Seats, the member lock and membership transitions
-Accepted; unchanged from revision 3.
+**Files:**
+- Create: `internal/console/planmembers.go`, `planmembers_test.go`.
+- Modify:
+ - `store.go`: `migratePlanSeats()` (`account_plans.seats INTEGER NOT NULL DEFAULT 0`, guarded), plus `acceptInviteTx`, `addMemberTx` and `removeMemberTx`, which the existing functions wrap;
+ - `accountplans.go`: `Seats` in the row, the columns, `SetAccountPlan` and the upsert; `SaveBillingSync`'s guard compares seats;
+ - `planlapse.go`: `applyAccountPlan` and `lapseStarted` carry seats;
+ - `planlimits.go`: `EffectiveLimits` and `publishAccountLimits` use `planMembers`;
+ - `apiaccountplan.go`: the operator door passes seats 0 and validates with the live count;
+ - `server.go` (`handleInvite`, `handleAcceptInvite`, `handleRevokeInvite`) and `ownership.go` (`handleRemoveMember`): the member lock, re-checks inside it, `membershipTransition`;
+ - `plancaps.go`, `plancaps_copy.go`;
+ - `cmd/console/member.go`: through `Store.MembershipTransition`, with the catalog loaded when `CARLOS_PLAN_CATALOG` is set.
**Interfaces:**
-- `SetAccountPlan(..., seats, ...)`, `applyAccountPlan(..., seats, ...)`;
-- `MemberCount`, `planMembers`, `lockMembers`, `membershipFell`;
-- `Store.MembershipTransition(accountID, cat, old, write, now)`, which counts before and after in one transaction, bumps the revision, and marks the lapse on a fall;
-- `membershipTransition` (wraps `transitionAccountPlan`);
-- `checkMemberCap`.
-
-Every invite, join, revoke and removal runs under `lockMembers`, with accept's re-checks inside it. The CLI uses `Store.MembershipTransition`.
+- Produces:
+ ```go
+ func (s *Store) SetAccountPlan(accountID int64, plan string, packs map[string]int, seats int, source string,
+ sponsored *plans.Limits, reason, by string, now time.Time) (int64, error)
+ func (s *Server) applyAccountPlan(ctx context.Context, acct *Account, plan string, packs map[string]int, seats int,
+ source string, sponsored *plans.Limits, reason, by string, now time.Time) error
+ func (s *Store) MemberCount(accountID int64) (int, error) // owners + members; never invites or services
+ func (s *Server) planMembers(row *AccountPlanRow, accountID int64) (int, error) // row.Seats when > 0, else MemberCount
+ func (s *Server) lockMembers(sqid string) func()
+ func membershipFell(cat *plans.Catalog, row *AccountPlanRow, before, after int) bool // live-counted team row, paid, not sponsored, LimitsFell
+ // MembershipTransition: one transaction; counts before and after; on a live-counted team row whose Billed count changed,
+ // bumps the revision; on a fall, marks the lapse and deletes the lapse caps' states. changed reports the bump.
+ func (s *Store) MembershipTransition(accountID int64, cat *plans.Catalog, old *AccountPlanRow,
+ write func(tx *sql.Tx) error, now time.Time) (changed bool, err error)
+ func (s *Server) membershipTransition(ctx context.Context, acct *Account, now time.Time, write func(tx *sql.Tx) error) error // transitionAccountPlan around it
+ func (s *Server) checkMemberCap(acct *Account, adding int) error // members+adding > MaxMembers; nil for team plans, sponsored rows, no catalog
+ ```
+- **Every invite, join, revoke and removal runs under `lockMembers(sqid)`.**
+ - `handleInvite` counts pending invites, checks the cap (`adding = pending + 1`), and creates the invite inside the lock.
+ - `handleAcceptInvite` finds the invite's account, takes the lock, and re-checks the invite (`PendingInviteFor`), existing membership and `checkMemberCap(acct, 1)` before writing.
+ - The limits pass retries a failed publication (`published_revision < revision`).
+- Draft copy:
+ - `browser.cap.members` "This plan has room for %d members. Move to a team plan to add more.";
+ - `browser.cap.members_join` "This account is full on its plan. Ask an owner to move it to a team plan.";
+ - `browser.cap.free_account` "You already own a free account, and each person can own one. Upgrade that account to create another, or ask an operator.";
+ - `cli.` twins in lower case.
-- **Tests** (as revision 2): `TestTeamLimitsFollowMembers`, `TestSeatsPinTeamLimits`, `TestMembershipRiseReconvergesAndPublishes`, `TestMembershipFallStartsLapse`, `TestMembershipNoLimitChangeWritesNothing`, `TestMembershipPublishFailureRetried`, `TestCLIMembershipTransition`, `TestConcurrentInvitesRespectCap`, `TestConcurrentAcceptsRespectCap`, `TestAcceptRechecksInsideLock`, `TestMemberCapAtInvite`, `TestMemberCountExcludesInvitesAndServices`.
-- [ ] **Steps 1 to 5:** write the failing tests, run them (FAIL), implement, run them with the account-plan, lapse and invite suites (PASS), commit `console: seats on the plan row; every membership change goes through the plan transition under a member lock; member caps checked inside it (plans 6b)`.
+- [ ] **Step 1: Write the failing tests**
+ ```go
+ func TestTeamLimitsFollowMembers(t *testing.T) // operator community (seats 0); 12 members: RunningThings 60; remove 2: 50 (min 10)
+ func TestSeatsPinTeamLimits(t *testing.T) // seats 14 with 3 members: RunningThings 70
+ func TestMembershipRiseReconvergesAndPublishes(t *testing.T) // community seats 0, 10 -> 11: revision+1, record republished, grace pass ran
+ func TestMembershipFallStartsLapse(t *testing.T) // operator community, 14 -> 11: LapseSince set, lapse cap states reset
+ func TestMembershipNoLimitChangeWritesNothing(t *testing.T) // 4 -> 5 (billed 10 both): no bump, no publish
+ func TestMembershipPublishFailureRetried(t *testing.T) // publish fails: published_revision < revision; the limits pass publishes
+ func TestCLIMembershipTransition(t *testing.T) // cmd/console member -remove on a live-counted community: revision bumped, LapseSince set
+ func TestConcurrentInvitesRespectCap(t *testing.T) // personal max 3, 2 members, two invites in parallel: one created, one refused
+ func TestConcurrentAcceptsRespectCap(t *testing.T) // personal, 2 members, two pending: parallel accepts: members 3, one refused, its invite still pending
+ func TestAcceptRechecksInsideLock(t *testing.T) // revoke lands while accept waits: accept refused as gone
+ func TestMemberCapAtInvite(t *testing.T) // personal 2 members + 1 pending: refused; community: allowed; sponsored: allowed
+ func TestMemberCountExcludesInvitesAndServices(t *testing.T) // 2 members, 1 pending invite, 1 service credential: 2
+ ```
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TeamLimits|SeatsPin|Membership|CLIMembership|Concurrent(Invites|Accepts)|AcceptRechecks|MemberCap|MemberCount'` and `go test ./cmd/console/ -run Member`. Expected: FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'AccountPlan|PlanLimits|Lapse|Invite|ClaimSQL'`. Expected: PASS.
+- [ ] **Step 5: Commit** `console: seats on the plan row; every membership change goes through the plan transition under a member lock; member caps checked inside it (plans 6b)`.
-### Task 4: Provider boundary and a payment-faithful fake
+### Task 4: Provider boundary, prepared requests and a payment-faithful fake
**Files:** `internal/billing/billing.go`, `recognise.go`, `billingtest/fake.go`, and their tests.
**Interfaces:**
- Produces:
```go
- // Item gains ItemID. Subscription gains PendingUpdate, PendingExpires, Collecting; Renewing() = Live && !CancelAtPeriodEnd.
- // Purchase gains Seats.
+ // Item gains ItemID. Subscription gains PendingUpdate bool, PendingExpires time.Time, Collecting bool,
+ // ProviderTime time.Time (the read's Date header); Renewing() = Live && !CancelAtPeriodEnd. Purchase gains Seats.
type Proration string // ProrateNone | ProrateNow
type ItemChange struct { ItemID, PriceID string; Quantity int64; Delete bool }
type ChangeRequest struct { Subscription string; Items []ItemChange; Proration Proration; ProrationDate time.Time; IdempotencyKey string }
+ type CheckoutItem struct { PriceID string; Quantity int64 }
+ type CheckoutRequest struct {
+ Customer, AccountSqid, IntentID, Book, Currency string
+ Items []CheckoutItem
+ SuccessURL, CancelURL string
+ Coupon string // the resolved coupon id, "" for none; never a flag (finding 4)
+ ExpiresAt time.Time
+ IdempotencyKey string
+ }
type CheckoutState string // open | complete | expired
type CheckoutInfo struct { ID, URL, Subscription, Customer, IntentID string; State CheckoutState; ExpiresAt time.Time }
- type CheckoutItem struct { PriceID string; Quantity int64 }
- type CheckoutRequest struct { Customer, AccountSqid, IntentID, Book, Currency string; Items []CheckoutItem; SuccessURL, CancelURL string; House bool; ExpiresAt time.Time; IdempotencyKey string }
+ // Prepared is a write exactly as the adapter will send it: opaque to the console, persisted before the first send,
+ // resent only verbatim.
+ type Prepared struct { Kind string; Method, Path string; Body []byte; Key string }
+ type Result struct {
+ Subscription *Subscription
+ Checkout *CheckoutInfo
+ Customer string
+ Replayed bool
+ ProviderTime time.Time
+ }
+ type InvoiceQuantities struct { Invoice string; PeriodStart time.Time; ByPrice map[string]int64 }
const MaxListPages = 10
- // Outcome classes of a write (provider facts 1-5). The adapter returns exactly one.
var (
- ErrPaymentFailed = errors.New("billing: payment failed") // definite: declined, nothing applied
- ErrRefused = errors.New("billing: request refused") // definite: an executed or validation 4xx; nothing applied
- ErrNotExecuted = errors.New("billing: request not executed") // 429 or a pre-execution refusal: safe to resend the same request (fact 2)
- ErrInFlight = errors.New("billing: request still executing") // 409 on the same key: wait, then resend the same request (fact 3)
- ErrNoResponse = errors.New("billing: no response") // transport error or timeout: resend the same request within the window (fact 4)
- ErrIndeterminate = errors.New("billing: outcome indeterminate") // 5xx: cached, a resend returns it again (fact 5)
- ErrIncomplete = errors.New("billing: list incomplete")
+ ErrPaymentFailed = errors.New("billing: payment failed") // definite: declined, nothing applied
+ ErrRefused = errors.New("billing: request refused") // definite: an executed or validation 4xx; nothing applied
+ ErrNotExecuted = errors.New("billing: request not executed") // 429 or another pre-execution refusal: resend the same bytes (fact 2)
+ ErrInFlight = errors.New("billing: request still executing") // 409 on the same key: wait, then resend the same bytes (fact 3)
+ ErrNoResponse = errors.New("billing: no response") // transport error or timeout: resend the same bytes inside the window (fact 4)
+ ErrIndeterminate = errors.New("billing: outcome indeterminate") // 5xx: cached; a resend returns it again (fact 5)
+ ErrIncomplete = errors.New("billing: list incomplete") // more than MaxListPages pages
ErrNoHouseCoupon = errors.New("billing: no house coupon configured")
)
- // Provider gains: EnsureCustomer, LiveSubscriptions (exhaustive), CustomerCheckouts (exhaustive), StartCheckout,
- // Checkout, ExpireCheckout (returns the session's state), ChangeItems, SetRenewal, PortalURL (as revision 3), and every
- // write also reports Replayed bool (fact 7) through its result.
+ type Provider interface {
+ // 6a's methods (ParseEvent, Subscription, CheckoutSubscription, Check), with CustomerSubscriptions removed (Task 5), plus:
+ PrepareCustomer(accountSqid, key string) (Prepared, error)
+ PrepareCheckout(req CheckoutRequest) (Prepared, error)
+ PrepareExpire(sessionID, key string) (Prepared, error)
+ PrepareChange(req ChangeRequest) (Prepared, error)
+ PrepareRenewal(subscription string, renew bool, key string) (Prepared, error)
+ Send(ctx context.Context, p Prepared) (Result, error) // exactly one HTTP request; outcome classes as in Task 5
+ LiveSubscriptions(ctx context.Context, customer string) ([]string, error) // exhaustive
+ CustomerCheckouts(ctx context.Context, customer string, createdAfter time.Time) ([]CheckoutInfo, error) // exhaustive
+ Checkout(ctx context.Context, sessionID string) (CheckoutInfo, error)
+ RenewalInvoice(ctx context.Context, subscription string, periodStart time.Time) (InvoiceQuantities, error) // exhaustive lines
+ PortalURL(ctx context.Context, customer, returnURL, key string) (string, error)
+ }
func FindItem(sub *Subscription, prices PriceMap, kind, name string) (Item, bool)
```
-- `Recognise` handles team quantities.
-- **The Fake** gains, beyond revision 3's cases:
- - `CompleteLater(n)`: the next write returns `ErrNoResponse` and applies after `n` further reads, modelling a request still processing;
- - `Cached500Before` and `Cached500After`: a 5xx cached for the key, with or without having applied;
- - `InFlight(n)`: the next `n` same-key sends get 409;
- - `RateLimit`: 429, not executed;
- - `PruneKeysOlderThan(d)`;
- - `Replayed` on responses served from a stored result.
- - Same-key sends with different parameters return an idempotency error.
-
-- [ ] **Step 1: Write the failing tests:**
- - `TestRecogniseTeamSeats`, `TestRecogniseTeamRefuses`, `TestFindItem`;
- - `TestFakeIdempotency` (same key and same parameters: the stored result, `Replayed`; different parameters: an error);
- - `TestFakeCompleteLater`;
- - `TestFakeCached500` (resend: the same 500, applied or not as configured);
- - `TestFakeInFlightAndRateLimit`, `TestFakePrune`;
- - `TestFakePendingPayLaterExpire`, `TestFakeFailBeforeDelivery`, `TestFakeLostResponse`, `TestFakeRenew`, `TestFakePagingAndIncomplete`, `TestFakeCheckoutRaces`.
-- [ ] **Steps 2 to 5:** run `go test ./internal/billing/... -run 'Recognise|FindItem|Fake'` (FAIL), implement (adapter stubs), run again with `go build ./...` (PASS), commit `billing: write outcome classes from the provider's idempotency rules, exhaustive lists, and a fake that models in-flight completion, cached 5xx, 409, 429, pruning, pending payments and renewal (plans 6b)`.
-
-### Task 5: Stripe adapter writes, outcome classes, discovery migration and readiness
+- `Recognise`: a team plan item needs quantity `MinMembers` to `MaxTeamMembers`, and sets `Seats`. Other plan items need 1.
+- **The Fake:**
+ - `Prepare*` encodes a canonical JSON body; `Send` checks the key against the body (a mismatch is an idempotency error).
+ - It models: `FailPayment`, `DeclineHard`, `PayPending`, `ExpirePending`, `FailBeforeDelivery`, `LoseNextResponse`, `CompleteLater(n)`, `Cached500Before`, `Cached500After`, `InFlight(n)`, `RateLimit`, `PruneKeysOlderThan`, `Replayed`.
+ - `Renew(sub)` moves the period a year on, keeps the items, drops any pending update, and writes a renewal invoice of the items' quantities.
+ - `ApplyAfterRenewal(key)` holds a sent request and applies it after the next `Renew`.
+ - `ProviderClock` and `SkewBy(d)`; `PageSize`; Checkout sessions and races; `CallsBy` per method.
+
+- [ ] **Step 1: Write the failing tests**
+ ```go
+ func TestRecogniseTeamSeats(t *testing.T)
+ func TestRecogniseTeamRefuses(t *testing.T)
+ func TestFindItem(t *testing.T)
+ func TestFakePreparedIdempotency(t *testing.T) // same Prepared twice: stored result, Replayed; same key, other body: error
+ func TestFakeCompleteLater(t *testing.T)
+ func TestFakeCached500(t *testing.T)
+ func TestFakeInFlightAndRateLimit(t *testing.T)
+ func TestFakePrune(t *testing.T)
+ func TestFakePendingPayLaterExpire(t *testing.T)
+ func TestFakeFailBeforeDeliveryAndLostResponse(t *testing.T)
+ func TestFakeRenewWritesInvoice(t *testing.T)
+ func TestFakeApplyAfterRenewal(t *testing.T)
+ func TestFakePagingAndIncomplete(t *testing.T)
+ func TestFakeCheckoutRaces(t *testing.T)
+ ```
+- [ ] **Step 2: Run** `go test ./internal/billing/... -run 'Recognise|FindItem|Fake'`. Expected: FAIL.
+- [ ] **Step 3: Implement,** with adapter stubs.
+- [ ] **Step 4: Run** again, plus `go build ./...`. Expected: PASS.
+- [ ] **Step 5: Commit** `billing: prepared requests sent verbatim, outcome classes, exhaustive lists, renewal invoices, and a fake that models every unclear-outcome and renewal case (plans 6b)`.
+
+### Task 5: Stripe adapter: prepare, send, classify; discovery; readiness
**Files:**
- `internal/billingstripe/client.go`, `customer.go`, `adapter.go`;
- `cmd/console/billing.go`;
-- `internal/console/billingpass.go`: discovery migrated.
+- `internal/console/billingpass.go` (discovery).
**Interfaces:**
-- The client keeps 6a's **no automatic retries**. Each call is one HTTP request; resends are the console's (Task 7).
-- **Outcome classification** (facts 1 to 5):
-
- | HTTP answer | Class |
+- **`Prepare*`** builds the complete form body, with keys sorted, so the same request always produces the same bytes. It includes:
+ - mode, currency, line items by price id, `adaptive_pricing[enabled]=false`, `billing_address_collection=required`, `customer_update[address]=auto`, `automatic_tax[enabled]=true`, `expires_at`, success and cancel URLs;
+ - `discounts[0][coupon]=<req.Coupon>` when set, otherwise `allow_promotion_codes=true`;
+ - metadata on the session and on `subscription_data`;
+ - for changes: items by id, price, quantity or deleted; `proration_behavior`; `payment_behavior=pending_if_incomplete` for `ProrateNow`; `proration_date` exactly as given;
+ - for renewal: `cancel_at_period_end`;
+ - for expiry: the session path;
+ - for a customer: metadata only, no address.
+- **`Send`** sends `Body` verbatim with `Idempotency-Key: Key`, as one HTTP request with no client retry. It decodes by `Kind`, and reports `Replayed` (`Idempotent-Replayed`) and `ProviderTime` (`Date`).
+- **Outcome classes:**
+
+ | Answer | Class |
| --- | --- |
- | 2xx | success, with `Replayed` from `Idempotent-Replayed` |
- | 402, or a `card_error` | `ErrPaymentFailed` |
- | 409 with an idempotency conflict "still executing" | `ErrInFlight` |
- | 409 or 400 with type `idempotency_error` for mismatched parameters | a programming error, panic in tests, logged in production, the operation marked `unresolved` |
+ | 2xx | success |
+ | 402 or `card_error` | `ErrPaymentFailed` |
+ | 409 with a same-key request still executing | `ErrInFlight` |
+ | an idempotency parameter mismatch | a programming error: panic in tests; logged and the operation `unresolved` in production |
| 429 | `ErrNotExecuted` |
| other 4xx | `ErrRefused` |
| 5xx | `ErrIndeterminate` |
| transport error or timeout | `ErrNoResponse` |
-- Lists: `LiveSubscriptions` and `CustomerCheckouts` page with `starting_after` over every status, up to 10 pages, else `ErrIncomplete`.
-- **Discovery migration** (the inherited caller): 6a's `billingDiscoveryPass` calls `LiveSubscriptions` instead of the capped `CustomerSubscriptions`. On `ErrIncomplete` it logs and changes nothing; it is an observing net, not a safety decision. `CustomerSubscriptions` is deleted once it has no caller.
-- Mappings, the portal and coupon checks, and the configuration variables are as revision 3.
-
-- [ ] **Step 1: Write the failing tests:**
- - `TestOutcomeClasses`, one per row of the table;
- - `TestReplayedHeader`, `TestNoClientRetry`;
- - `TestChangeItemsSendsProration` (`proration_date` sent exactly as given);
- - `TestStartCheckoutCollectsAddress`, `TestEnsureCustomerSendsNoAddress`, `TestExpireCheckoutStates`;
- - `TestLiveSubscriptionsPagesToCompletion` (200 ended + 1 active on page 3: returned, 3 requests);
- - `TestLiveSubscriptionsEmptyListIsOneRequest`, `TestLiveSubscriptionsIncomplete`, `TestCustomerCheckoutsPages`;
- - `TestDiscoveryUsesExhaustiveList` (console);
- - `TestCollectingOf`, `TestSetRenewal`, `TestCheckRefusesUnlockedPortal`, `TestCheckRefusesBadHouseCoupon`, `TestBillingConfigPortalAndCoupon`.
-- [ ] **Steps 2 to 5:** run them (FAIL), implement, run them with `GOOS=darwin go vet ./internal/billingstripe/` (PASS), commit `billingstripe: outcome classes from Stripe's idempotency rules, exhaustive paged lists, discovery migrated, readiness for the locked portal and house coupon (plans 6b)`.
+- **The house coupon** moves from `ProviderConfig` to `BillingConfig.HouseCoupon`. The console resolves it into `CheckoutRequest.Coupon` when it creates an intent. Readiness still verifies the configured coupon: valid, this mode, 100% off, no `amount_off`, `forever`, unrestricted.
+- **The portal check:** active; this mode; payment method update on; invoice history on; subscription update and cancel off; customer update off or limited to address, name and tax id.
+- `LiveSubscriptions` and `CustomerCheckouts` page with `starting_after` over every status, up to 10 pages. `RenewalInvoice` lists the subscription's invoices with `billing_reason=subscription_cycle` and a period start equal to the one given, then pages its lines exhaustively.
+- **Discovery is migrated:** 6a's `billingDiscoveryPass` calls `LiveSubscriptions`. On `ErrIncomplete` it logs and changes nothing; it is an observing net. `CustomerSubscriptions` is deleted.
+- Configuration: `CARLOS_STRIPE_PORTAL_CONFIGURATION` (required, `bpc_`), `CARLOS_STRIPE_HOUSE_COUPON` (optional).
+
+- [ ] **Step 1: Write the failing tests**
+ ```go
+ func TestPrepareIsDeterministic(t *testing.T) // same request twice: identical bytes; httptest captures exactly those bytes
+ func TestPrepareCheckoutCarriesResolvedCoupon(t *testing.T)
+ func TestSendVerbatimOneRequest(t *testing.T) // 500 or timeout: one HTTP request, body equals Prepared.Body
+ func TestOutcomeClasses(t *testing.T) // one case per table row
+ func TestReplayedAndProviderTime(t *testing.T)
+ func TestLiveSubscriptionsPagesToCompletion(t *testing.T) // 200 ended + 1 active on page 3: 3 requests
+ func TestLiveSubscriptionsEmptyListIsOneRequest(t *testing.T)
+ func TestLiveSubscriptionsIncomplete(t *testing.T)
+ func TestCustomerCheckoutsPages(t *testing.T)
+ func TestRenewalInvoiceQuantities(t *testing.T) // lines on two pages: summed by price
+ func TestDiscoveryUsesExhaustiveList(t *testing.T)
+ func TestCollectingOf(t *testing.T)
+ func TestCheckRefusesUnlockedPortal(t *testing.T) // inactive; other mode; payment method update off; invoice history off; update on; cancel on; email allowed
+ func TestCheckRefusesBadHouseCoupon(t *testing.T) // invalid; other mode; 50%; once; amount_off; restricted
+ func TestBillingConfigPortalAndCoupon(t *testing.T)
+ ```
+- [ ] **Step 2: Run** `go test ./internal/billingstripe/ ./cmd/console/ ./internal/console/ -run 'Prepare|SendVerbatim|OutcomeClasses|ReplayedAnd|LiveSubscriptions|CustomerCheckouts|RenewalInvoice|DiscoveryUses|CollectingOf|CheckRefuses|BillingConfig'`. Expected: FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** again, plus `GOOS=darwin go vet ./internal/billingstripe/`. Expected: PASS.
+- [ ] **Step 5: Commit** `billingstripe: deterministic prepared requests sent verbatim, outcome classes, exhaustive lists and renewal invoices; discovery migrated; readiness for the locked portal and house coupon (plans 6b)`.
### Task 6: Billing state: seats, facts, intents, house, retirement
-Accepted; unchanged from revision 3.
+**Files:** `internal/console/billingstore.go`, `billingsync.go`, `store_gate.go`, and their tests.
-- `billing_accounts` gains plan, seats, paid seats, live, collecting, pending update, pending expiry, and seats checked at.
-- New tables: `billing_checkout_intents` (the whole request, five states), `billing_house`, `billing_retirements`.
-- `decideBilling` carries seats and the facts through 6a's `applyBillingPlan` → `SaveBillingSync` (one transaction).
-- 6a integration tests.
-- One addition: `billing_accounts.seat_drift_at` and `seat_drift_members`, written by the pass (Task 11).
-- **Tests:** `TestDecideTeamSeatsHoldUntilRenewal`, `TestDecideUpgradeResetsSeats`, `TestDecideNewSubscriptionClearsSeats`, `TestDecideSavesFacts`, `TestSyncSeatsGoThroughOneTransaction`, `TestDiscoveryThenSeats`, `TestPendingReplacementThenPayment`, `TestMissingClosureRacesSeatWrite`, `TestCheckoutIntentRoundTrip`, `TestIntentTerminal`, `TestBillingHouseOnOff`, `TestRetirementRowsExpire`, `TestBillingRenewingUsesFacts`.
-- [ ] **Steps 1 to 5:** write the failing tests, run them (FAIL), implement, run them (PASS), commit `console: billing keeps team seats and neutral provider facts through 6a's one transaction; Checkout intents, house and retirement rows (plans 6b)`.
+**Interfaces:**
+- Produces:
+ ```go
+ // billingAccount gains Plan; Seats (current team quantity); PaidSeats (the period's highest paid); Live, Collecting,
+ // PendingUpdate; PendingExpires; SeatsCheckedAt; SeatDriftAt, SeatDriftMembers; CustomerAttempt int;
+ // CustomerPrepared *billing.Prepared; CustomerFirstSentAt.
+ // planChange gains Seats (0 for non-team plans).
+ func billingRenewing(b *billingAccount) bool // Live && !CancelAtPeriodEnd
+ type checkoutIntent struct {
+ AccountID int64
+ ID, Session, URL string
+ Book, Plan, Currency string
+ Seats int
+ Packs map[string]int
+ Prepared billing.Prepared // the create, exactly as sent
+ ExpirePrepared *billing.Prepared // set when an expiry is prepared
+ State string // intentCreating | intentOpen | intentCompleted | intentExpired | intentAbandoned
+ CreatedAt, ExpiresAt, FirstSentAt, ReturnedAt, ResolvedAt time.Time
+ }
+ func intentTerminal(ci *checkoutIntent) bool
+ func (s *Store) PutCheckoutIntent(ci checkoutIntent) error
+ func (s *Store) CheckoutIntent(accountID int64) (*checkoutIntent, error)
+ func (s *Store) CheckoutIntentBySession(session string) (*checkoutIntent, error)
+ func (s *Store) NonTerminalCheckoutIntents(limit int) ([]checkoutIntent, error)
+ func (s *Store) SetBillingHouse(accountID int64, on bool, by, note string, now time.Time) error
+ func (s *Store) BillingHouse(accountID int64) (bool, error)
+ func (s *Store) BeginRetirement(accountID int64, by string, now time.Time) error
+ func (s *Store) EndRetirement(accountID int64) error
+ func (s *Store) Retiring(accountID int64, now time.Time) (bool, error) // rows older than retirementTTL (1 h) are stale and cleared
+ ```
+- Schema (guarded `ALTER TABLE`s on `billing_accounts`; new tables `NonApp`):
+ - `billing_accounts` gains `plan`, `seats`, `paid_seats`, `live`, `collecting`, `pending_update`, `pending_expires`, `seats_checked_at`, `seat_drift_at`, `seat_drift_members`, `customer_attempt`, `customer_prepared`, `customer_first_sent_at`.
+ - `billing_checkout_intents(account_id INTEGER PRIMARY KEY, intent_id TEXT NOT NULL UNIQUE, session TEXT NOT NULL DEFAULT '', url TEXT NOT NULL DEFAULT '', book TEXT NOT NULL, plan TEXT NOT NULL, currency TEXT NOT NULL, seats INTEGER NOT NULL DEFAULT 0, packs TEXT NOT NULL DEFAULT '{}', prepared BLOB NOT NULL, expire_prepared BLOB, state TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, first_sent_at INTEGER NOT NULL DEFAULT 0, returned_at INTEGER NOT NULL DEFAULT 0, resolved_at INTEGER NOT NULL DEFAULT 0)`, with a partial unique index on `session` where non-empty.
+ - `billing_house(account_id INTEGER PRIMARY KEY, set_by TEXT NOT NULL, note TEXT NOT NULL, set_at INTEGER NOT NULL)`.
+ - `billing_retirements(account_id INTEGER PRIMARY KEY, started_by TEXT NOT NULL, started_at INTEGER NOT NULL)`.
+- `decideBilling`:
+ - copies the facts;
+ - paid and recognised: `Next.Plan`, `Next.Seats`;
+ - `PaidSeats = Purchase.Seats` on a new period, plan or subscription identity, else the max;
+ - `planChange.Seats = PaidSeats`;
+ - ended clears the team fields.
+
+ All of it goes through 6a's `applyBillingPlan` → `SaveBillingSync`, one transaction.
+
+- [ ] **Step 1: Write the failing tests**
+ ```go
+ func TestDecideTeamSeatsHoldUntilRenewal(t *testing.T) // community 14 then 11 same period: Seats 14; raised to 12: 14; new period with 11: 11
+ func TestDecideUpgradeResetsSeats(t *testing.T) // personal -> business x 10 same period: PaidSeats 10
+ func TestDecideNewSubscriptionClearsSeats(t *testing.T) // old sub ended with PaidSeats 20, new sub community x 10: PaidSeats 10
+ func TestDecideSavesFacts(t *testing.T)
+ func TestSyncSeatsGoThroughOneTransaction(t *testing.T) // a trigger failing the plan write: billing row and seats unchanged
+ func TestDiscoveryThenSeats(t *testing.T)
+ func TestPendingReplacementThenPayment(t *testing.T)
+ func TestMissingClosureRacesSeatWrite(t *testing.T) // a hook between steps; both orders end consistent
+ func TestCheckoutIntentRoundTrip(t *testing.T) // Prepared bytes round-trip exactly
+ func TestIntentTerminal(t *testing.T)
+ func TestBillingHouseOnOff(t *testing.T)
+ func TestRetirementRowsExpire(t *testing.T) // Retiring true; after 1 h false and cleared
+ func TestBillingRenewingUsesFacts(t *testing.T)
+ ```
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'DecideTeam|DecideUpgrade|DecideNewSubscription|DecideSaves|SyncSeats|DiscoveryThenSeats|PendingReplacementThen|MissingClosureRaces|CheckoutIntent|IntentTerminal|BillingHouse|Retirement|BillingRenewing'`. Expected: FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'Decide|Sync|BillingWebhook|BillingSyncPass|ClaimSQL'`. Expected: PASS.
+- [ ] **Step 5: Commit** `console: billing keeps team seats, provider facts and prepared requests through 6a's one transaction; intents, house and retirement rows (plans 6b)`.
-### Task 7: The billing hold, operations and their finality
+### Task 7: The billing hold, operations, finality and late-restore detection
**Files:**
-- Create: `internal/console/billinghold.go`, `billingops.go`, their tests, and `billinglint_test.go`.
+- Create: `internal/console/billinghold.go`, `billingops.go`, `billinglate.go`, their tests, and `billinglint_test.go`.
- Modify:
- - `billingsync.go`: `syncSubscription` becomes lookup, `holdBilling`, then `syncSubscriptionLocked`; `settleOpsLocked` runs after each `applyBillingRead`;
- - `billingpass.go`: readiness backoff, and observation of operations (reads and problems only);
+ - `billingsync.go`: lookup → `holdBilling` → `syncSubscriptionLocked`; after each `applyBillingRead`, `settleOpsLocked`, then `lateRestoreCheckLocked`;
+ - `billingpass.go`: readiness backoff, and operation observation (reads and problems only);
- `server.go`: `POST /a/{sqid}/billing/confirm`;
- - `store_gate.go`, `billingstore.go` (`problemOperationUnresolved`), `apibilling.go` (its close branch);
- - the claim entries for the confirm route.
+ - `store_gate.go` (`billing_operations`);
+ - `billingstore.go` (problem reasons `operation_unresolved`, `restore_after_renewal`);
+ - `apibilling.go` (the `operation_unresolved` close branch);
+ - the claim entries.
**Interfaces:**
- Produces:
@@ -405,350 +696,619 @@ Accepted; unchanged from revision 3.
func (s *Server) syncSubscriptionLocked(h billingHold, ctx context.Context, acct *Account, subscriptionID string, now time.Time) error
func (s *Server) refreshLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) (*billingAccount, *billing.Subscription, error)
func (s *Server) allowanceLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) (*billingAccount, *billing.Subscription, billing.Purchase, error)
-
- const (
- restoreMargin = 25 * time.Hour
- resendLifetime = 23 * time.Hour // under Stripe's 24 h key retention (fact 6)
- periodMargin = time.Hour
- handlerResends = 3 // backoff 1 s, 2 s, 4 s
- )
+ const (restoreMargin = 25 * time.Hour; resendLifetime = 23 * time.Hour; periodMargin = time.Hour; maxSkew = 5 * time.Minute; handlerRetries = 3)
+ func skewOK(sub *billing.Subscription, now time.Time) bool // |now - sub.ProviderTime| <= maxSkew
+ const (opSending = "sending"; opUnresolved = "unresolved"; opPending = "pending"; opApplied = "applied"; opFailed = "failed"; opAbandoned = "abandoned")
+ func opOutstanding(state string) bool // sending | unresolved | pending (Invariant 7)
type billingOp struct {
- ID, Subscription, Kind string // Kind: opPack | opPlan | opSeat | opRestore | opRenewal
+ ID, Subscription, Kind string // opPack | opPlan | opSeat | opRestore | opRenewal
AccountID int64
PeriodEnd time.Time
- Request billing.ChangeRequest // exact; never edited after insert
- Renew *bool
- InviteToken string
- AuthorisedBy string // the invite token whose authorisation an opSeat consumes
- State string // opSending | opUnresolved | opPending | opApplied | opFailed | opAbandoned
- Indeterminate bool // a cached 5xx: no resend (fact 5)
+ Target opTarget // what a read must show: item price -> quantity, or CancelAtPeriodEnd
+ Prepared billing.Prepared // exact; never edited
+ InviteToken string // opSeat / opRestore for one join
+ AuthorisedBy string // the invite token whose authorisation an opSeat consumes
+ State string
+ Indeterminate bool
FirstSentAt, LastSentAt, SettledAt time.Time
}
- func (op billingOp) resendUntil() time.Time // min(FirstSentAt+resendLifetime, PeriodEnd-periodMargin)
- var ErrOpOutstanding = errors.New("billing: another change is in progress")
- func (s *Store) BeginBillingOp(op billingOp) error
- // MarkOpApplied sets applied and, when AuthorisedBy is set, consumes that invite's seat authorisation in the same
- // transaction. It is the only way any path records applied (Invariant 2; finding 3).
- func (s *Store) MarkOpApplied(opID string, now time.Time) error
- func (s *Store) PutBillingOpState(opID, state string, indeterminate bool, now time.Time) error // any state but applied
+ func (op billingOp) resendUntil(providerNow time.Time) time.Time // min(FirstSentAt+resendLifetime, PeriodEnd-periodMargin)
+ func (s *Store) BeginBillingOp(op billingOp) error // ErrOpOutstanding when an opOutstanding row holds the subscription
+ func (s *Store) MarkOpApplied(opID string, now time.Time) error // the only route to applied; consumes AuthorisedBy in the same transaction
+ func (s *Store) PutBillingOpState(opID, state string, indeterminate bool, now time.Time) error
+ func (s *Store) LatestOpForInvite(token string) (*billingOp, error)
func quantityPlan(current, target, paidHighest int64) (restoreTo, chargeTo int64)
- // sendOpLocked: insert the row (sending), send, and on ErrNoResponse, ErrInFlight or ErrNotExecuted resend the same
- // request with the same key up to handlerResends times. Then record: success at the target -> MarkOpApplied;
- // success with PendingUpdate -> pending; ErrPaymentFailed or ErrRefused -> failed; ErrIndeterminate -> unresolved
- // with Indeterminate; anything else -> unresolved.
func (s *Server) sendOpLocked(h billingHold, ctx context.Context, op billingOp, now time.Time) (opOutcome, *billing.Subscription, error)
- // finishOpLocked resolves an unresolved op inside a user's request: read; target visible -> MarkOpApplied; PendingUpdate
- // -> pending; Indeterminate or now >= resendUntil() -> leave unresolved (the operator path); else resend the exact
- // request with its key once and record as sendOpLocked does.
func (s *Server) finishOpLocked(h billingHold, ctx context.Context, acct *Account, op *billingOp, now time.Time) (opOutcome, error)
- // settleOpsLocked, on every applied read (any path, the passes included): positive evidence only.
- // target visible -> MarkOpApplied; PendingUpdate -> pending;
- // op pending, PendingUpdate gone, target not met -> abandoned (Stripe voided or expired it; fact 8);
- // otherwise unchanged. A negative read never abandons an unresolved op.
func (s *Server) settleOpsLocked(h billingHold, acct *Account, sub *billing.Subscription, now time.Time) error
- func (s *Server) handleBillingConfirm(w http.ResponseWriter, r *http.Request) // owner: holdBilling, finishOpLocked, settle, redirect
+ func (s *Server) lateRestoreCheckLocked(h billingHold, ctx context.Context, acct *Account, prev *billingAccount, sub *billing.Subscription, now time.Time) error
+ func (s *Server) handleBillingConfirm(w http.ResponseWriter, r *http.Request)
func billingCheckDelay(failures int) time.Duration
```
-- **The observation pass** (Invariant 5):
- - For each unresolved operation: `holdBilling`, then `syncSubscriptionLocked` (which settles on positive evidence).
- - If the op is still unresolved and `Indeterminate` or past `resendUntil()`, open `operation_unresolved`.
- - Pending operations never escalate.
- - **It sends nothing.**
-- **The `operation_unresolved` close door** (6a's operator close, with a reason branch). Under `holdBilling` and a fresh read:
- - the target is visible: `MarkOpApplied`, then close;
- - otherwise the operator's `-note` must say what the Dashboard request log shows, as `executed` or `not-executed`. Executed records applied, which needs the target visible on a fresh read, else a 409. Not-executed records abandoned.
-
- A bare negative read never closes it.
-- **Multi-step changes:** the charge request is computed only from a definite `applied` response to the restore, inside the same request. The item id comes from the response, and the response's period must equal the restore's.
+- **`sendOpLocked`:**
+ 1. `BeginBillingOp` (`sending`, with `Prepared`).
+ 2. `Send`.
+ 3. On `ErrNoResponse`, `ErrInFlight` or `ErrNotExecuted`, up to `handlerRetries` times (backoff 1, 2, 4 s): read the subscription, which settles on positive evidence, then `Send` the same `Prepared` again, only if the op is still `sending` or `unresolved`, `skewOK`, and inside `resendUntil`.
+ 4. Record the outcome:
+ - success at the target: `MarkOpApplied`;
+ - success with `PendingUpdate`: `pending`;
+ - `ErrPaymentFailed` or `ErrRefused`: `failed`;
+ - `ErrIndeterminate`: `unresolved` with `Indeterminate` set;
+ - otherwise: `unresolved`.
+- **`finishOpLocked`** runs only in a user's request, for an `unresolved` op:
+ 1. Read, then settle. Target visible: `MarkOpApplied`. `PendingUpdate`: `pending`.
+ 2. If the op is `Indeterminate`, past `resendUntil`, has a bad skew, or **belongs to an invite that is no longer pending**: no send.
+ 3. Otherwise send the same `Prepared` once, and record the outcome as above.
+- **`settleOpsLocked`** uses positive evidence only:
+ - target visible: `MarkOpApplied`;
+ - `PendingUpdate`: `pending`;
+ - a `pending` op whose `PendingUpdate` is gone and whose target is unmet: `abandoned` (fact 8);
+ - otherwise unchanged. A negative read never abandons an unresolved op.
+- **`lateRestoreCheckLocked`** (Risks R1): when `sub.PeriodEnd` moved past `prev.PeriodEnd` and an `opRestore` was first sent in the previous period in any state but `failed`:
+ 1. `RenewalInvoice(sub, prevPeriodEnd)`.
+ 2. For each restored price: if the item's quantity exceeds the invoiced one, and no `applied` op in the new period explains the difference, open `restore_after_renewal` ("item %s is at %d, the renewal billed %d").
+ 3. `ErrIncomplete` logs, and retries at the next observation.
+
+ It writes nothing to the provider.
+- **The observation pass:**
+ - for each outstanding op, `holdBilling` and `syncSubscriptionLocked`;
+ - opens `operation_unresolved` for an `unresolved` op that is `Indeterminate` or past `resendUntil`;
+ - never for `pending`;
+ - **0 writes.**
+- **The `operation_unresolved` close**, under the hold, after a fresh read:
+ - target visible: `MarkOpApplied`, then close;
+ - otherwise a note with `executed` or `not-executed` from the Dashboard request log. `executed` without the target visible is a 409. `not-executed` records `abandoned`.
+- **Multi-step changes:**
+ - a charge is computed only from a definite `applied` restore response in the same request;
+ - the item id comes from that response;
+ - the period must match.
- [ ] **Step 1: Write the failing tests**
```go
func TestBillingLockedHelpersNeverLock(t *testing.T)
func TestConsoleBillingHasNoProviderWords(t *testing.T)
+ func TestOpOutstandingMatchesIndex(t *testing.T) // the partial index's state list == opOutstanding's set
func TestSyncSubscriptionLockedSharesTheLock(t *testing.T)
func TestRefreshHasNoPeriodCheck(t *testing.T)
func TestAllowanceAppliesDelayedRenewal(t *testing.T)
func TestAllowanceRefusesEndedOrMismatched(t *testing.T)
- func TestQuantityPlan(t *testing.T)
- func TestRequestPersistedBeforeSend(t *testing.T)
- func TestHandlerResendIsByteIdentical(t *testing.T) // ErrNoResponse then success: same key and same params (Fake verifies); Replayed true
- func TestTimeoutStillProcessingIsNotReleasedByANegativeRead(t *testing.T) // CompleteLater(2) on stop-renewal: unresolved; a read shows renewal on: still unresolved;
- // the owner's resume request: change.outstanding; Confirm now resends same key: Replayed result, applied; CallsBy[SetRenewal] == 1 + resends
- func TestInFlightWaitsAndResends(t *testing.T) // InFlight(2): resent until success; one execution
+ func TestQuantityPlan(t *testing.T) // (1,3,1) charge 3; (1,3,3) restore 3; (1,4,3) restore 3 charge 4; (0,4,3) restore 3 charge 4; (2,2,5) none
+ func TestPreparedPersistedBeforeSend(t *testing.T)
+ func TestHandlerRetryReadsThenResendsVerbatim(t *testing.T) // ErrNoResponse then success: CallsBy == 1 send + 1 read + 1 send; same bytes; Replayed
+ func TestTimeoutStillProcessingIsNotReleasedByANegativeRead(t *testing.T)
+ func TestInFlightWaitsAndResends(t *testing.T)
func TestRateLimitResends(t *testing.T)
- func TestCached500GoesToTheOperator(t *testing.T) // Cached500Before: Indeterminate, no resend; pass opens operation_unresolved; no write in the pass
- func TestCached500LaterSeenApplied(t *testing.T) // Cached500After: a later read shows the target: applied without an operator
- func TestWindowClosesToOperator(t *testing.T) // ErrNoResponse forever; after resendUntil: no resend; problem opened
- func TestNoResendAfterKeyLifetime(t *testing.T) // at FirstSentAt+23h+1m Confirm now reads but does not send
- func TestNoResendAfterPeriodMargin(t *testing.T) // PeriodEnd-59m: no resend
- func TestPendingNeverEscalates(t *testing.T) // FailPayment: pending for 5 h of passes, reads healthy: no problem; PayPending: applied
+ func TestCached500GoesToTheOperator(t *testing.T)
+ func TestCached500LaterSeenApplied(t *testing.T)
+ func TestWindowClosesToOperator(t *testing.T)
+ func TestNoResendAfterKeyLifetime(t *testing.T)
+ func TestNoResendAfterPeriodMargin(t *testing.T)
+ func TestNoResendWithClockSkew(t *testing.T) // SkewBy(6m): read only, no send
+ func TestPendingNeverEscalates(t *testing.T)
func TestPendingExpiryAbandons(t *testing.T)
- func TestOperatorCloseNeedsEvidence(t *testing.T) // negative read, no note: refused; note not-executed: abandoned; executed without target: 409
+ func TestOperatorCloseNeedsEvidence(t *testing.T)
func TestOneOutstandingPerSubscription(t *testing.T)
func TestReorderedWebhooksSettleOnce(t *testing.T)
- func TestPassesNeverWrite(t *testing.T) // passes over unresolved ops, open intents, drift: CallsBy has zero writes
+ func TestLateRestoreDetected(t *testing.T) // restore sent at P1-25h30m held by ApplyAfterRenewal; Renew; apply; observation: restore_after_renewal opened,
+ // CallsBy writes == the original send only
+ func TestLateRestoreNotFlaggedWhenBilled(t *testing.T) // restore applied in P1: renewal invoice bills it: no problem
+ func TestPassesNeverWrite(t *testing.T)
func TestReadinessBackoff(t *testing.T)
```
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'BillingLockedHelpers|ConsoleBillingHasNo|SyncSubscriptionLocked|Refresh|Allowance|QuantityPlan|RequestPersisted|HandlerResend|TimeoutStillProcessing|InFlight|RateLimit|Cached500|WindowCloses|NoResendAfter|Pending(Never|Expiry)|OperatorClose|OneOutstanding|ReorderedWebhooks|PassesNeverWrite|ReadinessBackoff'`. Expected: FAIL.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'BillingLockedHelpers|ConsoleBillingHasNo|OpOutstanding|SyncSubscriptionLocked|Refresh|Allowance|QuantityPlan|PreparedPersisted|HandlerRetry|TimeoutStillProcessing|InFlight|RateLimit|Cached500|WindowCloses|NoResend|Pending(Never|Expiry)|OperatorClose|OneOutstanding|ReorderedWebhooks|LateRestore|PassesNeverWrite|ReadinessBackoff'`. Expected: FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4: Run** again, plus the sync, webhook, pass, missing and claim suites. Expected: PASS.
-- [ ] **Step 5: Commit** `console: operations resolved by Stripe's idempotent result or a positive read, never by time; resends only byte-identical, inside the key's lifetime and a user's request; passes only read (plans 6b)`.
+- [ ] **Step 5: Commit** `console: operations as prepared requests resolved by Stripe's idempotent result or a positive read; one outstanding predicate; passes only read; late restores detected (plans 6b)`.
### Task 8: The billing page and the upgrade entry
-**Files:** as revision 3, plus the continue and seats actions shown on the page.
+**Files:**
+- Create: `internal/console/billingpage.go`, `billingpage_copy.go`, `templates/billing.html`, `templates/billing_pick.html`, `billingpage_test.go`.
+- Modify:
+ - `server.go`: the routes, plus `page.Billing *billingView`, `page.BillingPick []Account` and `page.BillingNav bool` (set in `accountPage` when billing is configured);
+ - `templates/layout.html`: the nav link;
+ - claim entries: `route GET /upgrade` and `route GET /a/{sqid}/billing` as `claimRead`, with probes.
**Interfaces:**
-- `decideBillingPage` rows, first match:
+- Produces:
+ ```go
+ type billingPageInput struct {
+ Row *AccountPlanRow
+ Billing *billingAccount
+ Intent *checkoutIntent
+ Op *billingOp // the outstanding operation, nil for none
+ Problems []string // open problem reasons
+ Retiring, Ready, Owner bool
+ Now time.Time
+ }
+ type billingPageState struct { Notice string; Offered []string } // button keys, in display order
+ func decideBillingPage(in billingPageInput) billingPageState
+ func (s *Server) requestCountry(r *http.Request) string // GeoIP ISO alpha-2 of s.clientIP(r), "" for none
+ func currencyQuery(raw string, book *plans.PriceBook) (code string, refused bool, shown string)
+ func (s *Server) handleBilling(w http.ResponseWriter, r *http.Request)
+ func (s *Server) handleUpgrade(w http.ResponseWriter, r *http.Request)
+ ```
+- `decideBillingPage`, first match. Members get the notice plus `notice.owners_only` where an owner would act. Terminal intents are ignored.
- | Condition | Notice | Offered |
+ | Condition | Notice | Offered (owners) |
| --- | --- | --- |
| not ready | `notice.not_ready` | nothing |
| retiring | `notice.retiring` | nothing |
- | `seats_unpaid` | `notice.seats_unpaid` | Portal |
- | `operation_unresolved` | `notice.unresolved` | Portal |
- | other problem | `notice.problem` | Portal if bound |
+ | `seats_unpaid` | `notice.seats_unpaid` | portal |
+ | `operation_unresolved` | `notice.unresolved` | portal |
+ | `restore_after_renewal` or another problem | `notice.problem` | portal if bound |
| operator or sponsored row | `notice.operator_plan` | nothing |
- | an op `unresolved` (no problem yet) | `notice.confirming` | **Confirm now**, Portal |
- | an op `pending`, or `PendingUpdate` | `notice.pending_payment` | Portal |
- | intent `open`, not live | `notice.checkout_open` | **Continue to payment**, **Start over**, Portal if bound |
- | intent `creating`, not live | `notice.settling` | **Confirm now** |
- | not `Live` | none | Buy |
+ | op `unresolved` | `notice.confirming` | confirm, portal |
+ | op `pending`, or `PendingUpdate` | `notice.pending_payment` | portal |
+ | intent `open`, not live | `notice.checkout_open` | continue, start over, portal if bound |
+ | intent `creating`, not live | `notice.settling` | confirm |
+ | not `Live` | none | buy |
| pending state | `notice.settling` | nothing |
- | `Collecting` | `notice.past_due` | Portal |
- | `CancelAtPeriodEnd` | `notice.ending` | resume, Portal |
- | seat drift (quantity above `Billed(members)`) | `notice.seat_drift` | **Match seats to members**, Change, stop, Portal |
- | paid | none | Change, stop, Portal |
-- Currencies and the `/upgrade` contract are as revision 3 (accepted), and the copy table is revision 3's, plus:
- - `notice.confirming` "We're confirming a recent change. Nothing more will be charged.";
- - `notice.checkout_open` "Your payment page is still open.";
- - `notice.seat_drift` "Your next renewal bills %d seats for %d members.";
- - buttons `confirm.now` "Confirm now", `checkout.continue` "Continue to payment", `checkout.start_over` "Start over", `seats.match` "Match seats to members".
+ | `Collecting` | `notice.past_due` | portal |
+ | `CancelAtPeriodEnd` | `notice.ending` | resume, portal |
+ | seat drift | `notice.seat_drift` | match seats, change, stop, portal |
+ | paid | none | change, stop, portal |
+- The page shows the plan name, the packs with quantities, "members N, paid for M" on a team plan, the currency, and the renewal or end date (`2 January 2006`, UTC).
+ - **Buy:** the paid plans with yearly prices (team: per member, for at least 10, and today's total at `Billed(MemberCount)`), a quantity input per offered pack (0 to `MaxQuantity`), and the currency radios.
+ - **Change:** pack quantities, and upgrade buttons per Call 4.
+- **Currencies:**
+ - an absent query `currency` preselects `ChooseCurrency("", requestCountry(r))`;
+ - a sold code preselects it;
+ - anything else (upper case, `usd1`, `<script>`) shows `currency.refused` with the value only when `currencyQuery` returns a safe `shown` (`^[a-z0-9]{1,8}$` after case folding), else `currency.refused_unshown`, with nothing preselected;
+ - an account with a fixed currency (from any earlier subscription) shows it as text with a hidden field and no radios; a different explicit value shows `currency.fixed`.
+- **`/upgrade` contract** (Call 1), the URL the pricing page links to:
+ - `GET /upgrade?plan=<plan>&currency=<currency>`, both optional.
+ - `plan` is kept if it is a paid catalog plan. `currency` is kept as given if it matches `^[A-Za-z0-9]{1,8}$`; any other non-empty value becomes `invalid`.
+ - Billing off: 404.
+ - Signed out: 303 to `/?next=` + `url.QueryEscape("/upgrade?" + kept.Encode())`. The front door's form serves sign-in and sign-up, and `finishSignin` returns through `safeNext` after minting the account.
+ - Signed in: own one, 303 to `/a/<sqid>/billing?` + kept; own several, `billing_pick`, most recent first; own none, `renderMessage(200, upgrade.not_owner_title, upgrade.not_owner)`.
+- Draft copy (`billingCopy`):
+
+ | key | draft |
+ | --- | --- |
+ | `page.title` | Billing |
+ | `notice.not_ready` | Billing isn't available right now. Try again in a few minutes. |
+ | `notice.retiring` | This account is being deleted, so nothing can be bought or changed. |
+ | `notice.problem` | We're checking this purchase. Your plan hasn't changed yet, and nothing more will be charged. |
+ | `notice.seats_unpaid` | This account has more members than it pays for. Remove members, or ask an operator. |
+ | `notice.unresolved` | We couldn't confirm a recent change, and someone is checking it. Nothing more will be charged. |
+ | `notice.operator_plan` | An operator set this account's plan, so there's nothing to buy here. |
+ | `notice.confirming` | We're confirming a recent change. Nothing more will be charged. |
+ | `notice.settling` | We're confirming your payment. This page shows your new plan once it's done. |
+ | `notice.pending_payment` | A change is waiting for payment. Pay it from Payment and invoices, or it's dropped after a day. |
+ | `notice.checkout_open` | Your payment page is still open. |
+ | `notice.past_due` | Your last payment didn't go through. Update your card in Payment and invoices. Your plan stays while we retry. |
+ | `notice.ending` | Your plan ends on %s. After that the account moves to the free plan. |
+ | `notice.seat_drift` | Your next renewal bills %d seats for %d members. |
+ | `notice.owners_only` | Only an owner of this account can change its plan. |
+ | `currency.refused` / `currency.refused_unshown` | We don't sell in %q. Choose usd, eur or gbp. / We don't sell in that currency. Choose usd, eur or gbp. |
+ | `currency.fixed` | This account pays in %s. To change that, ask an operator. |
+ | `buy.title` / `buy.button` | Choose a plan / Continue to payment |
+ | `team.price` / `team.members` | %s per member a year, for at least %d members / %d members, paid for %d |
+ | `renews` | Renews on %s |
+ | `button.confirm` / `button.continue` / `button.start_over` / `button.match_seats` / `button.portal` | Confirm now / Continue to payment / Start over / Match seats to members / Payment and invoices |
+ | `upgrade.not_owner_title` / `upgrade.not_owner` | Only owners can upgrade / Only an owner of an account can upgrade it. Create an account of your own to choose a plan. |
+ | `pick.title` | Which account? |
-- [ ] **Step 1: Write the failing tests:** `TestDecideBillingPage` (every row; terminal intents ignored), `TestBillingPageOffAndGate`, `TestBillingPageCurrencyRefusals`, `TestBillingPageFixedCurrency`, `TestBillingPageTeamTotals`, `TestUpgradeEntry`, `TestUpgradeAfterSignupLandsOnBilling`.
-- [ ] **Steps 2 to 5:** run them (FAIL), implement, run them with the claim suite (PASS), commit `console: billing page from neutral facts, with continue, confirm and match-seats actions, and the /upgrade entry (plans 6b)`.
+- [ ] **Step 1: Write the failing tests**
+ ```go
+ func TestDecideBillingPage(t *testing.T) // every row; member vs owner; terminal intents ignored
+ func TestBillingPageOffAndGate(t *testing.T) // billing nil 404; non-member 404; member no forms; owner free: buy with three plans
+ func TestBillingPageCurrencyRefusals(t *testing.T) // GeoIP DE: eur; gbp: gbp; jpy shown "jpy"; USD shown "usd"; usd1 shown "usd1"; <script>: unshown, no "<script" in the body
+ func TestBillingPageFixedCurrency(t *testing.T)
+ func TestBillingPageTeamTotals(t *testing.T) // 4 members: community 6000; 12: 7200
+ func TestUpgradeEntry(t *testing.T) // next local and escaped; plan=../x dropped; currency=<script> becomes invalid; owner of one, two, none; billing nil 404; hostile next variants
+ func TestUpgradeAfterSignupLandsOnBilling(t *testing.T)
+ ```
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'DecideBillingPage|BillingPage|UpgradeEntry|UpgradeAfterSignup'`. Expected: FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** again, plus the claim suite (niced). Expected: PASS.
+- [ ] **Step 5: Commit** `console: billing page from neutral facts, with continue, confirm and match-seats actions, and the /upgrade entry (plans 6b)`.
-### Task 9: Checkout: start, continue, replace, return
+### Task 9: Checkout: start, continue, start over, return
**Files:**
- `internal/console/billingcheckout.go` and its test;
- routes `POST /a/{sqid}/billing/checkout`, `GET /a/{sqid}/billing/continue`, `GET /a/{sqid}/billing/done`;
- `billingpass.go` (intent observation, reads only);
-- `billingwebhook.go`;
+- `billingwebhook.go` (`EventCheckout` observes its intent);
- the claim entries.
**Interfaces:**
- Produces:
```go
const checkoutLifetime = time.Hour
- // Customer creation and Checkout creation use Invariant 1's lifecycle: the request and key are persisted (on the
- // billing row and the intent) before the first send; no-response, 409 and 429 are resent byte-identically with the
- // same key, in the handler and on the next owner request, until min(first send + 23 h, the intent's ExpiresAt).
- // A cached 5xx or a closed window:
- // customer: a new attempt number (a new key). A late or duplicate customer is an unbound orphan with no payment
- // method or subscription, so it is harmless; only the definite answer is bound.
- // Checkout create: observe CustomerCheckouts by IntentID. Found -> record it. Not found -> abandoned. That is safe
- // because a session created late is unusable: its URL was never shown, and its expires_at has passed or soon will.
- // If one is ever completed, the live-subscription check and discovery adopt its subscription and refuse a second.
func (s *Server) ensureCustomerLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) (string, error)
func (s *Server) createSessionLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, now time.Time) error
func (s *Server) observeIntentLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, now time.Time) error // reads only
- func (s *Server) replaceIntentLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, now time.Time) error // owner's explicit new request or retirement only; expiry uses expire:<intent id> with the same lifecycle
+ func (s *Server) replaceIntentLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, now time.Time) error // Start over or retirement only
func (s *Server) handleBillingCheckout(w http.ResponseWriter, r *http.Request)
- func (s *Server) handleBillingContinue(w http.ResponseWriter, r *http.Request) // owner: read the session; open and ExpiresAt > now+5m -> 303 to its URL; else flash and back
+ func (s *Server) handleBillingContinue(w http.ResponseWriter, r *http.Request)
func (s *Server) handleBillingDone(w http.ResponseWriter, r *http.Request)
func (s *Server) billingIntentPass(ctx context.Context, now time.Time)
```
+- **The customer:**
+ 1. The first attempt prepares `PrepareCustomer(sqid, "customer:<sqid>:1")` and stores it on the billing row before sending.
+ 2. No response, 409 or 429: the handler retries (a read is not possible for a customer, so the resend is the check) inside `CustomerFirstSentAt + 23 h`. A later Checkout request finishes it the same way.
+ 3. A cached 5xx or a closed window: `CustomerAttempt++` with a new key (Risks R3). Only a definite answer is bound.
+- **The Checkout create:**
+ 1. The intent is put with its `Prepared`: every parameter resolved, including the coupon id from `BillingConfig.HouseCoupon` at that moment for a house account, URLs and expiry.
+ 2. Send, with handler retries: a `Checkout` read by intent id through `CustomerCheckouts` where possible, then the same bytes, inside `min(FirstSentAt + 23 h, ExpiresAt)`.
+ 3. Success: open. `ErrRefused`: abandoned. Otherwise it stays creating, and the page offers confirm.
+ 4. When indeterminate or out of the window, observe `CustomerCheckouts` by intent id: found, record it; not found, abandoned (Invariant 1's stated exception, Risks R2).
+- **Expiry** (Start over and retirement only): `PrepareExpire(session, "expire:<intent id>")` is stored on the intent. Send, with retries. The session's state from a read decides: expired, or complete (then sync it, completed).
- **Checkout POST:**
1. Owner, CSRF, ready; parse; `currencyQuery`.
2. `holdBilling`.
3. Refuse when retiring, on an operator or sponsored row, on a problem, or on a currency mismatch.
- 4. `refreshLocked`. Refuse if the recorded subscription is `Live`.
- 5. With a customer bound, `LiveSubscriptions`. Live: sync, then refuse. `ErrIncomplete`: refuse.
+ 4. `refreshLocked`; refuse if the recorded subscription is `Live`.
+ 5. `LiveSubscriptions` (exhaustive): live means sync, then refuse; `ErrIncomplete` refuses.
6. A non-terminal prior intent:
- - `creating`: `createSessionLocked` (finish its create);
- - `open`: `observeIntentLocked`.
-
- If it becomes completed: refuse. Same request and still open: 303 to its URL. Otherwise, with **Start over** (`replace=1`) or a different request: `replaceIntentLocked`.
- 7. `ensureCustomerLocked`.
- 8. Put the new intent (`creating`, the whole request and its key).
- 9. `createSessionLocked`: success gives open, then 303; `ErrRefused` gives abandoned; unresolved gives `checkout.uncertain`, and the page offers Confirm now.
-- **Continue** is the owner's path back to an observed open session (finding 6).
-- **The pass** observes intents: open, a session read; creating, nothing (only `ExpiresAt` passing turns it into an observation through `CustomerCheckouts`, which is a read).
-
-- [ ] **Step 1: Write the failing tests** (each asserting `CallsBy`):
- - `TestCheckoutStartsSession`, `TestCheckoutTeamSeats`;
- - `TestCheckoutContinueSameRequest`, `TestCheckoutStartOverReplaces`, `TestCheckoutExpiryLosesToCompletion`;
- - `TestCheckoutAfterCancellationWithOldRecorded`, `TestCheckoutRefusesScheduledCancellation`;
- - `TestCheckoutSeesLiveSubscriptionOnPageTwo`, `TestCheckoutRefusesIncompleteList`;
- - `TestLostCreateResentInHandler` (`LoseNextResponse`: the handler resends with the same key, `Replayed`, one session);
- - `TestLostCreateContinuedFromThePage` (create unresolved after 3 resends; the page shows Confirm now; Confirm resolves to open; the page shows Continue; GET continue gives a 303 to the URL; one session in all);
- - `TestCreateCached500ObservedByIntentID`, `TestCreateWindowClosedNotFoundAbandoned`;
- - `TestCustomerCreateNoResponseResent`, `TestCustomerCreateCached500NewAttempt`;
- - `TestExpiryNoResponseResent`;
- - `TestPassRightAfterCheckoutKeepsSession`, `TestPassObservesCompletedIntent`, `TestCompletedIntentDoesNotBlockNextPurchase`;
- - `TestCheckoutRefusesOperatorRows`, `TestCheckoutNotReadyStartsNothing`, `TestCheckoutHouseWithoutCoupon`, `TestCheckoutCurrencyRules`;
- - `TestCheckoutDoneSyncs`, `TestCheckoutDoneSettling`.
-- [ ] **Steps 2 to 5:** run them (FAIL), implement, run them with the claim suite (PASS), commit `console: Checkout creates, continues and replaces sessions with exact same-key resends; passes only observe; terminal intents are history (plans 6b)`.
+ - `creating`: finish its create;
+ - `open`: observe it;
+ - completed: refuse;
+ - same request and open: 303 to its URL;
+ - Start over or a different request: `replaceIntentLocked`.
+ 7. `ensureCustomerLocked`, then put and create the new intent.
+- **Continue (GET):** owner. A session read: open and `ExpiresAt > now + 5 min` gives a 303 to its URL; otherwise a flash and back.
+- **Done:** owner; the intent named by the session; mark returned; observe; then 303.
+- **The pass:** open intents get a session read; creating intents past `ExpiresAt` get a `CustomerCheckouts` read. **0 writes.**
+- Draft copy:
+ - `checkout.already` "This account already has a paid plan, or a payment is finishing. Check back in a minute.";
+ - `checkout.failed` "We couldn't start the payment. Try again in a minute.";
+ - `checkout.uncertain` "We couldn't confirm the payment page was created. Use Confirm now, or try again in a few minutes.";
+ - `checkout.done` "You're on %s.";
+ - `checkout.expired` "That payment page has expired. Start again.";
+ - `billing.retiring` "This account is being deleted.".
+
+- [ ] **Step 1: Write the failing tests** (asserting `CallsBy`, reads included)
+ ```go
+ func TestCheckoutStartsSession(t *testing.T)
+ func TestCheckoutTeamSeats(t *testing.T) // 4 members: qty 10; 13: 13
+ func TestCheckoutContinueSameRequest(t *testing.T)
+ func TestCheckoutStartOverReplaces(t *testing.T)
+ func TestCheckoutExpiryLosesToCompletion(t *testing.T)
+ func TestCheckoutAfterCancellationWithOldRecorded(t *testing.T)
+ func TestCheckoutRefusesScheduledCancellation(t *testing.T)
+ func TestCheckoutSeesLiveSubscriptionOnPageTwo(t *testing.T)
+ func TestCheckoutRefusesIncompleteList(t *testing.T)
+ func TestLostCreateResentInHandler(t *testing.T)
+ func TestLostCreateContinuedFromThePage(t *testing.T) // create unresolved; page Confirm resolves to open; page Continue; GET continue 303; one session
+ func TestCheckoutResendBytesSurviveConfigChange(t *testing.T) // house intent with coupon A; LoseNextResponse; config to coupon B; Confirm now:
+ // the adapter's captured HTTP body equals the first send's byte for byte; one session
+ func TestCreateCached500ObservedByIntentID(t *testing.T)
+ func TestCreateWindowClosedNotFoundAbandoned(t *testing.T)
+ func TestCustomerCreateNoResponseResent(t *testing.T)
+ func TestCustomerCreateCached500NewAttempt(t *testing.T)
+ func TestExpiryNoResponseResent(t *testing.T)
+ func TestPassRightAfterCheckoutKeepsSession(t *testing.T)
+ func TestPassObservesCompletedIntent(t *testing.T)
+ func TestCompletedIntentDoesNotBlockNextPurchase(t *testing.T)
+ func TestCheckoutRefusesOperatorRows(t *testing.T)
+ func TestCheckoutNotReadyStartsNothing(t *testing.T)
+ func TestCheckoutHouseWithoutCoupon(t *testing.T) // house account, no coupon configured: checkout.failed, nothing prepared or sent
+ func TestCheckoutCurrencyRules(t *testing.T)
+ func TestCheckoutDoneSyncs(t *testing.T)
+ func TestCheckoutDoneSettling(t *testing.T)
+ ```
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'Checkout|LostCreate|CreateCached|CreateWindow|CustomerCreate|ExpiryNoResponse|PassRightAfter|PassObserves|CompletedIntent'`. Expected: FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** again, plus the claim suite. Expected: PASS.
+- [ ] **Step 5: Commit** `console: Checkout with prepared customer, create and expiry requests resent verbatim; continue and start over from the page; passes only observe (plans 6b)`.
### Task 10: Pack changes, plan upgrades and renewal
**Files:** `internal/console/billingchange.go` and its test; the change and renewal routes; the claim entries.
-**Interfaces:** `prorateEstimate`, `handleBillingChange`, `handleBillingRenewal`.
+**Interfaces:** `prorateEstimate(annualMinor, qty int64, now, periodEnd time.Time) int64`, `handleBillingChange`, `handleBillingRenewal`.
- **Change:**
- 1. Owner, CSRF, and `requireFreshAuth` for a confirmed charge.
+ 1. Owner, CSRF, and `requireFreshAuth` for a confirmed charge, before the hold.
2. `holdBilling`. Refuse when retiring, on a problem, or on a row that isn't billing-owned.
- 3. If an op is outstanding, `finishOpLocked` first; still outstanding is `change.outstanding`.
+ 3. For each outstanding op on the subscription, `finishOpLocked`. Still outstanding: `change.outstanding`.
4. `allowanceLocked`.
5. **pack:** `quantityPlan(current, target, PaidPacks[name])`:
- a reduction is one `opPack` with `ProrateNone`;
- - a restore is sent **only if `PeriodEnd − now > restoreMargin`**, else the whole request is refused with `change.near_renewal` (Invariant 4);
- - a charge is sent only after a definite applied restore, in the same period.
- 6. **plan:** one swap with `ProrateNow`.
- 7. Without confirmation: release, then the confirm page.
- 8. The proration timestamp is captured once and persisted.
+ - a restore needs `PeriodEnd − sub.ProviderTime > restoreMargin` and `skewOK`, else the whole request is refused (`change.near_renewal` or `change.clock`);
+ - a charge is computed only after a definite applied restore.
+ 6. **plan (Call 4):** one swap with `ProrateNow`, at `Billed(MemberCount)` or 1. The target must be higher in the configured book and offer every held pack.
+ 7. No step: `change.none`. A charge without `confirmed`: release, then the confirm page with `prorateEstimate`.
+ 8. The proration timestamp is captured once, in the `Prepared`.
9. Settle, then flash.
-- **Renewal:** `holdBilling`, then refuse when retiring; finish any outstanding op; `refreshLocked`; one `opRenewal` through `sendOpLocked`; settle.
-- Draft copy: revision 2's, plus `change.near_renewal` "Your plan renews within a day. Try again after it renews; the pack will then be a normal purchase."
+- **Renewal:** owner, CSRF, `holdBilling`, then refuse when retiring. Finish outstanding ops, `refreshLocked`, then one `opRenewal` via `sendOpLocked`, then settle.
+- Draft copy:
+
+ | key | draft |
+ | --- | --- |
+ | `confirm.title` | Pay for this change? |
+ | `confirm.line` | You'll pay about %s now for the rest of the year, plus any tax. |
+ | `change.no_estimate` | Stripe charges the difference for the rest of the year. |
+ | `confirm.button` | Pay now |
+ | `change.done` | Done. Your new limits apply now. |
+ | `change.pending` | Your card didn't go through, so nothing changed. Pay from Payment and invoices to finish. |
+ | `change.declined` | Your card was declined, so nothing changed. |
+ | `change.uncertain` | We couldn't confirm that change yet. Use Confirm now. Nothing more will be charged. |
+ | `change.outstanding` | Another change is still being confirmed or paid for. Finish or wait for it first. |
+ | `change.none` | That's already your plan. |
+ | `change.failed` | We couldn't make that change. Try again in a minute. |
+ | `change.book` | This change isn't available on your current prices. An operator can make it at renewal. |
+ | `change.retry` | Your plan just renewed. Try again in a minute. |
+ | `change.near_renewal` | Your plan renews within a day. Try again after it renews; the pack will then be a normal purchase. |
+ | `change.clock` | We can't make that change right now. Try again in a few minutes. |
+ | `renewal.stopped` / `renewal.resumed` | Renewal stopped. Your plan ends on %s. / Renewal is back on. |
-- [ ] **Step 1: Write the failing tests:**
- - `TestPackRaiseCharges`, `TestPackReduceAndBuyBack`, `TestDeletedPackRestoreThenCharge`;
- - `TestRestoreRefusedNearRenewal` (PeriodEnd − 24 h: refused; no ChangeItems);
- - `TestRestoreResendWindowEndsBeforeRenewal` (a restore sent at PeriodEnd − 25 h 30 m, `ErrNoResponse` forever: resends stop by PeriodEnd − 1 h; Renew; nothing is sent in P2; P2's PaidPacks equals P2's items);
- - `TestOneOutstandingOperation`, `TestRetryAfterDeclineIsRefusedUntilSettled`, `TestChangeTwiceChargesOnce`, `TestChangeComputesFromTheFreshRead`;
- - `TestChangeAfterDelayedRenewal`, `TestChangeAfterReplacementSubscription`;
- - `TestChangeUnresolvedFinishedOnNextRequest` (the next owner request resends the same key, `Replayed`, applied, then computes its own change);
- - `TestPlanUpgrade`, `TestUpgradeRefusedWhenPackNotOffered`, `TestChangeUsesTheSubscriptionsBook`, `TestRenewalStopAndResume`, `TestChangeAndRenewalReturnUnderTimeout`.
-- [ ] **Steps 2 to 5:** run them (FAIL), implement, run them with the claim suite (PASS), commit `console: pack changes and upgrades as single operations finished by same-key resends; no restore within 25 hours of renewal; stop and resume renewal (plans 6b)`.
+- [ ] **Step 1: Write the failing tests**
+ ```go
+ func TestPackRaiseCharges(t *testing.T)
+ func TestPackReduceAndBuyBack(t *testing.T)
+ func TestDeletedPackRestoreThenCharge(t *testing.T) // 0 -> restore 3 (si_n from the response) -> charge si_n to 4; two ops
+ func TestRestoreRefusedNearRenewal(t *testing.T) // ProviderTime = PeriodEnd - 24h: refused, no write
+ func TestRestoreRefusedOnClockSkew(t *testing.T)
+ func TestRestoreResendWindowEndsBeforeRenewal(t *testing.T)
+ func TestOneOutstandingOperation(t *testing.T)
+ func TestRetryAfterDeclineIsRefusedUntilSettled(t *testing.T)
+ func TestChangeTwiceChargesOnce(t *testing.T)
+ func TestChangeComputesFromTheFreshRead(t *testing.T)
+ func TestChangeAfterDelayedRenewal(t *testing.T)
+ func TestChangeAfterReplacementSubscription(t *testing.T)
+ func TestChangeUnresolvedFinishedOnNextRequest(t *testing.T)
+ func TestPlanUpgrade(t *testing.T)
+ func TestUpgradeRefusedWhenPackNotOffered(t *testing.T)
+ func TestChangeUsesTheSubscriptionsBook(t *testing.T)
+ func TestRenewalStopAndResume(t *testing.T)
+ func TestChangeAndRenewalReturnUnderTimeout(t *testing.T)
+ ```
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'Pack|DeletedPack|Restore|OneOutstanding|RetryAfterDecline|ChangeTwice|ChangeComputes|ChangeAfter|ChangeUnresolved|PlanUpgrade|UpgradeRefused|ChangeUses|Renewal|ChangeAndRenewal'`. Expected: FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** again, plus the claim suite. Expected: PASS.
+- [ ] **Step 5: Commit** `console: pack changes and upgrades as prepared operations; no restore near renewal or on clock skew; stop and resume renewal (plans 6b)`.
-### Task 11: Seats: authorised invites, admission, reconciliation, drift
+### Task 11: Seats: authorised invites, admission, revocation, drift
**Files:**
- `internal/console/billingseats.go` and its test;
-- `store.go`: the invite authorisation columns and `seat_consumed_at`;
-- `server.go`: invite, accept, revoke, and the new `POST /a/{sqid}/billing/seats`;
+- `store.go`: invite columns `seat_plan`, `seat_book`, `seat_currency`, `seat_price_minor`, `seat_authorised_by`, `seat_authorised_at`, `seat_consumed_at`;
+- `server.go`: invite, accept, revoke, and `POST /a/{sqid}/billing/seats`;
- `ownership.go`: removal;
-- `billingpass.go`: drift observation, reads only;
+- `billingpass.go`: drift observation;
- `apibilling.go`: the `seats_unpaid` close;
+- `billingstore.go`: `problemSeatsUnpaid`, `CloseBillingProblemsByReason`;
- the claim entries.
**Interfaces:**
-- Produces: `seatAuthorisation`, `SetInviteSeatAuthorisation`, `seatCovered` (unconsumed, same plan, book and currency, price not above), `admitMember`, `reconcileSeatsLocked`, `closeSeatsUnpaidLocked`, `CloseBillingProblemsByReason`, `handleBillingSeats`. Consumption happens only inside `Store.MarkOpApplied` (Task 7).
-- **`admitMember`** (Invariant 2), under the member lock:
- 1. Re-check the invite, existing membership and the cap.
- 2. Not a billing team: `membershipTransition`.
- 3. Billing team: `holdBilling`, then refuse when retiring. Finish any outstanding op of this subscription with `finishOpLocked`. If one is still outstanding: this invite's pending op gives `admitWaitPayment`; anything else gives `admitOutstanding`.
- 4. `allowanceLocked`, then recompute `need`, `cur` and `paid` from scratch:
- - `need ≤ cur`: free;
- - `cur < need ≤ paid`: a restore, only outside `restoreMargin`, else `admitNearRenewal` ("try again after the renewal");
- - `need > paid`: `seatCovered` must hold, else `admitNeedsConsent`. Then a restore (margin rule), then the `opSeat` charge carrying `AuthorisedBy`, only after a definite applied restore.
- 5. `membershipTransition`, then settle.
-- An applied charge whose membership write fails stays a credit. Its authorisation was consumed atomically with `applied`, so a retry that needs another seat gives `admitNeedsConsent`.
-- **Reconciliation never runs in a pass** (Invariant 5):
- - `reconcileSeatsLocked` runs only inside a user's request: member removal through the web, **Match seats to members**, and any join (which reconciles first).
- - It reduces with `ProrateNone`, restores within the margin, and opens or closes `seats_unpaid`.
-- **The drift pass** reads only. It records `seat_drift_at` and `seat_drift_members` when the stored quantity exceeds `Billed(MemberCount)`, so the page shows `notice.seat_drift` to owners. It opens `seats_unpaid` when members exceed paid seats, and closes it when a read shows they no longer do. Drift arises only from an operator's CLI removal or a failed membership write; owners resolve it with one click.
-- Revoke, the `seats_unpaid` close door and the invite confirm (with fresh auth) are as revision 3.
-
-- [ ] **Step 1: Write the failing tests:**
- - `TestInviteRecordsSeatAuthorisation`, `TestJoinChargesAuthorisedSeat`, `TestJoinWaitsForPayment`, `TestJoinNeedsConsentWithoutAuthorisation`, `TestJoinNeedsConsentAfterPlanSwitch`, `TestConcurrentJoinsShareNoSeat`;
- - `TestAppliedInviteChargeIsACreditNotAPass` (A's charge applied through the **definite-response path**; A's membership write fails; B joins free; A retries: `admitNeedsConsent`; members 11, paid 11; `CallsBy[ChangeItems] == 1`);
- - `TestConsumptionIsAtomicWithApplied` (consumption made to fail inside `MarkOpApplied`: the op is not applied and the authorisation not consumed; the next settle applies both; a crash injected between the two statements is impossible by construction, shown with a transaction hook);
- - `TestJoinUnresolvedFinishedOnRetry`, `TestJoinFailBeforeDeliveryResent`;
- - `TestSeatRestoreRefusedNearRenewal`;
- - `TestRevokedInviteStartsNoPurchase`, `TestJoinAfterDelayedRenewal`, `TestRejoinRestoresBeforeAdmission`, `TestLeaveReducesAtRenewal`;
- - `TestDriftPassOnlyObserves` (CLI removal: the pass records drift with 0 writes; the page shows match seats; the POST reduces with `ProrateNone`);
- - `TestPassOpensAndClosesSeatsUnpaid`, `TestSeatsUnpaidCloseDoor`, `TestSeatsUnpaidRecheckedDaily`, `TestAcceptAndRemoveReturnUnderTimeout`.
-- [ ] **Steps 2 to 5:** run them (FAIL), implement, run them with the invite, pass and claim suites (PASS), commit `console: team seats decided at admission, consent consumed with applied, no restore near renewal; reconciliation only in user requests; drift observed and shown to owners (plans 6b)`.
+- Produces:
+ ```go
+ type seatAuthorisation struct { Plan, Book, Currency string; PriceMinor int64; By string; At, ConsumedAt time.Time }
+ func (s *Store) SetInviteSeatAuthorisation(token string, a seatAuthorisation) error
+ func seatCovered(a *seatAuthorisation, row *billingAccount, book *plans.PriceBook) bool // unconsumed, same plan, book, currency, price not above
+ type admitOutcome int // admitJoined | admitWaitPayment | admitNeedsConsent | admitOutstanding | admitUncertain | admitNearRenewal | admitRefused
+ func (s *Server) admitMember(ctx context.Context, acct *Account, token, addr string, now time.Time) (admitOutcome, error)
+ func (s *Server) reconcileSeatsLocked(h billingHold, ctx context.Context, acct *Account, members int, now time.Time) error
+ func (s *Server) closeSeatsUnpaidLocked(h billingHold, ctx context.Context, acct *Account, by, note string, now time.Time) (bool, error)
+ func (s *Store) CloseBillingProblemsByReason(accountID int64, reason, by, note string, now time.Time) (int, error)
+ func (s *Server) handleBillingSeats(w http.ResponseWriter, r *http.Request) // owner: Match seats to members
+ ```
+- **Invite** (Calls 6 and 11), on a billing-owned team row, under the member lock and `holdBilling`:
+ 1. `allowanceLocked`.
+ 2. If `Billed(members + pending + 1) > max(cur, PaidSeats)`: release, then render the confirm with the per-seat estimate, carrying `to`.
+ 3. On a confirmed POST: `requireFreshAuth`, then `CreateInvite` and `SetInviteSeatAuthorisation` (the current plan, book, currency and per-seat price), under the locks again.
+- **`admitMember`** (Invariant 2), under `lockMembers`:
+ 1. Re-check the invite (`PendingInviteFor`), existing membership and the cap.
+ 2. Not a billing team: `membershipTransition(acceptInviteTx)`.
+ 3. Billing team: `holdBilling`, then refuse when retiring. `finishOpLocked` each outstanding op of the subscription. Still outstanding: this invite's `pending` op gives `admitWaitPayment`; anything else gives `admitOutstanding`.
+ 4. `allowanceLocked`. Then **use available capacity first, never reduce:** `need = Billed(members+1)`, `cur` = the plan item's quantity, `paid = PaidSeats`.
+ - `need ≤ cur`: free, with no write. This covers a paid seat left by an earlier credit, even inside the renewal margin.
+ - `cur < need ≤ paid`: a restore, needing the margin and skew rules, else `admitNearRenewal`.
+ - `need > paid`: `seatCovered`, else `admitNeedsConsent`. Then a restore if `paid > cur` (margin rules), then the `opSeat` charge with `AuthorisedBy` and `InviteToken`, only after a definite applied restore.
+ 5. `membershipTransition(acceptInviteTx)`, then settle.
+ 6. `reconcileSeatsLocked(h, ctx, acct, members+1)`, **never reducing at a join**: it only opens or closes `seats_unpaid`.
+- **Revocation** (inlined; Invariant 7). `handleRevokeInvite`, under `lockMembers` and, with billing configured, `holdBilling`:
+ 1. `op := LatestOpForInvite(token)`.
+ 2. If `op != nil && opOutstanding(op.State)`: refuse with `seats.revoke_wait`. That covers `sending`, `unresolved` and `pending`.
+ 3. Otherwise revoke as today.
+
+ Independently, `finishOpLocked` never sends for an op whose invite is no longer pending, however that came about (revoked, expired or used). Such an op stays unresolved until a positive read or the operator path settles it.
+- **Removal** (web): under the member lock, `membershipTransition(removeMemberTx)`, then with billing `holdBilling` and `reconcileSeatsLocked(h, ctx, acct, membersAfter)`, which reduces with `ProrateNone` (Call 12) and opens or closes `seats_unpaid`.
+- **Match seats** (owner POST): `holdBilling`, finish outstanding ops, `allowanceLocked`, then `reconcileSeatsLocked(h, ctx, acct, MemberCount)`.
+- **The drift pass** reads only. It records `SeatDriftAt` and `SeatDriftMembers` when the stored quantity exceeds `Billed(MemberCount)`. It opens `seats_unpaid` when members exceed paid seats, and closes it when a read shows they no longer do. It re-checks an open `seats_unpaid` at most daily. **0 writes.**
+- **The `seats_unpaid` close door:** 6a's operator close gains a reason branch. Under `holdBilling` with a fresh read, it closes only when members ≤ paid seats, else 409 `billingCopySeatsStillOver`. The other reasons keep their gates, including `subscription_missing`.
+- Draft copy:
+
+ | key | draft |
+ | --- | --- |
+ | `seats.invite_line` | When %s joins, the account pays about %s now for the rest of the year, plus any tax. |
+ | `seats.join_wait_title` | Not yet |
+ | `seats.join_wait` | This account can't add you yet because its payment didn't go through. Its owners can see this on their billing page. Try the link again later. |
+ | `seats.join_consent` | This invitation doesn't cover a new paid seat. Ask an owner to invite you again. |
+ | `seats.join_busy` | This account is in the middle of another change. Try the link again in a minute. |
+ | `seats.join_uncertain` | We couldn't confirm the account's payment for your seat. Try the link again in a few minutes. |
+ | `seats.join_near_renewal` | This account renews within a day. Try the link again after it renews. |
+ | `seats.revoke_wait` | This person's payment is still going through. Try again in a minute. |
+ | door `billingCopySeatsStillOver` | the account still has more members than paid seats. remove members first |
+
+- [ ] **Step 1: Write the failing tests**
+ ```go
+ func TestInviteRecordsSeatAuthorisation(t *testing.T)
+ func TestJoinChargesAuthorisedSeat(t *testing.T)
+ func TestJoinWaitsForPayment(t *testing.T)
+ func TestJoinNeedsConsentWithoutAuthorisation(t *testing.T)
+ func TestJoinNeedsConsentAfterPlanSwitch(t *testing.T)
+ func TestConcurrentJoinsShareNoSeat(t *testing.T)
+ func TestAppliedInviteChargeIsACreditNotAPass(t *testing.T) // A's charge applied on the definite path; A's membership write fails; B joins free;
+ // A retries: admitNeedsConsent; members 11, paid 11; CallsBy[Send] == 1 in total
+ func TestJoinUsesPresentPaidSeatInsideMargin(t *testing.T) // as above but B accepts at PeriodEnd - 24h: B joins, no write, no admitNearRenewal
+ func TestJoinNeverReduces(t *testing.T) // cur 13, paid 13, 10 members: a join writes nothing; seat drift still shown
+ func TestConsumptionIsAtomicWithApplied(t *testing.T)
+ func TestRevokeRefusedWhileUnresolved(t *testing.T) // FailBeforeDelivery on an opSeat: unresolved; revoke: seats.revoke_wait; pending and sending too
+ func TestConfirmNeverSendsForAGoneInvite(t *testing.T) // unresolved opSeat; invite expired; Confirm now and another invite's accept: no Send for it; positive read still settles it
+ func TestJoinUnresolvedFinishedOnRetry(t *testing.T)
+ func TestJoinFailBeforeDeliveryResent(t *testing.T)
+ func TestSeatRestoreRefusedNearRenewal(t *testing.T)
+ func TestRevokedInviteStartsNoPurchase(t *testing.T)
+ func TestJoinAfterDelayedRenewal(t *testing.T)
+ func TestRejoinRestoresBeforeAdmission(t *testing.T)
+ func TestLeaveReducesAtRenewal(t *testing.T)
+ func TestDriftPassOnlyObserves(t *testing.T)
+ func TestMatchSeatsReduces(t *testing.T)
+ func TestPassOpensAndClosesSeatsUnpaid(t *testing.T)
+ func TestSeatsUnpaidCloseDoor(t *testing.T)
+ func TestSeatsUnpaidRecheckedDaily(t *testing.T)
+ func TestAcceptAndRemoveReturnUnderTimeout(t *testing.T)
+ ```
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'InviteRecords|Join|ConcurrentJoins|AppliedInvite|Consumption|Revoke|ConfirmNever|SeatRestore|RevokedInvite|Rejoin|Leave|Drift|MatchSeats|SeatsUnpaid|PassOpens|AcceptAndRemove'`. Expected: FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** again, plus the invite, pass and claim suites. Expected: PASS.
+- [ ] **Step 5: Commit** `console: team seats use present paid capacity first and never reduce at a join; revocation and resends share one outstanding predicate; drift observed and matched by owners (plans 6b)`.
### Task 12: The locked portal
-Unchanged. `handleBillingPortal`: owner, CSRF, ready, a bound customer, `requireFreshAuth`, `PortalURL`, then 303. No hold.
+**Files:** `internal/console/billingportal.go` and its test; `server.go` (`POST /a/{sqid}/billing/portal`); claim entries (`claimNonApp`, writes nothing locally).
+
+**Interfaces:** `handleBillingPortal`:
+1. Owner, CSRF, ready.
+2. A bound customer, else `portal.none`.
+3. `requireFreshAuth`.
+4. `PortalURL(customer, s.cfg.Origin+"/a/"+sqid+"/billing", "portal:"+customer+":"+nonce)`, then 303. An error flashes `portal.failed`.
-- **Tests:** `TestPortalOpens`, `TestPortalGates`.
-- [ ] **Steps 1 to 5:** write the failing tests, run them, implement, run them again, commit `console: owners reach the locked portal for cards and invoices (plans 6b)`.
+There is no hold. Draft copy: `portal.none` "This account hasn't bought anything yet."; `portal.failed` "We couldn't open Payment and invoices. Try again in a minute."
+
+- [ ] **Step 1: Write the failing tests**
+ ```go
+ func TestPortalOpens(t *testing.T) // owner with customer and fresh auth: 303; return URL origin + /a/bab/billing
+ func TestPortalGates(t *testing.T) // member 404; no customer: portal.none; stale auth: step-up, no call; billing nil: 404; not ready: no call
+ ```
+- [ ] **Steps 2 to 5:** run them (FAIL), implement, run them (PASS), commit `console: owners reach the locked portal for cards and invoices (plans 6b)`.
### Task 13: The retirement gate for account deletion
-**Files:** `internal/console/billingretire.go` and its test; `ownership.go`.
+**Files:** `internal/console/billingretire.go` and its test; `ownership.go` (`handleDeleteAccount`).
-**Interfaces:** `retireGateLocked`:
-1. With a customer bound, `LiveSubscriptions` (exhaustive; `ErrIncomplete` refuses with `delete.unverified`). Each live id: `syncSubscriptionLocked`, then require `CancelAtPeriodEnd && !Collecting && !PendingUpdate`.
-2. For each unresolved op: `finishOpLocked` (the deletion request is a user request). Any op still outstanding refuses with `delete.pending`.
-3. A non-terminal intent: `open` goes through `replaceIntentLocked`; `creating` goes through `createSessionLocked`'s finish, then is judged again. A completed one is judged in step 1. Terminal intents are ignored.
+**Interfaces:** `func (s *Server) retireGateLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) error`, which returns nil or a refusal carrying a `billingCopy` key. **The order is load-bearing** (finding 1):
+1. **Finish outstanding work first.** `finishOpLocked` for every outstanding op of every subscription the account records. If any is still outstanding (`opOutstanding`): refuse with `delete.pending`.
+2. **Resolve non-terminal intents.** `creating`: finish its create. `open`: `replaceIntentLocked`. Still non-terminal: refuse with `delete.checkout`.
+3. **Then judge subscriptions, last.** `LiveSubscriptions` (exhaustive; `ErrIncomplete` refuses with `delete.unverified`). For each live id, `syncSubscriptionLocked`, then require `CancelAtPeriodEnd && !Collecting && !PendingUpdate` (refusals `delete.renewing`, `delete.collecting`).
-`handleDeleteAccount`: `BeginRetirement` and the gate; then `requireFreshAuth`; on the replay, the gate again, then `DeleteAccount`. Every purchase path refuses while retiring.
+Nothing after step 3 writes to the provider before `DeleteAccount`. Steps 1 and 2 are the only writes, and step 3 always runs after them.
-- [ ] **Step 1: Write the failing tests** (each asserting `CallsBy` against the deletion row):
- - `TestDeleteRefusedWhileRenewing`;
- - `TestDeleteAfterCompletedPurchaseAndStop`;
- - `TestDeleteRefusedWhileCollecting`;
- - `TestDeleteFinishesUnresolvedOp` (resolved by a same-key resend, then allowed);
- - `TestDeleteRefusedWithIndeterminateOp`;
- - `TestDeleteSeesLiveSubscriptionOnPageTwo`, `TestDeleteRefusesIncompleteList`;
- - `TestDeleteExpiresOpenCheckout`, `TestDeleteFinishesCreatingIntent`;
- - `TestResumeDuringRetirementRefused`, `TestDeleteGateRerunsAfterStepUp`, `TestStaleRetirementClears`.
-- [ ] **Steps 2 to 5:** run them (FAIL), implement, run them (PASS), commit `console: a retirement gate that judges every live subscription, finishes unclear operations and ignores reconciled intents (plans 6b)`.
+- **`handleDeleteAccount`,** with billing configured, after its existing checks and CSRF:
+ - **Fresh proof already present:** one hold for `BeginRetirement`, the gate, then `DeleteAccount`.
+ - **Otherwise:** hold, `BeginRetirement`, the gate (refusal: `EndRetirement` and a flash), release, then `requireFreshAuth` stashes. On the replay: hold, `Retiring` must still hold, the gate again, then `DeleteAccount`.
+ - Every purchase, change, renewal, join, reconciliation and Match seats path refuses while retiring, checked after taking the hold.
+- Draft copy:
+ - `delete.renewing` "This account renews on %s. Stop renewal first, then you can delete it.";
+ - `delete.collecting` "A payment for this account is still being collected. Settle it in Payment and invoices first.";
+ - `delete.pending` "A change is still being confirmed or paid for. Finish it first.";
+ - `delete.checkout` "A payment for this account is finishing. Try again in a few minutes.";
+ - `delete.unverified` "We couldn't check every subscription for this account. Try again later, or ask an operator.".
+
+- [ ] **Step 1: Write the failing tests** (asserting `CallsBy` against the deletion row)
+ ```go
+ func TestDeleteFinishesOpsBeforeChecksWithFreshProof(t *testing.T) // renewal stopped; an unresolved resume-renewal op that never reached Stripe; fresh step-up:
+ // the gate resends it (renewal resumes), then judges: delete.renewing, nothing deleted
+ func TestDeleteRefusedWhileRenewing(t *testing.T)
+ func TestDeleteAfterCompletedPurchaseAndStop(t *testing.T)
+ func TestDeleteRefusedWhileCollecting(t *testing.T)
+ func TestDeleteFinishesUnresolvedOp(t *testing.T)
+ func TestDeleteRefusedWithIndeterminateOp(t *testing.T)
+ func TestDeleteSeesLiveSubscriptionOnPageTwo(t *testing.T)
+ func TestDeleteRefusesIncompleteList(t *testing.T)
+ func TestDeleteExpiresOpenCheckoutThenJudges(t *testing.T) // CompleteBeforeExpire: the completed sub is judged in step 3 and refuses
+ func TestDeleteFinishesCreatingIntent(t *testing.T)
+ func TestResumeDuringRetirementRefused(t *testing.T)
+ func TestDeleteGateRerunsAfterStepUp(t *testing.T)
+ func TestStaleRetirementClears(t *testing.T)
+ ```
+- [ ] **Steps 2 to 5:** run them (FAIL), implement, run them (PASS), commit `console: a retirement gate that finishes outstanding work before judging every live subscription (plans 6b)`.
### Task 14: The house flag
-Unchanged: the operator door `POST /api/cli/billing/house` and `carlos billing house -account <sqid> -on|-off -note`.
+**Files:**
+- Create: `internal/console/apibillinghouse.go`.
+- Modify:
+ - `apibilling_copy.go`, `billing_cli.go` and `billing_cli_copy.go` (`carlos billing house`);
+ - `authcli.go`: `s.cliRoute("POST /api/cli/billing/house", svcrole.Set{}, s.handleAPIBillingHouse)`;
+ - the empty-role allowlist and the closed-door count (`TestEveryCLIDoorNamesItsRoles`, `TestEveryClosedDoorRefusesAServiceCredential`);
+ - the claim entries.
+
+**Interfaces:** `handleAPIBillingHouse`:
+- body `{"account":"<sqid>","on":true,"note":"..."}`;
+- operator only, through 6a's `billingDoor`;
+- an empty note is 400; an unknown account is 404;
+- writes an audit line.
+
+CLI: `carlos billing house -account <sqid> -on|-off -note "..."`, console mode only. Draft strings: `cli.house_on` "account %s is now the house: its checkout is free"; `cli.house_off` "account %s pays like everyone else".
-- **Tests:** `TestBillingHouseDoor`, `TestBillingCLIHouse`.
-- [ ] **Steps 1 to 5:** write the failing tests, run them, implement, run them again, commit `console, cli: operators mark house accounts, whose checkout carries the 100% coupon (plans 6b)`.
+- [ ] **Step 1: Write the failing tests**
+ ```go
+ func TestBillingHouseDoor(t *testing.T) // member 404; operator on: BillingHouse true, audit; off: false; empty note 400; billing off 409
+ func TestBillingCLIHouse(t *testing.T) // httptest console: -on sends on true; neither flag: usage error
+ ```
+- [ ] **Steps 2 to 5:** run them (FAIL), implement, run them (PASS), commit `console, cli: operators mark house accounts, whose checkout carries the 100% coupon (plans 6b)`.
### Task 15: Copy, docs, census and gates
-- [ ] **Luna copy pass,** as revision 3. Add to the facts:
- - an unclear change is confirmed with Stripe, never charged twice;
- - buying back a pack is refused within a day of renewal.
-- [ ] **Docs:**
- - the operators' section covers `operation_unresolved`: what it means, and how to close it from the Dashboard request log;
- - the owners' section covers Confirm now, Continue to payment, and Match seats.
-- [ ] **Census from the final diff:**
- - expect among its units `sendOpLocked`, `finishOpLocked`, `settleOpsLocked`, `MarkOpApplied`, `ensureCustomerLocked`, `createSessionLocked`, `observeIntentLocked`, `replaceIntentLocked`, `admitMember`, `reconcileSeatsLocked`, the retirement gate, the passes, eleven routes and five tables;
- - review every changed function in each re-pinned envelope;
- - keep the record-write gate;
+- [ ] **Luna copy pass.**
+ - Commit `docs/superpowers/specs/LUNA-COPY-BRIEF-PLANS-6B.md`, shaped like 6a's. It carries:
+ - the house rules: no em dashes; `cli.` and `door.` keys lower case with no final full stop; placeholders kept in order; no product name; Stripe may be named;
+ - the facts that must stay true:
+ - nothing is charged without the owner's button or a stored seat authorisation;
+ - reductions keep limits until renewal;
+ - a join waits for payment;
+ - the currency is fixed after the first purchase;
+ - the portal is for cards and invoices only;
+ - deletion needs renewal stopped and payments settled;
+ - an unclear change is confirmed with Stripe, never charged twice;
+ - buying back is refused within a day of renewal;
+ - every new string, with example renderings.
+ - Run Luna (gpt-5.6-luna via codex), commit the result unedited, apply it verbatim, and show Paul only the strings it flags.
+- [ ] **Docs.** Extend `docs/site/plans.md`:
+ - "Billing (operators)": the variables, the house flag, and the meaning and closing of `seats_unpaid`, `operation_unresolved` (from the Dashboard request log) and `restore_after_renewal`;
+ - an owners' section: buying, packs, members and seats, Confirm now, Continue to payment, Match seats, stopping renewal, deleting a paid account, the portal;
+ - `carlos billing house` in the CLI reference.
+- [ ] **Census from the final diff.**
+ - `make census-card` on the finished branch; units and envelopes come from its output.
+ - Expect among them: `Prepare*`, `Send`, `sendOpLocked`, `finishOpLocked`, `settleOpsLocked`, `lateRestoreCheckLocked`, `MarkOpApplied`, `ensureCustomerLocked`, `createSessionLocked`, `observeIntentLocked`, `replaceIntentLocked`, `admitMember`, `reconcileSeatsLocked`, `retireGateLocked`, the passes, eleven routes and five tables.
+ - `census-propose` takes the body and sites changes. New units are hand-written decisions.
+ - Review every changed function in each re-pinned envelope. Keep the record-write gate.
- Astra approves; Paul takes the decisions.
-- [ ] **Gates:** the darwin and windows builds; the census tests; the package tests.
+- [ ] **Gates:**
+ - `GOOS=darwin go build ./...` and `GOOS=windows go build ./...`;
+ - `go test ./internal/provision/ -run 'TestPlan14RootReadCensus|TestPlan9B8|Census'`;
+ - `go test ./internal/plans/ ./internal/billing/... ./internal/billingstripe/ ./cmd/console/ ./cmd/pricebook-export/ ./internal/docsite/`.
- [ ] **Finish:** merge main (with 6a), CI green, then Astra's whole-branch review.
## Done when
- Every task's tests pass, including the call-count assertions, and Review Focus 1 to 5 are pinned.
-- Nothing user-facing changes with billing unset, beyond `max_members` and team limits under a catalog.
+- With billing unset, nothing user-facing changes beyond `max_members` and team limits under a catalog.
- The census is approved from the final diff; CI is green; the whole-branch review has no open Critical or Important finding.
- The website has the schema-3 document and the `/upgrade` contract.
## Review record
-**Rounds 1 and 2:** see revisions 2 and 3 (`c86d0692`, `b505823d`). Round 3 confirmed round 2's findings 1, 4, 5, 6, 7 and 8 fixed.
+**Rounds 1 to 3:** see revisions 2 to 4 (`c86d0692`, `b505823d`, `3da59f32`). Round 4 confirmed round 3's findings 3 to 8 fixed, and the discovery migration.
-**Round 3** (`c2e313e3`):
+**Round 4** (`98fc42c8`):
-| Finding | Revision 4 |
+| Finding | Revision 5 |
| --- | --- |
-| 1. a negative read after 10 minutes is not finality | Finality comes only from Stripe's idempotent result (facts 1 to 4, a byte-identical same-key resend within 23 h) or a positive read. A negative read never releases an op. A cached 5xx (fact 5) and a closed window (fact 6) go to `operation_unresolved`, whose close needs Dashboard evidence. The Fake models completion after an uncertain return and after a read (`TestTimeoutStillProcessingIsNotReleasedByANegativeRead`). |
-| 2. a first restore executing in the next period | `proration_date` is no precondition (fact 10), so restores are refused within 25 h of the period end. Every attempt, resends included, lands at least an hour before renewal. Pending charges cannot cross a period (fact 8). Tests for packs and seats; schedules rejected (fact 9). |
-| 3. definite-response applied skips consumption | `Store.MarkOpApplied` is the only route to `applied`, and it consumes the authorisation in the same transaction (`TestConsumptionIsAtomicWithApplied`, and the credit test through the definite path). |
-| 4. the drift pass mutates | Passes never write. Drift is observed and shown to owners, who match seats with one click. Reconciliation runs only in user requests (`TestDriftPassOnlyObserves`, `TestPassesNeverWrite`). |
-| 5. pending payments escalate | `pending` never escalates. It follows Stripe's pending-update lifecycle (fact 8); only an indeterminate result or a closed window escalates (`TestPendingNeverEscalates`). |
-| 6. no way back to a recovered session | **Continue to payment** and **Start over** on the page, plus `GET /billing/continue`; the end-to-end test runs from the page (`TestLostCreateContinuedFromThePage`). |
-| 7. customer and expiry lack the lifecycle | Both persist the request and key and use the same-key resend window. A customer past it gets a new attempt key, because orphan customers are harmless. Expiry is decided by the session read. |
-| 8. budget undercounts | `L(n)` counts every object examined, with a 1-request minimum. Checkout branches include the recorded-subscription sync. Resends (`R`, `F`) are counted, and pass rows assert zero writes. |
-| inherited discovery cap | Discovery is migrated to the exhaustive `LiveSubscriptions` (Task 5); on `ErrIncomplete` it logs and changes nothing, as an observing net. |
-| Call 17 | Ruled by Paul: auto first, then an operator. The mechanism is fixed as above. |
+| 1. retirement retries invalidate passed checks | The gate finishes outstanding ops (step 1), resolves intents (step 2), and only then enumerates and judges subscriptions (step 3), with no write after step 3. Tested with an already-fresh proof (`TestDeleteFinishesOpsBeforeChecksWithFreshProof`). |
+| 2. reconciliation before admission removes the paid seat | Admission uses present capacity first and never reduces; reconciliation at a join uses `members+1` and only opens or closes `seats_unpaid`. The credit test keeps one send; new `TestJoinUsesPresentPaidSeatInsideMargin` and `TestJoinNeverReduces`. |
+| 3. revocation omits `unresolved` | Invariant 7: `opOutstanding` (sending, unresolved, pending) for the index, revocation, retries, admission, changes and retirement, with a test pinning the index to it. Revocation is inlined. `finishOpLocked` never sends for a gone invite (`TestRevokeRefusedWhileUnresolved`, `TestConfirmNeverSendsForAGoneInvite`). |
+| 4. persisted Checkout request loses the coupon | Every write is a `billing.Prepared`, the adapter's exact bytes with every parameter resolved (coupon id, price ids, URLs, constants), persisted before the first send and resent verbatim. Tested on the adapter's captured HTTP body across a coupon change (`TestCheckoutResendBytesSurviveConfigChange`). |
+| 5. budget omits the read before each resend | `R` counts a read and a resend per retry (`1 + 2R`); `F` is a read plus at most one resend; the tests count reads. |
+| inherited 2 (execution after renewal) | Stated as Risk R1 with detection: `lateRestoreCheckLocked` compares the renewal invoice with item quantities and opens `restore_after_renewal`, with no provider write (`TestLateRestoreDetected`). It fails toward free capacity, never an overcharge. Clock skew is capped at 5 minutes, and the margin is measured in provider time. |
+| inherited 1 (Checkout create exception) | Stated as Invariant 1's exception and Risk R2. |
+| single file | Revisions 2 and 3's binding text, draft strings and test assertions are inlined; no task points elsewhere. |
---
## Plan 6c: Stripe setup runbook (outline)
-The runbook goes at `docs/superpowers/plans/2026-10-XX-plans-6c-stripe-setup.md`, reshaped from the old `ENABLEMENT.md`. **Every live step is Paul's.** Test mode on dev comes first, and live comes after spec §12 steps 1 to 4.
+The runbook goes at `docs/superpowers/plans/2026-10-XX-plans-6c-stripe-setup.md`, following `165472b8:implementation/carloku-paid-launch/ENABLEMENT.md`, reshaped. **Every live step is Paul's.** Test mode on dev comes first, and live comes after spec §12 steps 1 to 4.
-1. **Products:** Personal, Community, Business and the five packs (8).
-2. **Prices:** 24, yearly, licensed, per unit, tax exclusive, one currency each, with `metadata[price_key]`. In minor units, usd / eur / gbp:
+1. **Products:** Personal, Community, Business and the five packs (8). The tax code is to be confirmed with the accountant.
+2. **Prices:** 24, yearly, licensed, per unit, tax exclusive, one currency each, with `metadata[price_key]` set to the key. In minor units, usd / eur / gbp:
| Item | usd | eur | gbp |
| --- | --- | --- | --- |
@@ -761,18 +1321,38 @@ The runbook goes at `docs/superpowers/plans/2026-10-XX-plans-6c-stripe-setup.md`
| email | 2400 | 2100 | 1900 |
| bandwidth | 4800 | 4100 | 3800 |
- The book becomes a new approved version before live.
-3. **Locked portal configuration.** Its id goes to `CARLOS_STRIPE_PORTAL_CONFIGURATION`.
-4. **House coupon:** 100% off, forever. Its id goes to `CARLOS_STRIPE_HOUSE_COUPON`.
-5. **Webhook:** six events, API version `2025-02-24.acacia`.
-6. **Retry settings:** cancel after all retries.
-7. **The restricted key:** Checkout Sessions write, Customers write, Subscriptions write, Customer portal write, Billing portal configurations read, Prices, Products and Coupons read. Nothing else. No subscription schedules.
-8. **Console variables:** as 6a, plus the portal configuration and the house coupon.
-9. **Test-mode rehearsal on dev** (test clocks), revision 3's list plus:
- - a same-key resend after a dropped connection (check for `Idempotent-Replayed`);
+ The book becomes a new `approved` version before live.
+3. **The locked portal configuration:**
+ - on: payment method update and invoice history;
+ - customer update limited to address, name and tax id;
+ - off: subscription update, cancel and pause.
+
+ Its id goes to `CARLOS_STRIPE_PORTAL_CONFIGURATION`.
+4. **The house coupon:** 100% off, forever, unrestricted, no promotion code. Its id goes to `CARLOS_STRIPE_HOUSE_COUPON`.
+5. **The webhook:** `https://<console>/billing/webhook`, with `checkout.session.completed`, `customer.subscription.created`, `customer.subscription.updated`, `customer.subscription.deleted`, `invoice.paid` and `invoice.payment_failed`; API version `2025-02-24.acacia`; the secret goes to `CARLOS_STRIPE_WEBHOOK_SECRET`.
+6. **Retry settings:** cancel after all retries fail.
+7. **The restricted `rk_` key:**
+ - granted: Checkout Sessions write (which also lists a customer's sessions), Customers write, Subscriptions write, Customer portal write, Billing portal configurations read, Prices read, Products read, Coupons read, and **Invoices read** (Risk R1's detection, new in revision 5);
+ - not granted: refunds, charges, events, webhook endpoints, keys, subscription schedules.
+8. **Console variables** (EnvironmentFile only): `CARLOS_BILLING`, `CARLOS_PLAN_CATALOG`, `CARLOS_PRICE_BOOK`, `CARLOS_BILLING_PRICES`, `CARLOS_STRIPE_SECRET_KEY`, `CARLOS_STRIPE_ACCOUNT`, `CARLOS_STRIPE_WEBHOOK_SECRET`, `CARLOS_STRIPE_PORTAL_CONFIGURATION`, and optionally `CARLOS_STRIPE_HOUSE_COUPON`.
+9. **Test-mode rehearsal on dev** (test clocks):
+ - `/upgrade` while signed out, through sign-up, to Checkout;
+ - Personal with packs; Community at 4 and at 12 members;
+ - a declined pack raise, then paid from the portal; a resubmit refused while pending; a pending update left to expire;
+ - a deleted pack restored and charged above its paid count;
+ - a buy-back refused within 25 h of renewal and allowed after it;
+ - a delayed renewal webhook, followed by a pack request;
+ - member joins with a good card, a declining card and a dropped connection (check `Idempotent-Replayed`); two joins at once; a join using an already-paid seat inside the margin;
+ - a leave, then a rejoin; Match seats after a CLI removal;
+ - Personal to Business (`pending_if_incomplete` with a price swap);
+ - stopping and resuming renewal;
+ - deletion refused while renewing, collecting, or with an unresolved resume-renewal request, then allowed;
+ - an expiry racing a completed Checkout;
+ - a Checkout create with a lost response, continued from the page;
- a 409 while a request is in flight;
- an operator closing `operation_unresolved` from the Dashboard request log;
- - a pack buy-back refused within 25 h of renewal and allowed after it;
- - Match seats after a CLI removal;
- - Continue to payment after a lost create response.
+ - the renewal invoice read used by the late-restore check;
+ - a failed renewal, then cancellation; out-of-order events; `incomplete_expired`; webhook secret rotation;
+ - readiness refusing a wrong price, an unlocked portal and a bad coupon, with backoff;
+ - a house account at zero; the customer-currency lock.
10. **Flagship:** the same in live mode on Paul's approval, then publish `https://<console>/upgrade?plan=<plan>&currency=<cur>`.