plans 6b: revision 4 after Astra's round 3. Call 17 ruled by Paul (auto first, then an operator). Finality from Stripe's documented idempotency (same-key byte-identical resends within 23 h; cached 5xx and closed windows to the operator; Dashboard evidence to close; pending payments never escalate), cited from stripe docs; subscription schedules considered and not adopted; restores refused within 25 h of renewal; consent consumed atomically with every applied; passes never write, drift shown to owners with Match seats; Continue to payment for a recovered session; customer and expiry on the same lifecycle; discovery migrated to the exhaustive list; budget counts every object examined and every resend
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+541
−821
docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md+541 −821
CI cancelled — superseded by a newer push — 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 a02a76dee..8a345fcc2 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,644 +12,493 @@ |
| A static pricing page links to one stable console URL, which takes a signed-out visitor through sign-in or sign-up first. |
| -**Revision 3 (2026-10-25).** Revision 2 fixed Astra's round 1 (`plans6b-plan-review.md`). Round 2 (`plans6b-plan-review-r2.md`, at `d705d1c7`) accepted most of it. Its eight new findings came from revision 2's replay and recovery machinery. Revision 3 deletes that machinery rather than patching it: |
| -- nothing is ever resent after a call returns; |
| -- recovery only observes; |
| -- the six invariants below govern every flow. |
| - |
| -"Review record" at the end maps each finding to its fix. Paul's sixteen calls stand as ruled. Call 17 is a new choice the simplification raises. |
| +**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. |
| + |
| +## Provider facts this plan relies on |
| + |
| +Read with `stripe docs` on 2026-10-25. API v1, which is what the 6a client calls. |
| + |
| +1. **Idempotent retries.** |
| + - "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. |
| ## Invariants |
| -Every task obeys these. A reviewer rejects any step that contradicts one. |
| - |
| -1. **Never replay a saved step.** |
| - - An operation is **one provider request**, written to `billing_operations` before it is sent. The row holds the exact request: the subscription id **and its period end**, item id or absence, price id, quantity, proration, proration timestamp and idempotency key. |
| - - It is sent exactly once. The 6a client never retries, and 6b adds no retry. |
| - - After the call, recovery **re-reads the provider** (the subscription with its items and period, or the session) and records what happened: applied, pending payment, or not done. |
| - - Anything further is **recomputed from scratch** by a new request, under the current period and authorisation. |
| - - A step that was never sent is abandoned, never executed. So is one whose context changed (a new period, a new book, consumed consent, an expired intent). |
| - - A second step (restore, then charge) is computed only from a **definite** response to the first, inside the same request. |
| +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. |
| 2. **Paid capacity is decided at admission, every time.** |
| - - An applied invite charge is **a credit that reconciliation absorbs**, not an entitlement to skip the capacity check. |
| - - No seat is reserved for an invite. Each admission recomputes `need` against the freshened paid capacity. If a paid seat is free, whoever is admitted next takes it. |
| - - A seat authorisation is **single use**: it is consumed when a charge under it is applied. A retry that needs another charge needs fresh consent. |
| -3. **Provider enumeration is exhaustive or it refuses.** Every list (live subscriptions, a customer's Checkout sessions) pages to completion, up to `billing.MaxListPages` (10) pages of 100. More than that is `billing.ErrIncomplete`, and the caller refuses. |
| -4. **Refresh and the allowance invariant are separate.** |
| - - `refreshLocked` is the plain 6a sync of the recorded subscription, with no period check. Checkout, retirement and the page use it. |
| - - `allowanceLocked` refreshes, then requires the row's `PaidPeriodEnd` to equal the read's period end. Only quantity changes on a live, paid subscription use it. |
| -5. **Background passes only observe.** |
| - - The hourly pass reads sessions and subscriptions and records what they show. |
| - - It never expires an unexpired open Checkout session, never sends a change, and never creates a session. |
| - - Only an owner's explicit new Checkout (replacement) or the retirement gate expires a session. |
| -6. **A terminal intent is history.** Once its outcome is recorded (`completed` with its subscription synced, `expired` or `abandoned`), an intent blocks nothing. Checkout and retirement judge the account's **subscriptions**, from an exhaustive list, never a past intent. |
| + - 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. |
| +6. **A terminal intent is history.** Checkout and retirement judge the account's subscriptions from an exhaustive list. |
| **Architecture:** |
| -- **Team plans in the catalog** (`internal/plans`): |
| - - A plan may carry a `team` block: a base plan, a per-member multiple in thousandths, and a minimum. |
| - - `Effective` takes a member count. It multiplies the base plan's pooled limits by `multiple × max(members, minimum)`. |
| - - Non-team plans may carry `max_members`. |
| - - The public export moves to schema 3. |
| -- **Seats and membership** (`internal/console`): |
| - - `account_plans.seats` is the paid seat count billing wrote. 0 means "count the members now". |
| - - Every membership change goes through `membershipTransition`, which wraps 6a's `transitionAccountPlan`. |
| - - Every join is admitted under a per-account member lock, with all checks re-run inside it. |
| -- **Provider writes** (`internal/billing`, `internal/billingstripe`): new `Provider` methods behind the 6a boundary. Stripe status words stay in the adapter. |
| -- **Operations and intents** (`internal/console`): |
| - - A `billing_operations` row is one provider request: written before sending, settled only by observing. At most one is outstanding per subscription. |
| - - A Checkout intent is created before the session, and recovered only by observing the customer's sessions. |
| -- **The console flow:** the billing page, `/upgrade`, Checkout, pack, plan and seat changes, renewal, the portal, and a retirement gate for deletion. |
| - - Every flow takes the billing lock through `holdBilling`. |
| - - It refreshes, or for quantity changes passes the allowance check. |
| - - It sends at most the requests it can compute from definite answers. |
| - - It settles with one more read through 6a's `applyBillingRead`. |
| - |
| -**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. |
| +- **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. |
| **Spec:** `docs/superpowers/specs/2026-10-20-plans-caps-packs-design.md`: |
| -- §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 locked portal; |
| - - the console changes plans and quantities, never the portal. |
| -- §9.2: paid limits while Stripe retries; Plan 4d owns what falls. |
| -- §9.6: live setup (the 6c outline at the end). |
| -- §10: the provider boundary. |
| -- §3: usd, eur and 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. |
| +- §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. |
| Also binding: |
| -- **Plan 6a** (`docs/superpowers/plans/2026-10-25-plans-6a-checkout.md`): all of its Calls are accepted, and its outline of 6b is the starting shape. |
| -- **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 pricing page publishes only when checkout is live, and its buttons go straight to the console's upgrade entry (Task 8). |
| +- **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). |
| ## Base branch, order and 6a's names |
| -- This branch was cut from `plans-6-checkout` at `f4ce6bda`. |
| -- **Rebase it onto main after 6a merges,** before Task 1. If 6a has not merged, merge `origin/plans-6-checkout` and then `origin/main`. Build Tasks 0 to 2 only, and stop before Task 3 until 6a merges. |
| -- **6a's merged names, which this plan uses:** |
| +- 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 func(old *AccountPlanRow) (bool, error))`; |
| + - `transitionAccountPlan(ctx, acct, now, write)`; |
| - `Store.SaveBillingSync(next, accountID, plan, markLapse, resetCaps, now)`; |
| - - `syncSubscription` (takes the billing lock); |
| - - `applyBillingRead` (the caller holds it); |
| + - `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. Where that pass merges different names, use 6a's, and note the ruling in the ledger. 6b only adds hooks: |
| - - seats in `decideBilling`; |
| - - operation settlement after `applyBillingRead`; |
| - - intent observation in discovery. |
| +- **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. |
| ## Calls for Paul |
| -**Ruled 2026-10-25: Paul accepted every recommendation (1 to 16) as written.** Task 0 records them. Don't reopen them. Revisions 2 and 3 change only how Calls 6, 11 and 15 are made safe, never what they decide; those places are marked. Call 17 is new in revision 3. |
| - |
| -1. **The upgrade URL and which account it upgrades.** The contract is Task 8's. Owns one account: its billing page. Several: a picker, the most recent first. None: a not-owner page. **Recommend: as stated.** |
| -2. **Default currency:** from the visitor's GeoIP country, with an override. Checkout collects the billing address. An explicit unsold currency is refused. **Recommend: as stated.** |
| -3. **An account's currency is fixed after its first purchase.** **Recommend: as stated.** |
| -4. **Paid-to-paid switches: upgrades only in 6b**, charged at once and granted once paid. **Recommend: as stated.** |
| -5. **Quotes are a local estimate.** **Recommend: as stated.** |
| -6. **A fresh sign-in proof before charging a saved card or opening the portal.** (Revision 2: the invite confirm that records a seat authorisation also needs one.) **Recommend: as stated.** |
| -7. **Disk is not pooled.** Team plans keep Personal's 10 GB per running thing. **Recommend: as stated.** |
| -8. **Ceilings scale with the team.** **Recommend: as stated.** |
| -9. **Community's history:** the latest copy only. Business gets 7 days. **Recommend: as read.** |
| -10. **Packs on team plans:** the same five, flat per account. **Recommend: yes.** |
| -11. **A member joins while the card fails.** |
| - - The owner confirms the cost at invite time. |
| - - The charge happens at accept, before the membership is created. |
| - - On failure the person does not join yet, and the invite stays valid. |
| - - Operator-added members are never charged; any excess opens `seats_unpaid`. |
| - |
| - (Revision 3: the stored authorisation is single use. If a charge it paid for ends up seating someone else, the retry asks the owner again, Invariant 2.) **Recommend: as stated.** |
| -12. **A member who leaves:** comes off at once with no proration. The account keeps the period's highest paid seats. A rejoin within the period is free. **Recommend: as stated.** |
| -13. **Who counts:** owners and members. Not invites, not service credentials. Billed and limited at a minimum of 10. **Recommend: as stated.** |
| -14. **`max_members` 3 on Free and Personal,** checked at invite and accept only. **Recommend: as stated.** |
| -15. **Deleting a renewing account is refused; allowed once renewal is stopped.** (Revision 2: a durable retirement gate checks provider truth. Revision 3: it judges an exhaustive subscription list, and ignores reconciled intents.) **Recommend: as stated.** |
| -16. **No create-as-paid path for a second account.** **Recommend: as stated.** |
| -17. **(New, revision 3) An operation whose outcome the provider leaves unclear.** Invariant 1 never resends, so an operation with no definite answer (a timeout, a crash mid-send) is **observed**. The first applied read at least `opQuiet` (10 minutes) after the send records it as applied, pending, or abandoned. Until then, changes on that subscription are refused (one outstanding operation). |
| - - **Recommend: (a) as stated, plus a refusal backstop.** If an operation is still unresolved after `opStuck` (1 hour), which happens only when the provider can't be read, the console opens an `operation_unresolved` billing problem. All changes on the account are refused until an operator closes it. The close is allowed once a fresh read settles the operation. |
| - - **Alternative (b):** drop observation. Every unclear outcome opens `operation_unresolved` at once, and nothing is settled automatically. That is less logic but more operator work: every timeout reaches a person. |
| +**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): |
| + - **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). |
| ## Global Constraints |
| -- **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; |
| - - no retirement gate. |
| - |
| - Team limits, `max_members`, the member lock and `membershipTransition` work with a catalog and no billing. |
| -- **6a's rules hold:** |
| - - the event body is never trusted; |
| - - the plan follows only a fresh read applied under the billing lock; |
| - - billing writes only `default` or `billing` rows; |
| - - a live console refuses a draft book; |
| - - `rk_` keys only. |
| -- **Locks: member → billing → lapse → store.** |
| - - The member lock is `s.memberLocks`, 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. |
| - - 5-second timeout tests. |
| -- **Granted once paid.** Charges are `billing.ProrateNow` (`always_invoice` + `pending_if_incomplete`). Reductions, and restores up to the period's paid quantity, are `billing.ProrateNone`. |
| -- **One outstanding operation per subscription:** a partial unique index over `sending`, `uncertain` and `pending`. A read with `PendingUpdate` counts as outstanding even with no row. |
| -- **Idempotency keys:** |
| - - customer: `customer:<sqid>`; |
| - - Checkout create: `checkout:<intent id>`; |
| - - Checkout expiry: `expire:<intent id>`; |
| - - an operation: `op:<operation id>`; |
| - - portal: `portal:<customer>:<16 random hex>`. |
| - |
| - Keys are persisted with the exact request, and each request is sent once (Invariant 1). |
| +- **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 | |
| - **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`. |
| - **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. |
| - **Request budget, by branch and cardinality.** |
| - - Stripe requests. Notation: `L(n)` is one list of `n` objects, `ceil(n/100)` requests, at most 10, else `ErrIncomplete`; `S` is one sync of a subscription, 1 read plus 1 more when another recorded subscription is live, so 1 to 2. |
| + - 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. |
| - | Operation | Branch | Requests | |
| + | Operation | Branch | Stripe requests | |
| | --- | --- | --- | |
| - | Readiness attempt | all prices good | 34 (35 with a house coupon); stops at the first failure. Retries back off 1, 2, 4, 8, 16, then every 30 min: ≤ 6 attempts in the first hour, then 2 an hour | |
| + | 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. | |
| | Billing page view | any | 0 | |
| - | Checkout start | first purchase, no prior intent | `L(live subs)` + 1 customer create + 1 session create | |
| - | | prior intent `open`, same request | `L` + 1 session read (reuse) | |
| - | | prior intent `open`, other request | `L` + 1 session read + 1 expiry (+1 session read if the expiry is refused) + 1 create | |
| - | | prior intent `creating`, older than `opQuiet` | `L` + `L(customer sessions since the intent)` (+1 sync if one completed) + 1 create | |
| - | | prior intent `creating`, younger than `opQuiet` | `L`, then a refusal ("still preparing") | |
| - | | a live subscription found | `L` + `S` per live id, then a refusal | |
| + | 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 | |
| + | Continue (GET) | open intent | 1 session read | |
| | Checkout return | any | 1 session read + `S` | |
| - | Pack or plan change | no step | `allowance` (`S`) | |
| - | | one step | `S` + 1 send + settle `S` | |
| - | | restore, then charge | `S` + 1 send + 1 send (computed from the first's definite response) + settle `S`. A lost first response stops after its send, then a settle read | |
| - | Renewal change | any | `S` + 1 send + `S` | |
| + | Pack or plan change | prior op unresolved | `F` first; if still unresolved, 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` | |
| | Portal | any | 1 | |
| - | Join on a billing team | seat free | `S` | |
| - | | restore | `S` + 1 + `S` | |
| - | | charge | `S` + 1 + `S` | |
| - | | restore, then charge | `S` + 2 + `S` | |
| - | Deletion gate, per run (runs twice) | `k` live subscriptions, `j` non-terminal intents | `L(live subs)` + `k` sync reads + per intent: 1 session read (`open`; +1 expiry, +1 read if refused) or `L(customer sessions)` (`creating`) | |
| - | Hourly pass, per account | any | 6a's sync and discovery; + per non-terminal intent: 1 session read (`open`) or `L` (`creating` older than `opQuiet`); + per unresolved operation older than `opQuiet`: `S`; + per seat drift: as a join or a reduction; + `seats_unpaid` re-checked at most daily | |
| - |
| - - S3: nothing polled. A limits publication is a GET plus a conditional PUT, with retries on conflict. `transitionAccountPlan` adds 4d's inventory reads and convergence writes per change that moves limits. A change that moves no limit publishes nothing. |
| - - **Call-count assertions:** every recovery, retirement and Checkout-branch test asserts `Fake.Calls` (by method) against this table. |
| + | 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 | |
| + |
| + - 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. House rules apply. |
| - - Where a task says "revision 2's" draft strings, they are in revision 2 of this file (`git show c86d0692:docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md`), same task. The Luna pass replaces every draft, so none of them is load-bearing. |
| - - Test bodies marked "(as revision 2)" have their one-line assertions there too. |
| -- **Census:** |
| - - route lines, fixtures and probes go with each route-adding task; |
| - - new tables are `NonApp`; |
| - - units are derived from the final diff (Task 15). |
| + - 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. |
| - **Tests:** |
| - - TDD, no network; inject `now`; |
| - - the Fake models idempotency, pending updates, later payment, expiry, failure **before** delivery, lost responses **after** applying, renewal across a period boundary, list paging and Checkout races; |
| - - run touched packages, niced; one `-run Claim` run per route-adding task. |
| + - TDD, no network; inject `now`. |
| + - The Fake models: |
| + - per-key idempotency, including parameter mismatch, the replay marker 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. |
| ## Review Focus |
| -1. **A lost response, then the clock moves on.** A lost add response must never be resent or turned into an update. A crash before sending, followed by a renewal, must send nothing in the new period. Pinned in Task 7 (`TestLostAddResponseIsObservedNotResent`, `TestUnsentRestoreAbandonedAcrossRenewal`) and Task 11 (`TestUnsentSeatRestoreAbandonedAcrossRenewal`). |
| -2. **A paid invite seat taken by another joiner.** The members never exceed the paid seats, and the first invitee's retry needs fresh consent. Pinned in Task 11 (`TestAppliedInviteChargeIsACreditNotAPass`). |
| -3. **A live subscription on page two.** Checkout and deletion must see it, and refuse when the list is incomplete. Pinned in Task 5 (`TestLiveSubscriptionsPagesToCompletion`), Task 9 (`TestCheckoutSeesLiveSubscriptionOnPageTwo`) and Task 13 (`TestDeleteSeesLiveSubscriptionOnPageTwo`, `TestDeleteRefusesIncompleteList`). |
| -4. **A buyer mid-Checkout when the hourly pass runs.** Their session survives. Pinned in Task 9 (`TestPassRightAfterCheckoutKeepsSession`). |
| -5. **Purchase, stop renewal, delete.** Deletion succeeds; the completed intent does not block it. Pinned in Task 13 (`TestDeleteAfterCompletedPurchaseAndStop`). |
| +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`). |
| --- |
| ### Task 0: Record the rulings |
| -**Files:** |
| -- Modify: `docs/superpowers/specs/2026-10-20-plans-caps-packs-design.md`: |
| - - §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; |
| - - §4.2: the Community and Business columns, with disk at "10 GB per running thing (not pooled)"; |
| - - §9.1: the team plan item, with quantity `max(members, 10)`; |
| - - a "Plan 6b rulings" list with Calls 1 to 16 as ruled. Add Call 17 once Paul rules on it. |
| +**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. |
| - [ ] **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 |
| -**Files:** |
| -- Create: `internal/plans/team.go`, `internal/plans/team_test.go`. |
| -- Modify: |
| - - `internal/plans/catalog.go`; |
| - - `internal/plans/testdata/example-catalog.json`: `community`, `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 passes `1` until Task 3. |
| +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. |
| **Interfaces:** |
| -- Produces: |
| - ```go |
| - type Team struct { |
| - Base string `json:"base"` |
| - PerMemberMilli int `json:"per_member_milli"` // 200 = 0.2, 2000 = 2 |
| - MinMembers int `json:"min_members"` |
| - } |
| - // Plan gains Team *Team `json:"team,omitempty"` and MaxMembers int `json:"max_members,omitempty"`. |
| - 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 |
| - func (t *Team) PerMember() string |
| - func (c *Catalog) Effective(plan string, packs map[string]int, sponsored *Limits, members int) (Limits, error) |
| - ``` |
| -- Validation: |
| - - the base is a paid, non-team plan; |
| - - milli is 1 to 100000; the minimum is 1 to `MaxTeamMembers`; |
| - - a team plan sets no pooled field of its own and no `max_members`; |
| - - `max_members` ≥ 0. |
| -- Team `Effective`: |
| - 1. The team plan's own limits, its `disk_bytes` included. |
| - 2. Pooled fields: `floor(base × milli × Billed / 1000)`, overflow-checked (an overflow is `ErrTeamMembers`). |
| - 3. Packs. |
| - 4. Ceilings; only the pooled fields' ceilings scale by the same factor when it is above 1 (Call 8). |
| - 5. The sponsored merge. |
| - |
| - Members outside 0 to `MaxTeamMembers` is `ErrTeamMembers`. On non-team plans, members is ignored. |
| -- Example team plans: `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. Community milli 200, Business 2000, both minimum 10. |
| +- `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)`. |
| -- [ ] **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, EmailPerDay 24000, HistoryDays 7, DiskBytes 10737418240 |
| - func TestEffectiveTeamWithPacks(t *testing.T) // community 10 + apps 2: 60; disk 1: DiskBytes 21474836480 |
| - func TestEffectiveIgnoresMembersOffTeam(t *testing.T) |
| - func TestEffectiveTeamMemberBounds(t *testing.T) |
| - func TestCatalogRefusesBadTeams(t *testing.T) |
| - func TestTeamBilledAndPerMember(t *testing.T) |
| - ``` |
| -- [ ] **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)`. |
| +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. |
| -### Task 2: Public export schema 3 and money formatting |
| +- [ ] **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)`. |
| -**Files:** |
| -- Modify: `internal/plans/export.go`, `export_test.go`, the regenerated golden, and the `cmd/pricebook-export` tests. |
| -- Create: `docs/superpowers/specs/2026-10-25-public-price-export-schema-3.md`. |
| +### Task 2: Public export schema 3 and money formatting |
| -**Interfaces:** |
| -- Produces: schema 3. `publicPlan` gains `Team *publicTeam` (base, `per_member`, `min_members`, `pooled` without disk) and `MaxMembers`. Also `func FormatMinor(currency string, minor int64) string`. |
| -- A team plan's `annual_minor` is per member. Its `limits` carry the pooled fields at `min_members`. The order is free first, then `annual × max(1, min_members)`, then key. |
| +Accepted; unchanged. |
| -- [ ] **Step 1: Write the failing tests:** `TestPublicExportSchema3Team`, `TestPublicExportGolden`, `TestFormatMinor` (`"$28"`, `"£4.50"`, `"€24"`, `"$0.07"`). |
| -- [ ] **Step 2: Run** `go test ./internal/plans/ ./cmd/pricebook-export/ -run 'PublicExport|FormatMinor|Golden'`. Expected: FAIL. |
| -- [ ] **Step 3: Implement,** and 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)`. |
| +- 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)`. |
| ### Task 3: Seats, the member lock and membership transitions |
| -Accepted in round 2; unchanged from revision 2. |
| - |
| -**Files:** |
| -- Create: `internal/console/planmembers.go`, `planmembers_test.go`. |
| -- Modify: |
| - - `store.go`: `account_plans.seats`, and the `acceptInviteTx`, `addMemberTx`, `removeMemberTx` variants; |
| - - `accountplans.go`: seats in the row, `SetAccountPlan` and the upsert; `SaveBillingSync`'s guard compares seats; |
| - - `planlapse.go`: `applyAccountPlan` and `lapseStarted` carry seats; |
| - - `planlimits.go`: `planMembers`; |
| - - `apiaccountplan.go`; |
| - - `server.go` (`handleInvite`, `handleAcceptInvite`, `handleRevokeInvite`) and `ownership.go` (`handleRemoveMember`): the member lock and in-lock re-checks; |
| - - `plancaps.go`, `plancaps_copy.go`; |
| - - `cmd/console/member.go`: through `Store.MembershipTransition`. |
| +Accepted; unchanged from revision 3. |
| **Interfaces:** |
| -- 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) |
| - func (s *Server) planMembers(row *AccountPlanRow, accountID int64) (int, error) |
| - func (s *Server) lockMembers(sqid string) func() |
| - func membershipFell(cat *plans.Catalog, row *AccountPlanRow, before, after int) bool |
| - 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 |
| - func (s *Server) checkMemberCap(acct *Account, adding int) error |
| - ``` |
| -- How these work: |
| - - `MembershipTransition` counts members before and after, in one transaction. On a live-counted team row whose billed count changed, it bumps the revision; on a fall, it marks the lapse and resets the lapse caps. |
| - - `membershipTransition` wraps it in `transitionAccountPlan`. The limits pass retries publication. |
| - - Every invite, join, revoke and removal runs under `lockMembers`. Accept re-checks inside the lock: the invite, existing membership and the cap. |
| -- Draft copy: `browser.cap.members`, `browser.cap.members_join`, `browser.cap.free_account` (Call 16), with `cli.` twins. |
| - |
| -- [ ] **Step 1: Write the failing tests:** `TestTeamLimitsFollowMembers`, `TestSeatsPinTeamLimits`, `TestMembershipRiseReconvergesAndPublishes`, `TestMembershipFallStartsLapse`, `TestMembershipNoLimitChangeWritesNothing`, `TestMembershipPublishFailureRetried`, `TestCLIMembershipTransition`, `TestConcurrentInvitesRespectCap`, `TestConcurrentAcceptsRespectCap`, `TestAcceptRechecksInsideLock`, `TestMemberCapAtInvite`, `TestMemberCountExcludesInvitesAndServices` (as revision 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)`. |
| +- `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`. |
| + |
| +- **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)`. |
| ### Task 4: Provider boundary and a payment-faithful fake |
| -**Files:** |
| -- Modify: `internal/billing/billing.go`, `recognise.go`, `billingtest/fake.go`. |
| -- Test: `recognise_test.go`, `billingtest/fake_test.go`. |
| +**Files:** `internal/billing/billing.go`, `recognise.go`, `billingtest/fake.go`, and their tests. |
| **Interfaces:** |
| - Produces: |
| ```go |
| - // Item gains ItemID. Subscription gains PendingUpdate bool, PendingExpires time.Time, Collecting bool. |
| - func (s *Subscription) Renewing() bool // Live && !CancelAtPeriodEnd |
| - // Purchase gains Seats int. |
| - type Proration string |
| - const (ProrateNone Proration = "none"; ProrateNow Proration = "now") |
| + // Item gains ItemID. Subscription gains PendingUpdate, PendingExpires, Collecting; 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 // persisted with the operation; never recomputed |
| - IdempotencyKey string |
| - } |
| - type CheckoutState string |
| - const (CheckoutOpen CheckoutState = "open"; CheckoutComplete CheckoutState = "complete"; CheckoutExpired CheckoutState = "expired") |
| + type ChangeRequest struct { Subscription string; Items []ItemChange; Proration Proration; ProrationDate 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 |
| - } |
| - const MaxListPages = 10 // of 100 |
| + type CheckoutRequest struct { Customer, AccountSqid, IntentID, Book, Currency string; Items []CheckoutItem; SuccessURL, CancelURL string; House bool; ExpiresAt time.Time; IdempotencyKey string } |
| + const MaxListPages = 10 |
| + // Outcome classes of a write (provider facts 1-5). The adapter returns exactly one. |
| var ( |
| - ErrPaymentFailed = errors.New("billing: payment failed") // declined; nothing applied |
| - ErrRefused = errors.New("billing: request refused") // a definite 4xx refusal; nothing applied |
| - ErrUncertain = errors.New("billing: outcome unknown") // transport, timeout or 5xx |
| - ErrIncomplete = errors.New("billing: list incomplete") // more than MaxListPages pages |
| + 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") |
| ErrNoHouseCoupon = errors.New("billing: no house coupon configured") |
| ) |
| - // Provider gains: |
| - EnsureCustomer(ctx context.Context, accountSqid, idempotencyKey string) (string, error) |
| - LiveSubscriptions(ctx context.Context, customer string) ([]string, error) // exhaustive or ErrIncomplete |
| - CustomerCheckouts(ctx context.Context, customer string, createdAfter time.Time) ([]CheckoutInfo, error) // exhaustive or ErrIncomplete |
| - StartCheckout(ctx context.Context, req CheckoutRequest) (CheckoutInfo, error) |
| - Checkout(ctx context.Context, sessionID string) (CheckoutInfo, error) |
| - ExpireCheckout(ctx context.Context, sessionID, idempotencyKey string) (CheckoutState, error) // expired, or complete if it completed first |
| - ChangeItems(ctx context.Context, req ChangeRequest) (*Subscription, error) |
| - SetRenewal(ctx context.Context, subscription string, renew bool, idempotencyKey string) (*Subscription, error) |
| - PortalURL(ctx context.Context, customer, returnURL, idempotencyKey string) (string, error) |
| + // 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. |
| func FindItem(sub *Subscription, prices PriceMap, kind, name string) (Item, bool) |
| ``` |
| -- `Recognise`: a team plan item needs `MinMembers` to `MaxTeamMembers`, and sets `Seats`. Other plan items need quantity 1. |
| -- **`billingtest.Fake`** models: |
| - - **Idempotency:** the same key with the same parameters returns the stored result and applies nothing; with other parameters, an error. |
| - - **Pending payments:** `FailPayment` gives a pending update (`PendingExpires` +23 h); `DeclineHard` gives `ErrPaymentFailed`; `PayPending` and `ExpirePending` resolve it. |
| - - **Failure before delivery:** `FailBeforeDelivery` returns `ErrUncertain` and applies nothing, and records no key. |
| - - **Lost responses:** `LoseNextResponse` applies, then returns `ErrUncertain`. |
| - - **Renewal:** `Renew(sub)` moves `PeriodEnd` a year on. Items carry over at their current quantities, and any pending update is dropped. |
| - - **Paging:** `PageSize` (default 100) and counted pages. More than `MaxListPages` pages gives `ErrIncomplete`. |
| - - **Checkout:** sessions open, complete or expired; `CompleteCheckout`, `CompleteBeforeExpire`, `SessionsFor(customer)`. |
| - - **Call counts by method:** `CallsBy map[string]int`. |
| - |
| -- [ ] **Step 1: Write the failing tests** |
| - ```go |
| - func TestRecogniseTeamSeats(t *testing.T) |
| - func TestRecogniseTeamRefuses(t *testing.T) |
| - func TestFindItem(t *testing.T) |
| - func TestFakeIdempotency(t *testing.T) |
| - func TestFakePendingPayLaterExpire(t *testing.T) |
| - func TestFakeFailBeforeDelivery(t *testing.T) // ErrUncertain, nothing applied, key unknown |
| - func TestFakeLostResponse(t *testing.T) // ErrUncertain, applied |
| - func TestFakeRenew(t *testing.T) // PeriodEnd +1y, items kept, pending dropped |
| - func TestFakePagingAndIncomplete(t *testing.T) // PageSize 2, 5 live subs: 3 pages counted; 21 pages: ErrIncomplete |
| - func TestFakeCheckoutRaces(t *testing.T) |
| - ``` |
| -- [ ] **Step 2: Run** `go test ./internal/billing/... -run 'Recognise|FindItem|Fake'`. Expected: FAIL. |
| -- [ ] **Step 3: Implement.** Temporary adapter stubs keep the build. |
| -- [ ] **Step 4: Run** again, plus `go build ./...`. Expected: PASS. |
| -- [ ] **Step 5: Commit** `billing: team items, neutral facts, exhaustive lists, checkout states, and a fake that models failure before delivery, lost responses, pending payments and renewal (plans 6b)`. |
| - |
| -### Task 5: Stripe adapter writes and the extended readiness check |
| +- `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 |
| **Files:** |
| -- Modify: |
| - - `internal/billingstripe/client.go`: `UpdateSubscription`; pending-update decoding; checkout address collection and expiry; `ListCustomerSubscriptionsAll` and `ListCustomerCheckoutsSince`, which page with `starting_after` up to `MaxListPages`, else `ErrIncomplete`; |
| - - `customer.go`: an empty country is allowed; |
| - - `adapter.go`: the methods, `collectingOf`, portal and coupon configuration, the `Check` additions, error classification (`card_error` is `ErrPaymentFailed`; other 4xx `ErrRefused`; transport, timeout and 5xx `ErrUncertain`); |
| - - `cmd/console/billing.go`: `CARLOS_STRIPE_PORTAL_CONFIGURATION` (required), `CARLOS_STRIPE_HOUSE_COUPON` (optional). |
| +- `internal/billingstripe/client.go`, `customer.go`, `adapter.go`; |
| +- `cmd/console/billing.go`; |
| +- `internal/console/billingpass.go`: discovery migrated. |
| **Interfaces:** |
| -- Produces: `SubscriptionItemUpdate`, `SubscriptionUpdate`, `(*Client).UpdateSubscription`, `collectingOf`, and the two list functions. |
| -- The client keeps 6a's rule: **no retries**. A send is one HTTP request. |
| -- Mappings: |
| +- 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): |
| - | Method | Stripe | |
| + | HTTP answer | Class | |
| | --- | --- | |
| - | `StartCheckout` | address collection, `expires_at`, the house coupon (`ErrNoHouseCoupon` before any request) | |
| - | `Checkout` | status, subscription, customer, `metadata[checkout_intent]`, `expires_at` | |
| - | `ExpireCheckout` | on a 400, a session read returning its state | |
| - | `ChangeItems` | `always_invoice` + `pending_if_incomplete`, or `none`; items; the given `proration_date`, sent unchanged | |
| - | `SetRenewal` | `cancel_at_period_end` | |
| - | `PortalURL` | the configured configuration | |
| - | `LiveSubscriptions` | every page, filtered by the adapter's `liveOf` | |
| - | `CustomerCheckouts` | every page created after the time given | |
| -- `Check` additions: |
| - - **Portal:** active; mode; payment method update on; invoice history on; subscription update and cancel off; customer update off or ⊆ {address, name, tax_id}. |
| - - **Coupon:** valid; mode; 100%; no amount off; forever; unrestricted. |
| - |
| -- [ ] **Step 1: Write the failing tests** |
| - ```go |
| - func TestChangeItemsSendsProration(t *testing.T) // includes proration_date exactly as given |
| - func TestChangeItemsOutcomes(t *testing.T) // pending; 402 card_error ErrPaymentFailed; 400 ErrRefused; 500 and timeout ErrUncertain |
| - func TestNoClientRetry(t *testing.T) // a 500 or timeout: exactly one HTTP request |
| - func TestStartCheckoutCollectsAddress(t *testing.T) |
| - func TestEnsureCustomerSendsNoAddress(t *testing.T) |
| - func TestExpireCheckoutStates(t *testing.T) |
| - func TestLiveSubscriptionsPagesToCompletion(t *testing.T) // page 1 ended only, page 2 has an active sub: returned; requests == 2 |
| - func TestLiveSubscriptionsIncomplete(t *testing.T) // 11 full pages: ErrIncomplete |
| - func TestCustomerCheckoutsPages(t *testing.T) |
| - func TestCollectingOf(t *testing.T) |
| - func TestSetRenewal(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/ -run 'ChangeItems|NoClientRetry|StartCheckout|EnsureCustomer|ExpireCheckout|LiveSubscriptions|CustomerCheckouts|CollectingOf|SetRenewal|CheckRefuses|BillingConfig'`. Expected: FAIL. |
| -- [ ] **Step 3: Implement.** |
| -- [ ] **Step 4: Run** again, plus `go test ./internal/billingstripe/` and `GOOS=darwin go vet ./internal/billingstripe/`. Expected: PASS. |
| -- [ ] **Step 5: Commit** `billingstripe: single-send subscription updates, exhaustive paged lists, checkout states that tell expired from completed, and a readiness check for the locked portal and house coupon (plans 6b)`. |
| + | 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` | |
| + | 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)`. |
| ### Task 6: Billing state: seats, facts, intents, house, retirement |
| -**Files:** |
| -- Modify: |
| - - `internal/console/billingstore.go`: |
| - - columns `plan`, `seats`, `paid_seats`, `live`, `collecting`, `pending_update`, `pending_expires`, `seats_checked_at` on `billing_accounts`; |
| - - tables `billing_checkout_intents`, `billing_house`, `billing_retirements`; |
| - - `billingsync.go`: seats and facts in `decideBilling`; `planChange.Seats` goes through 6a's `applyBillingPlan` → `SaveBillingSync`; |
| - - `store_gate.go`. |
| +Accepted; unchanged from revision 3. |
| -**Interfaces:** |
| -- Produces: |
| - ```go |
| - // billingAccount gains Plan; Seats; PaidSeats; Live, Collecting, PendingUpdate; PendingExpires, SeatsCheckedAt. |
| - func billingRenewing(b *billingAccount) bool // b.Live && !b.CancelAtPeriodEnd |
| - type checkoutIntent struct { |
| - AccountID int64 |
| - ID, Session, URL string |
| - Book, Plan, Currency string |
| - Seats int |
| - Packs map[string]int |
| - Items []billing.CheckoutItem |
| - House bool |
| - State string // intentCreating | intentOpen | intentCompleted | intentExpired | intentAbandoned |
| - CreatedAt, ExpiresAt, ReturnedAt, ResolvedAt time.Time |
| - } |
| - func intentTerminal(ci *checkoutIntent) bool // completed, expired or abandoned (Invariant 6) |
| - 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 as revision 2, with `state` in the intents table taking the five values above. |
| -- `decideBilling`: |
| - - copies the facts; |
| - - `PaidSeats` resets on a new period, plan or subscription identity, and otherwise takes the max; |
| - - `planChange.Seats = PaidSeats`; |
| - - an ended subscription clears the team fields. |
| -- **6a integration tests:** discovery → seats; pending replacement → payment; identity change clears seats; `subscription_missing` closure racing a seat write; seats through `SaveBillingSync`'s one transaction. |
| - |
| -- [ ] **Step 1: Write the failing tests:** `TestDecideTeamSeatsHoldUntilRenewal`, `TestDecideUpgradeResetsSeats`, `TestDecideNewSubscriptionClearsSeats`, `TestDecideSavesFacts`, `TestSyncSeatsGoThroughOneTransaction`, `TestDiscoveryThenSeats`, `TestPendingReplacementThenPayment`, `TestMissingClosureRacesSeatWrite`, `TestCheckoutIntentRoundTrip`, `TestIntentTerminal`, `TestBillingHouseOnOff`, `TestRetirementRowsExpire`, `TestBillingRenewingUsesFacts`. |
| -- [ ] **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 and neutral provider facts through 6a's one transaction; Checkout intents, house and retirement rows (plans 6b)`. |
| +- `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)`. |
| -### Task 7: The billing hold, single-send operations and observation |
| +### Task 7: The billing hold, operations and their finality |
| **Files:** |
| -- Create: `internal/console/billinghold.go`, `billingops.go`, `billinghold_test.go`, `billingops_test.go`, `billinglint_test.go`. |
| +- Create: `internal/console/billinghold.go`, `billingops.go`, their tests, and `billinglint_test.go`. |
| - Modify: |
| - - `billingsync.go`: `syncSubscription` becomes lookup → `holdBilling` → `syncSubscriptionLocked`; 6a's other locking paths go through `holdBilling`; `settleOpsLocked` runs after each `applyBillingRead`; |
| - - `billingpass.go`: readiness backoff, and the observation of operations; |
| - - `store_gate.go`: `billing_operations`; |
| - - `billingstore.go`: `problemOperationUnresolved`, for Call 17. |
| + - `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); |
| + - `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. |
| **Interfaces:** |
| -- Consumes: Tasks 4 and 6; 6a's `applyBillingRead`. |
| - Produces: |
| ```go |
| type billingHold struct{ sqid string } |
| func (s *Server) holdBilling(sqid string) (billingHold, func()) |
| func (s *Server) syncSubscriptionLocked(h billingHold, ctx context.Context, acct *Account, subscriptionID string, now time.Time) error |
| - // refreshLocked: the plain sync of the recorded subscription, if any; no period check (Invariant 4). |
| func (s *Server) refreshLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) (*billingAccount, *billing.Subscription, error) |
| - // allowanceLocked: refreshLocked, then the read must be Live and paid, and row.Subscription == read.ID |
| - // and row.PaidPeriodEnd == read.PeriodEnd; else errAllowanceStale (the caller says change.retry). |
| - // Only quantity changes and joins on a live paid subscription call it. |
| func (s *Server) allowanceLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) (*billingAccount, *billing.Subscription, billing.Purchase, error) |
| - const (opQuiet = 10 * time.Minute; opStuck = time.Hour) |
| + 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 |
| + ) |
| type billingOp struct { |
| - ID string |
| - AccountID int64 |
| - Subscription string |
| - PeriodEnd time.Time // the period the request was computed in (Invariant 1) |
| - Kind string // opPack | opPlan | opSeat | opRestore | opRenewal |
| - Request billing.ChangeRequest // exact, including ItemID or "", PriceID, Quantity, Proration, ProrationDate, key |
| - Renew *bool // opRenewal instead of Request.Items |
| - InviteToken string // opSeat or opRestore for one join |
| - AuthorisedBy string // the seat authorisation it consumes (opSeat), "" otherwise |
| - State string // opSending | opUncertain | opPending | opApplied | opFailed | opAbandoned |
| - SentAt, SettledAt time.Time |
| + ID, Subscription, Kind string // Kind: 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) |
| + 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 // ErrOpOutstanding when sending|uncertain|pending holds the subscription |
| - func (s *Store) PutBillingOp(op billingOp) error |
| - func (s *Store) OutstandingBillingOp(subscription string) (*billingOp, error) |
| - func (s *Store) UnresolvedBillingOps(sentBefore time.Time, limit int) ([]billingOp, error) |
| - func quantityPlan(current, target, paidHighest int64) (restoreTo int64, chargeTo int64) // 0 for "no such step" |
| - type opOutcome int |
| - const (opOutcomeApplied opOutcome = iota; opOutcomePending; opOutcomeFailed; opOutcomeUncertain) |
| - // sendOpLocked writes the row (state sending) with the exact request, sends it once, and records the answer: |
| - // a response at the target -> applied; with PendingUpdate -> pending; ErrPaymentFailed or ErrRefused -> failed; |
| - // ErrUncertain -> uncertain. It never sends again. It returns the response for a following step's item id. |
| + 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 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 billingCheckDelay(failures int) time.Duration |
| ``` |
| -- Schema: `billing_operations(id TEXT PRIMARY KEY, account_id INTEGER NOT NULL, subscription TEXT NOT NULL, period_end INTEGER NOT NULL, kind TEXT NOT NULL, request TEXT NOT NULL, renew INTEGER, invite_token TEXT NOT NULL DEFAULT '', authorised_by TEXT NOT NULL DEFAULT '', state TEXT NOT NULL, sent_at INTEGER NOT NULL, settled_at INTEGER NOT NULL DEFAULT 0)`, with a partial unique index on `subscription` WHERE `state IN ('sending','uncertain','pending')`. It is `NonApp`. |
| -- `quantityPlan(current, target, paid)`: |
| - - `target < current`: a reduction (the caller sends `ProrateNone` to `target`); |
| - - otherwise `restoreTo = min(target, paid)` if that is above `current`, and `chargeTo = target` if `target > paid`. |
| -- **Multi-step changes (Invariant 1):** |
| - 1. The handler sends the restore operation. |
| - 2. Only if that returns `applied` with a definite response does it compute the charge request. The item id comes from that response (`FindItem` by price) and the period from the response's `PeriodEnd`. If the period moved, the charge is not sent. |
| - 3. Any other outcome ends the request after the first send. The owner sees the outcome, and a later request recomputes from scratch. |
| -- `settleOpsLocked`, for the subscription's unresolved operation, on every applied read: |
| - 1. `read.ID != op.Subscription` or `read.PeriodEnd != op.PeriodEnd`: `abandoned` (the context moved; the sync already governs the plan). |
| - 2. The items match the request's target, or `CancelAtPeriodEnd == !*Renew`: `applied`. |
| - 3. `PendingUpdate`: `pending`. |
| - 4. The op was `pending`, there is no pending update, and the target is not met: `abandoned`. |
| - 5. The op is `sending` or `uncertain`, the target is not met, there is no pending update, and `now ≥ SentAt + opQuiet`: `abandoned`. |
| - 6. Otherwise unchanged. |
| - |
| - An operation with `AuthorisedBy` set consumes that authorisation when it becomes `applied`, never before (a pending charge that expires leaves the authorisation usable; the one-outstanding rule stops a second charge meanwhile) (Task 11). |
| -- **Observation pass:** for `UnresolvedBillingOps(now - opQuiet)`: `holdBilling`, `syncSubscriptionLocked` (which settles). It sends nothing. With Call 17 (a), an operation still unresolved at `SentAt + opStuck` opens `operation_unresolved`, and changes refuse while it is open. The operator close door allows closing once a fresh read settles it. |
| -- Readiness backoff: `billingCheckDelay` (1, 2, 4, 8, 16, then 30 minutes). |
| +- **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. |
| - [ ] **Step 1: Write the failing tests** |
| ```go |
| func TestBillingLockedHelpersNeverLock(t *testing.T) |
| func TestConsoleBillingHasNoProviderWords(t *testing.T) |
| func TestSyncSubscriptionLockedSharesTheLock(t *testing.T) |
| - func TestRefreshHasNoPeriodCheck(t *testing.T) // ended sub with PeriodEnd, row PaidPeriodEnd cleared: refresh ok |
| - func TestAllowanceAppliesDelayedRenewal(t *testing.T) // PaidPacks {apps:3} P1; Fake Renew to P2 apps 1, no webhook: allowance -> PaidPacks {apps:1}, P2 |
| + func TestRefreshHasNoPeriodCheck(t *testing.T) |
| + func TestAllowanceAppliesDelayedRenewal(t *testing.T) |
| func TestAllowanceRefusesEndedOrMismatched(t *testing.T) |
| - 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 TestRequestPersistedBeforeSend(t *testing.T) // FailBeforeDelivery: row exists with exact request, state uncertain; CallsBy[ChangeItems] == 1 |
| - func TestLostAddResponseIsObservedNotResent(t *testing.T) // restore add 3, LoseNextResponse; clock +2h: no second ChangeItems; settle read shows qty 3: applied; |
| - // the charge to 4 never sent; a new owner request computes one ProrateNow to 4 on the existing item |
| - func TestUnsentRestoreAbandonedAcrossRenewal(t *testing.T) // FailBeforeDelivery on a restore to 3 in P1; Renew; pass: abandoned; CallsBy[ChangeItems] == 1 total |
| - func TestChargeNotSentWhenFirstStepPeriodMoved(t *testing.T) // restore response carries P2 (renewed between): charge not sent |
| - func TestPendingThenPaidThenExpired(t *testing.T) // pending -> PayPending -> applied; second run: ExpirePending -> abandoned |
| - func TestUncertainSettledAfterQuiet(t *testing.T) // uncertain, not applied: refused before opQuiet; abandoned at the first read after |
| + 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 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 TestPendingExpiryAbandons(t *testing.T) |
| + func TestOperatorCloseNeedsEvidence(t *testing.T) // negative read, no note: refused; note not-executed: abandoned; executed without target: 409 |
| func TestOneOutstandingPerSubscription(t *testing.T) |
| func TestReorderedWebhooksSettleOnce(t *testing.T) |
| - func TestStuckOperationOpensProblem(t *testing.T) // provider unreadable for 1 h: operation_unresolved open, changes refused; read recovers: close allowed |
| - func TestObservationPassSendsNothing(t *testing.T) // CallsBy has no ChangeItems/SetRenewal/StartCheckout/ExpireCheckout after a pass |
| + func TestPassesNeverWrite(t *testing.T) // passes over unresolved ops, open intents, drift: CallsBy has zero writes |
| func TestReadinessBackoff(t *testing.T) |
| ``` |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'BillingLockedHelpers|ConsoleBillingHasNo|SyncSubscriptionLocked|Refresh|Allowance|QuantityPlan|RequestPersisted|LostAdd|UnsentRestore|ChargeNotSent|PendingThen|UncertainSettled|OneOutstanding|ReorderedWebhooks|StuckOperation|ObservationPass|ReadinessBackoff'`. Expected: FAIL. |
| +- [ ] **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 3: Implement.** |
| -- [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'Sync|BillingWebhook|BillingSyncPass|Missing|ClaimSQL'`. Expected: PASS. |
| -- [ ] **Step 5: Commit** `console: typed billing hold; single-send operations bound to subscription and period, settled only by observation; refresh separate from the allowance check (plans 6b)`. |
| +- [ ] **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)`. |
| ### Task 8: The billing page and the upgrade entry |
| -Accepted in round 2, except that it now reads intents and operations under the new states. |
| - |
| -**Files:** as revision 2: `billingpage.go`, `billingpage_copy.go`, `templates/billing.html`, `templates/billing_pick.html`, `billingpage_test.go`; the routes, the nav link and the claim entries. |
| +**Files:** as revision 3, plus the continue and seats actions shown on the page. |
| **Interfaces:** |
| -- Produces: `billingPageInput`, `billingPageState`, `decideBillingPage`, `requestCountry`, `currencyQuery`, `handleBilling`, `handleUpgrade` (as revision 2). |
| - `decideBillingPage` rows, first match: |
| | Condition | Notice | Offered | |
| @@ -660,367 +509,237 @@ Accepted in round 2, except that it now reads intents and operations under the n |
| | `operation_unresolved` | `notice.unresolved` | Portal | |
| | other problem | `notice.problem` | Portal if bound | |
| | operator or sponsored row | `notice.operator_plan` | nothing | |
| - | an unresolved operation, or `PendingUpdate` | `notice.pending_payment` | Portal | |
| - | intent `creating` or `open`, not live | `notice.settling` | 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 | |
| | 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". |
| - Terminal intents are ignored (Invariant 6). |
| -- **Currencies** (round 2 accepted these): |
| - - absent: preselect `ChooseCurrency("", requestCountry(r))`; |
| - - a sold code: preselect it; |
| - - anything else (upper case, `usd1`, `<script>`): `currency.refused` showing 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) gets that currency as text and a hidden field, with no radios. A different explicit value shows `currency.fixed`. |
| -- **`/upgrade` contract:** |
| - - `GET /upgrade?plan=<plan>¤cy=<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())`. |
| - - Signed in, by the accounts the viewer owns: one, 303 to `/a/<sqid>/billing?` + kept; several, a picker (most recent first); none, the not-owner message. |
| -- Draft copy (`billingCopy`; the Luna pass replaces every draft): |
| - |
| - | 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.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.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.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 | |
| - | `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` (one case per row, terminal intents ignored), `TestBillingPageOffAndGate`, `TestBillingPageCurrencyRefusals`, `TestBillingPageFixedCurrency`, `TestBillingPageTeamTotals`, `TestUpgradeEntry`, `TestUpgradeAfterSignupLandsOnBilling`. |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'DecideBillingPage|BillingPage|UpgradeEntry|UpgradeAfterSignup'`. Expected: FAIL. |
| -- [ ] **Step 3: Implement.** |
| -- [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'Claim' -timeout 40m` (niced). Expected: PASS. |
| -- [ ] **Step 5: Commit** `console: billing page from neutral facts, refusing every unsold or malformed currency, and the /upgrade entry (plans 6b)`. |
| +- [ ] **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)`. |
| -### Task 9: Checkout: start, replace, observe, return |
| +### Task 9: Checkout: start, continue, replace, return |
| **Files:** |
| -- Create: `internal/console/billingcheckout.go`, `billingcheckout_test.go`. |
| -- Modify: |
| - - `server.go`: `POST /a/{sqid}/billing/checkout`, `GET /a/{sqid}/billing/done`; |
| - - `billingpass.go`: intent observation; |
| - - `billingwebhook.go`: `EventCheckout` observes its intent; |
| - - the claim entries. |
| +- `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`; |
| +- the claim entries. |
| **Interfaces:** |
| -- Consumes: Tasks 4, 6, 7. |
| - Produces: |
| ```go |
| const checkoutLifetime = time.Hour |
| - // observeIntentLocked records what the provider shows for a non-terminal intent. It never expires, creates or resends (Invariant 5): |
| - // open with a session: Checkout(session): complete -> sync its subscription, completed; expired -> expired; open -> unchanged. |
| - // creating: if SentAt + opQuiet has passed, CustomerCheckouts(customer, CreatedAt) (exhaustive): |
| - // a session whose IntentID matches -> record it, then observe it as above; |
| - // none -> abandoned (the create never ran, or ran and its session is what the list shows); |
| - // ErrIncomplete -> unchanged, logged. |
| - // creating within opQuiet: unchanged. |
| - func (s *Server) observeIntentLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, now time.Time) error |
| - // replaceIntentLocked is the only path that expires a session (besides retirement): an owner's explicit new |
| - // Checkout with a different request. ExpireCheckout; expired -> expired; complete -> sync, completed. |
| - func (s *Server) replaceIntentLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, now time.Time) error |
| + // 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) 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) handleBillingDone(w http.ResponseWriter, r *http.Request) |
| - func (s *Server) billingIntentPass(ctx context.Context, now time.Time) // NonTerminalCheckoutIntents: holdBilling, observeIntentLocked only |
| + func (s *Server) billingIntentPass(ctx context.Context, now time.Time) |
| ``` |
| -- **Checkout:** |
| +- **Checkout POST:** |
| 1. Owner, CSRF, ready; parse; `currencyQuery`. |
| 2. `holdBilling`. |
| - 3. Refuse when retiring, on an operator or sponsored row, on an open problem, or on a currency mismatch (the fixed currency read under the hold). |
| - 4. `refreshLocked` (Invariant 4: no allowance check). Refuse if the recorded subscription is `Live`. |
| - 5. With a bound customer, `LiveSubscriptions` (exhaustive). Any live id: `syncSubscriptionLocked`, then refuse with `checkout.already`. `ErrIncomplete`: refuse with `checkout.failed` (Invariant 3). |
| - 6. Handle the previous intent, if non-terminal: |
| - - `observeIntentLocked` first. If it becomes `completed`, refuse (`checkout.already`). |
| - - Still `creating` (within `opQuiet`): refuse (`checkout.preparing`). |
| - - Still `open`: if its stored request equals the new one and `ExpiresAt` is more than 5 minutes away, 303 to its URL (reuse). Otherwise `replaceIntentLocked`; `completed` refuses. |
| - |
| - Terminal intents are ignored. |
| - 7. Bind a customer if none. |
| - 8. Put a new intent: `creating`, the whole request, `ExpiresAt = now+checkoutLifetime`, key `checkout:<id>`. |
| - 9. `StartCheckout`, sent once: |
| - - success: `open`, with session and URL; 303; |
| - - `ErrRefused`: `abandoned`, with `checkout.failed`; |
| - - `ErrUncertain`: stays `creating`, with `checkout.uncertain`. Observation settles it after `opQuiet`. |
| - |
| - **No resend, ever** (Invariant 1). |
| -- **Done:** |
| - 1. Owner; the intent named by the session. |
| - 2. `holdBilling`; mark returned. |
| - 3. `observeIntentLocked`. |
| - 4. 303 with `checkout.done` if the plan is now paid, otherwise `notice.settling`. |
| -- **Discovery:** 6a's discovery selects accounts with a non-terminal intent. `billingIntentPass` observes them only. |
| -- Draft copy: revision 2's, plus `checkout.preparing` "A payment page is still being prepared. Try again in a minute." and `checkout.uncertain` "We couldn't confirm the payment page was created. Try again in a few minutes." |
| - |
| -- [ ] **Step 1: Write the failing tests** |
| - ```go |
| - func TestCheckoutStartsSession(t *testing.T) |
| - func TestCheckoutTeamSeats(t *testing.T) |
| - func TestCheckoutReusesTheSameRequest(t *testing.T) |
| - func TestCheckoutReplacesOnExplicitNewRequest(t *testing.T) |
| - func TestCheckoutExpiryLosesToCompletion(t *testing.T) |
| - func TestCheckoutAfterCancellationWithOldRecorded(t *testing.T) // old sub ended, still recorded with a PeriodEnd: Checkout proceeds (Invariant 4) |
| - func TestCheckoutRefusesScheduledCancellation(t *testing.T) |
| - func TestCheckoutSeesLiveSubscriptionOnPageTwo(t *testing.T) // PageSize 2, live sub on page 2: refused; CallsBy[LiveSubscriptions pages] == 2 |
| - func TestCheckoutRefusesIncompleteList(t *testing.T) |
| - func TestCheckoutFailBeforeDelivery(t *testing.T) // FailBeforeDelivery: creating; immediate retry: checkout.preparing, no call; after opQuiet: observed abandoned; retry creates once |
| - func TestCheckoutLostResponseObserved(t *testing.T) // LoseNextResponse: creating; after opQuiet the customer list finds the session by intent id: open, reused; StartCheckout calls == 1 |
| - func TestCheckoutCreateRefused(t *testing.T) // ErrRefused: abandoned at once |
| - func TestPassRightAfterCheckoutKeepsSession(t *testing.T) // pass 1 s after start: session still open, CallsBy[ExpireCheckout] == 0 |
| - func TestPassObservesCompletedIntent(t *testing.T) |
| - func TestCompletedIntentDoesNotBlockNextPurchase(t *testing.T) // completed intent, subscription since ended: Checkout proceeds |
| - func TestCheckoutRefusesOperatorRows(t *testing.T) |
| - func TestCheckoutNotReadyStartsNothing(t *testing.T) |
| - func TestCheckoutHouseWithoutCoupon(t *testing.T) |
| - func TestCheckoutCurrencyRules(t *testing.T) |
| - func TestCheckoutDoneSyncs(t *testing.T) |
| - func TestCheckoutDoneSettling(t *testing.T) |
| - ``` |
| - Each test asserts `CallsBy` against the budget's Checkout branches. |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'Checkout|PassRightAfter|PassObserves|CompletedIntent'`. Expected: FAIL. |
| -- [ ] **Step 3: Implement.** |
| -- [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'Claim' -timeout 40m` (niced). Expected: PASS. |
| -- [ ] **Step 5: Commit** `console: Checkout sends each create once, observes rather than resends, never expires a session from the pass, and judges subscriptions, not past intents (plans 6b)`. |
| + 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. |
| + 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)`. |
| ### Task 10: Pack changes, plan upgrades and renewal |
| -**Files:** |
| -- Create: `internal/console/billingchange.go`, `billingchange_test.go`. |
| -- Modify: `server.go` (the change and renewal routes); the claim entries. |
| +**Files:** `internal/console/billingchange.go` and its test; the change and renewal routes; the claim entries. |
| + |
| +**Interfaces:** `prorateEstimate`, `handleBillingChange`, `handleBillingRenewal`. |
| -**Interfaces:** |
| -- Produces: `prorateEstimate`, `handleBillingChange`, `handleBillingRenewal`. |
| - **Change:** |
| - 1. Owner, CSRF, `requireFreshAuth` for a confirmed charge (before the hold). |
| + 1. Owner, CSRF, and `requireFreshAuth` for a confirmed charge. |
| 2. `holdBilling`. Refuse when retiring, on a problem, or on a row that isn't billing-owned. |
| - 3. `allowanceLocked` (Invariant 4); `errAllowanceStale` gives `change.retry`. |
| - 4. Refuse on an outstanding operation or `PendingUpdate` (`change.outstanding`). |
| - 5. **pack:** `quantityPlan(current, target, row.PaidPacks[name])`: |
| + 3. If an op is outstanding, `finishOpLocked` first; still outstanding is `change.outstanding`. |
| + 4. `allowanceLocked`. |
| + 5. **pack:** `quantityPlan(current, target, PaidPacks[name])`: |
| - a reduction is one `opPack` with `ProrateNone`; |
| - - otherwise the restore, then the charge only after a definite applied restore (Task 7). |
| - 6. **plan:** one `opPlan` swap with `ProrateNow`. |
| - 7. With no step: `change.none`. |
| - 8. A charge without `confirmed`: release, and render the confirm page. |
| - 9. Each operation's `ProrationDate` is `now`, captured once and persisted. |
| - 10. Settle: `syncSubscriptionLocked`. |
| - 11. Flash by the last outcome: `change.done`, `change.pending`, `change.declined`, `change.uncertain`, or `change.failed`. |
| -- **Renewal:** `holdBilling`, then refuse when retiring. `refreshLocked`; refuse on an outstanding operation. One `opRenewal`, sent once, then settle. |
| -- Draft copy: revision 2's. |
| - |
| -- [ ] **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 (add, si_n from the response) -> charge si_n to 4; two ops; CallsBy[ChangeItems] == 2 |
| - 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) // charged, not restored free |
| - func TestChangeAfterReplacementSubscription(t *testing.T) |
| - func TestChangeUncertainNotResent(t *testing.T) // LoseNextResponse: change.uncertain; pass after opQuiet settles applied; CallsBy[ChangeItems] == 1 |
| - 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|OneOutstanding|RetryAfterDecline|ChangeTwice|ChangeComputes|ChangeAfter|ChangeUncertain|PlanUpgrade|UpgradeRefused|ChangeUses|Renewal|ChangeAndRenewal'`. Expected: FAIL. |
| -- [ ] **Step 3: Implement.** |
| -- [ ] **Step 4: Run** again, plus the Claim suite (niced). Expected: PASS. |
| -- [ ] **Step 5: Commit** `console: pack changes and upgrades as single-send operations after the allowance check; stop and resume renewal (plans 6b)`. |
| - |
| -### Task 11: Seats: authorised invites, admission, reconciliation |
| + - 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. |
| + 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." |
| + |
| +- [ ] **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)`. |
| + |
| +### Task 11: Seats: authorised invites, admission, reconciliation, drift |
| **Files:** |
| -- Create: `internal/console/billingseats.go`, `billingseats_test.go`. |
| -- Modify: |
| - - `store.go`: the invite seat-authorisation columns, plus `seat_consumed_at`; |
| - - `server.go`: invite, accept, revoke; |
| - - `ownership.go`: removal; |
| - - `billingpass.go`: seat drift; |
| - - `apibilling.go`: the `seats_unpaid` close; |
| - - `billingstore.go`. |
| +- `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`; |
| +- `ownership.go`: removal; |
| +- `billingpass.go`: drift observation, reads only; |
| +- `apibilling.go`: the `seats_unpaid` close; |
| +- the claim entries. |
| **Interfaces:** |
| -- 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 (s *Store) ConsumeInviteSeatAuthorisation(token string, now time.Time) error // called by settleOpsLocked when an opSeat becomes applied |
| - func seatCovered(a *seatAuthorisation, row *billingAccount, book *plans.PriceBook) bool // unconsumed, same plan, book, currency, price not above |
| - type admitOutcome int |
| - const (admitJoined admitOutcome = iota; admitWaitPayment; admitNeedsConsent; admitOutstanding; admitUncertain; 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, 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) |
| - ``` |
| -- **Invite:** as revision 2. Under the member lock and `holdBilling`: `allowanceLocked`. A seat charge would be needed if `Billed(members + pending + 1) > max(cur, PaidSeats)`. Then the confirm, `requireFreshAuth`, and storing the authorisation. |
| -- **`admitMember`** (Invariant 2), under `lockMembers(sqid)`: |
| +- 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(acceptInviteTx)`. |
| - 3. Billing team: `holdBilling`, refuse when retiring, `allowanceLocked`. |
| - 4. An outstanding operation or `PendingUpdate`: if it is this invite's `opSeat` in `pending`, `admitWaitPayment`; otherwise `admitOutstanding`. |
| - 5. **Recompute capacity from scratch, every time:** `need = Billed(members+1)`, `cur` = the plan item's quantity, `paid = PaidSeats`. A previous applied charge for this invite only raised `cur` and `paid`; it is not consulted. |
| - - `need ≤ cur`: free. |
| - - `cur < need ≤ paid`: one `opRestore` (`ProrateNone`). It must return `applied` definitely, else `admitUncertain` or `admitWaitPayment`. |
| - - `need > paid`: `seatCovered` must hold (unconsumed), else `admitNeedsConsent`. Then `quantityPlan(cur, need, paid)`: a restore, then a charge (an `opSeat` carrying the token and the authorisation) only after a definite applied restore. `applied` goes on; `pending` or `failed` gives `admitWaitPayment`; `uncertain` gives `admitUncertain`. |
| - 6. `membershipTransition(acceptInviteTx)`, then settle, inside both locks. |
| -- If the membership write fails after an applied charge, the paid seat stays: a credit. The next admission (anyone's) finds `need ≤ cur` and takes it. The first invitee's retry recomputes; if it needs another charge, its consumed authorisation gives `admitNeedsConsent`. |
| -- **Revoke:** refused while the invite's `opSeat` is `sending`, `uncertain` or `pending`. |
| -- **`reconcileSeatsLocked`:** |
| - - `refreshLocked`, then `allowanceLocked` when live and paid. |
| - - Refuse on an outstanding operation. |
| - - `want < cur`: `opSeat`, `ProrateNone`. |
| - - `cur < want ≤ PaidSeats`: `opRestore`, `ProrateNone`. |
| - - `want > PaidSeats`: open `seats_unpaid`. Close it when resolved. |
| - - Daily re-check while it is open. |
| - - Callers: removal; the pass on drift. |
| -- **The `seats_unpaid` close door:** as revision 2 (accepted). |
| -- Draft copy: revision 2's, plus `seats.join_uncertain` "We couldn't confirm the account's payment for your seat. Try the link again in a few minutes." |
| - |
| -- [ ] **Step 1: Write the failing tests** |
| - ```go |
| - func TestInviteRecordsSeatAuthorisation(t *testing.T) |
| - func TestJoinChargesAuthorisedSeat(t *testing.T) // authorisation consumed |
| - 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) // 10 members: A's charge applied, A's membership write fails; B joins free (CallsBy[ChangeItems] unchanged); |
| - // A retries: need 12 > paid 11, authorisation consumed -> admitNeedsConsent; members 11, paid 11 |
| - func TestJoinUncertainNotResent(t *testing.T) // LoseNextResponse on the seat charge: admitUncertain; retry before opQuiet: admitOutstanding, no call; |
| - // after settle (applied): retry joins free; CallsBy[ChangeItems] == 1 |
| - func TestJoinFailBeforeDelivery(t *testing.T) // FailBeforeDelivery: uncertain; after opQuiet: abandoned; retry charges once (authorisation unconsumed) |
| - func TestRevokedInviteStartsNoPurchase(t *testing.T) |
| - func TestJoinAfterDelayedRenewal(t *testing.T) |
| - func TestUnsentSeatRestoreAbandonedAcrossRenewal(t *testing.T) // FailBeforeDelivery on opRestore in P1; Renew; pass: abandoned; nothing sent in P2 |
| - func TestRejoinRestoresBeforeAdmission(t *testing.T) |
| - func TestLeaveReducesAtRenewal(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|RevokedInvite|UnsentSeat|Rejoin|Leave|SeatsUnpaid|PassOpens|AcceptAndRemove'`. Expected: FAIL. |
| -- [ ] **Step 3: Implement.** |
| -- [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'Invite|BillingSyncPass|Claim' -timeout 40m` (niced). Expected: PASS. |
| -- [ ] **Step 5: Commit** `console: team seats decided at admission every time, single-use authorisations, applied charges as credits; leaves reduce at renewal; seats_unpaid resolves itself (plans 6b)`. |
| + 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)`. |
| ### Task 12: The locked portal |
| -Unchanged from revision 2. |
| +Unchanged. `handleBillingPortal`: owner, CSRF, ready, a bound customer, `requireFreshAuth`, `PortalURL`, then 303. No hold. |
| -- Produces `handleBillingPortal`: owner, CSRF, ready, a bound customer, `requireFreshAuth`, `PortalURL`, then 303. No hold. |
| -- **Tests:** `TestPortalOpens`; `TestPortalGates`. |
| -- [ ] **Steps 1-5:** write the failing tests, run them (FAIL), implement, run them (PASS), commit `console: owners reach the locked portal for cards and invoices (plans 6b)`. |
| +- **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)`. |
| ### Task 13: The retirement gate for account deletion |
| -**Files:** |
| -- Create: `internal/console/billingretire.go`, `billingretire_test.go`. |
| -- Modify: `ownership.go` (`handleDeleteAccount`). |
| +**Files:** `internal/console/billingretire.go` and its test; `ownership.go`. |
| -**Interfaces:** |
| -- Produces: |
| - ```go |
| - // retireGateLocked (Invariants 3 and 6): |
| - // 1. with a bound customer, LiveSubscriptions (exhaustive; ErrIncomplete refuses: delete.unverified); |
| - // each live id: syncSubscriptionLocked, then require CancelAtPeriodEnd && !Collecting && !PendingUpdate; |
| - // 2. no unresolved operation on any of them; |
| - // 3. the intent, only if non-terminal: observeIntentLocked; still open -> replaceIntentLocked (expire); |
| - // still creating -> refuse (delete.checkout); completed -> its subscription is judged in step 1 on the next run. |
| - // Terminal intents are ignored. |
| - func (s *Server) retireGateLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) error |
| - ``` |
| -- `handleDeleteAccount`: |
| - 1. `holdBilling`, `BeginRetirement`, then the gate. A refusal is `EndRetirement` and a flash. |
| - 2. `requireFreshAuth`. |
| - 3. On the replayed POST: `holdBilling`; `Retiring` must still hold; the gate again; then `DeleteAccount`. |
| +**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. |
| - Every purchase, change, renewal, join and reconciliation refuses while retiring, checked after the hold. |
| -- Draft copy: revision 2's, plus `delete.unverified` "We couldn't check every subscription for this account. Try again later, or ask an operator." |
| +`handleDeleteAccount`: `BeginRetirement` and the gate; then `requireFreshAuth`; on the replay, the gate again, then `DeleteAccount`. Every purchase path refuses while retiring. |
| -- [ ] **Step 1: Write the failing tests** |
| - ```go |
| - func TestDeleteRefusedWhileRenewing(t *testing.T) |
| - func TestDeleteAfterCompletedPurchaseAndStop(t *testing.T) // purchase -> completed intent -> stop renewal -> delete: allowed; CallsBy per gate run == L(1) + 1 sync |
| - func TestDeleteRefusedWhileCollecting(t *testing.T) |
| - func TestDeleteRefusedWithUnresolvedOp(t *testing.T) |
| - func TestDeleteSeesLiveSubscriptionOnPageTwo(t *testing.T) |
| - func TestDeleteRefusesIncompleteList(t *testing.T) |
| - func TestDeleteExpiresOpenCheckout(t *testing.T) // open session expired by the gate; CompleteBeforeExpire: synced, then judged as a live sub (refused) |
| - func TestDeleteRefusedWhileCheckoutCreating(t *testing.T) |
| - func TestResumeDuringRetirementRefused(t *testing.T) |
| - func TestDeleteGateRerunsAfterStepUp(t *testing.T) |
| - func TestStaleRetirementClears(t *testing.T) |
| - ``` |
| - Each test asserts `CallsBy` against the deletion-gate row of the budget. |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'Delete|ResumeDuringRetirement|StaleRetirement'`. Expected: FAIL. |
| -- [ ] **Step 3: Implement.** |
| -- [ ] **Step 4: Run** again. Expected: PASS. |
| -- [ ] **Step 5: Commit** `console: a retirement gate that judges every live subscription and ignores reconciled intents (plans 6b)`. |
| +- [ ] **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)`. |
| ### Task 14: The house flag |
| -Unchanged from revision 2: the `POST /api/cli/billing/house` operator door and `carlos billing house -account <sqid> -on|-off -note`. |
| +Unchanged: the operator door `POST /api/cli/billing/house` and `carlos billing house -account <sqid> -on|-off -note`. |
| - **Tests:** `TestBillingHouseDoor`, `TestBillingCLIHouse`. |
| -- [ ] **Steps 1-5:** write the failing tests, run them (FAIL), implement, run them (PASS), commit `console, cli: operators mark house accounts, whose checkout carries the 100% coupon (plans 6b)`. |
| +- [ ] **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)`. |
| ### Task 15: Copy, docs, census and gates |
| -- [ ] **Luna copy pass,** as revision 2. Add to the facts: |
| - - nothing is retried behind the owner's back; |
| - - an unclear change is checked and never charged twice. |
| -- [ ] **Docs,** as revision 2. Add `operation_unresolved` to the operators' section. |
| -- [ ] **Census from the final diff:** `make census-card` on the finished branch, with units and envelopes from its output. Expect admission, membership transitions, the retirement gate, `sendOpLocked`, `settleOpsLocked`, `observeIntentLocked`, `replaceIntentLocked`, the passes, eight routes and five tables. `census-propose` takes the body and sites changes; hand-written decisions take new units. Review every changed function in each re-pinned envelope, and keep the record-write gate. Astra approves; Paul takes the decisions. |
| -- [ ] **Gates:** the darwin and windows builds; `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), push, wait for green CI, then Astra's whole-branch review. |
| +- [ ] **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; |
| + - Astra approves; Paul takes the decisions. |
| +- [ ] **Gates:** the darwin and windows builds; the census tests; the package tests. |
| +- [ ] **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. |
| -- With `CARLOS_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 after merging main; the whole-branch review has no open Critical or Important finding. |
| +- Nothing user-facing changes with billing unset, 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 |
| -**Round 1** (`b6005e86`). Round 2 accepted fixes 1, 9, 10, 12 and 13, and the readiness, census and neutrality gaps. Fixes 2 to 8 and 11 are reworked in revision 3, below. |
| +**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. |
| -**Round 2** (`d705d1c7`): |
| +**Round 3** (`c2e313e3`): |
| -| Finding | Revision 3 | |
| +| Finding | Revision 4 | |
| | --- | --- | |
| -| 1. replay changes the request under the same key | Invariant 1: an operation is one request, persisted exactly (item id or absence, price, quantity, proration, proration timestamp, key) before its single send. Nothing is ever resent. A lost response is observed (`TestLostAddResponseIsObservedNotResent`, clock advanced). | |
| -| 2. a free restore in another period | Operations are bound to subscription and period. Unsent steps are never executed later. Settlement abandons on a moved period. A charge step is computed only from a definite response in the same period (`TestUnsentRestoreAbandonedAcrossRenewal`, the seat twin). | |
| -| 3. an applied invite charge as an admission pass | Invariant 2: capacity is recomputed at every admission. An applied charge is a credit any admission can take, and authorisations are single use (`TestAppliedInviteChargeIsACreditNotAPass`). | |
| -| 4. one page of live subscriptions | Invariant 3: lists page to completion, up to 10 pages, else `ErrIncomplete`, and the caller refuses (page-two tests in Tasks 5, 9 and 13). | |
| -| 5. freshen blocks returning customers | Invariant 4: `refreshLocked` with no period check for Checkout, retirement and the page; `allowanceLocked` only for quantity changes and joins on a live paid subscription (`TestCheckoutAfterCancellationWithOldRecorded`). | |
| -| 6. the pass expires a live Checkout | Invariant 5: the passes only observe. Only an explicit replacement or the retirement gate expires a session (`TestPassRightAfterCheckoutKeepsSession`). | |
| -| 7. a completed intent blocks retirement | Invariant 6: terminal intents are history. The gate judges the exhaustive subscription list (`TestDeleteAfterCompletedPurchaseAndStop`). | |
| -| 8. replaying an expired, never-executed create | No Checkout create is resent. A `creating` intent is observed after `opQuiet` through the customer's sessions, by intent id. If none is found, it is abandoned. `ErrRefused` abandons at once. The Fake models failure before delivery (`TestCheckoutFailBeforeDelivery`). | |
| -| 9. the budget misses algorithm costs | The budget is by branch and cardinality (`L(n)`, `S`, `k`, `j`). The recovery, Checkout and retirement tests assert `CallsBy`. | |
| -| Fake gaps | Failure before delivery, `Renew` across a period boundary, paging, and call counts by method (Task 4). | |
| +| 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. | |
| --- |
| @@ -1042,17 +761,18 @@ 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. |
| + 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:** `https://<console>/billing/webhook`, the six events, API version `2025-02-24.acacia`. |
| -6. **Retry settings:** cancel after all retries. Pending updates expire after about 23 hours. |
| -7. **The restricted key:** Checkout Sessions write (which also allows listing a customer's sessions), Customers write, Subscriptions write, Customer portal write, Billing portal configurations read, Prices, Products and Coupons read. Nothing else. |
| +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), the revision-2 list plus: |
| - - a request timed out at the network edge, then observed after 10 minutes (Call 17); |
| - - a Checkout create whose response is lost, found again by intent id; |
| - - a customer with more than 100 subscriptions (paging); |
| - - a pack restore interrupted across a renewal; |
| - - the hourly pass running while a buyer is on the Checkout page. |
| +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`); |
| + - 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. |
| 10. **Flagship:** the same in live mode on Paul's approval, then publish `https://<console>/upgrade?plan=<plan>¤cy=<cur>`. |