carlos / platform Public

Plans 4a: warnings, grace and notice. Hourly measurement of five caps, 80% warnings (owner email, account banner, CLI warning line), grace clocks per cap, notice recorded only for owners after a cap went over; nothing cut off; dormant without CARLOS_PLAN_CATALOG

Squashed from plans-4-notices-grace into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 9623e47cddbea06353cd3bdec1e1974d3f7daf4b parent 606afcb
37 files changed, +2,236 −8
  • auth.go +17 −3
  • cmd/console/main.go +1 −0
  • docs/site/plans.md +23 −0
  • docs/superpowers/notes/census-proposal-plans-4-notices-grace.md +45 −0
  • docs/superpowers/notes/plans-4a-ledger.md +21 −0
  • docs/superpowers/plans/2026-10-25-plans-4a-warnings-and-grace.md +324 −0
  • docs/superpowers/specs/CODEX-FINDINGS-PLANS-4A-CODE.md +53 −0
  • docs/superpowers/specs/CODEX-REVIEW-BRIEF-PLANS-4A-CODE.md +50 −0
  • docs/superpowers/specs/LUNA-COPY-BRIEF-PLANS-4A.md +45 −0
  • docs/superpowers/specs/LUNA-COPY-RESULT-PLANS-4A.md +21 −0
  • internal/console/apicli.go +8 −1
  • internal/console/claim_invariant_fixtures_test.go +1 −0
  • internal/console/claim_invariant_probes_worker_test.go +14 −0
  • internal/console/claim_workers.go +1 −0
  • internal/console/mailcounts.go +9 −0
  • internal/console/plancaps_copy.go +20 −0
  • internal/console/plangrace.go +127 −0
  • internal/console/plangrace_cli_test.go +100 −0
  • internal/console/plangrace_store.go +117 −0
  • internal/console/plangrace_test.go +240 −0
  • internal/console/plangrace_view_test.go +90 −0
  • internal/console/plangracepass.go +311 −0
  • internal/console/plangracepass_test.go +146 −0
  • internal/console/planmeasure.go +105 −0
  • internal/console/planmeasure_test.go +129 −0
  • internal/console/server.go +13 −2
  • internal/console/store.go +5 −1
  • internal/console/store_gate.go +1 −0
  • internal/console/templates/layout.html +2 −1
  • internal/console/testdata/claim-routes.txt +1 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +2 −0
  • internal/provision/testdata/plan14-root-reads-plans-4-notices-grace.tsv +19 −0
  • internal/provision/testdata/plan14-root-reads-plans-4a-store.tsv +13 −0
  • internal/usage/statement.go +15 −0
  • internal/usage/statement_test.go +26 −0
  • planwarnings.go +46 −0
  • planwarnings_test.go +75 −0

CI passed — run details

diff --git a/auth.go b/auth.go
index 47565dc94..a721fa7bf 100644
--- a/auth.go
+++ b/auth.go
@@ -392,6 +392,9 @@ type consoleClient struct {
base string
token string
httpc *http.Client
+ // warn is the one plan-warning transport every request of this client
+ // goes through, JSON, upload or stream, so a warning prints once.
+ warn *planWarningTransport
}
func newConsoleClient(base, token string) *consoleClient {
@@ -400,9 +403,11 @@ func newConsoleClient(base, token string) *consoleClient {
// new host) and surfaces unreplayable POSTs as raw 3xx — both wrong.
// Refusing uniformly lets every method see the 3xx + Location, which
// consoleMoved (apimode.go) turns into an explanation and an offer.
- return &consoleClient{base: base, token: token, httpc: &http.Client{
+ warn := &planWarningTransport{out: os.Stderr}
+ return &consoleClient{base: base, token: token, warn: warn, httpc: &http.Client{
Timeout: 30 * time.Second,
CheckRedirect: neverFollow,
+ Transport: warn,
}}
}
@@ -529,7 +534,7 @@ func (c *consoleClient) doMultipartHeaders(ctx context.Context, method, path str
// A client of its own — see shipHTTPClientTimeout above — never c.httpc,
// whose 30s absolute Timeout is sized for the JSON verbs, not a large
// upload. Same no-redirect rule as c.httpc, same reason.
- client := &http.Client{Timeout: shipHTTPClientTimeout, CheckRedirect: neverFollow}
+ client := &http.Client{Timeout: shipHTTPClientTimeout, CheckRedirect: neverFollow, Transport: c.transport()}
res, err := client.Do(req)
if err != nil {
return 0, nil, err
@@ -571,7 +576,7 @@ func (c *consoleClient) doStream(ctx context.Context, method, path string, body
if c.token != "" {
req.Header.Set("Authorization", "Bearer "+c.token)
}
- client := &http.Client{Timeout: shipHTTPClientTimeout, CheckRedirect: neverFollow}
+ client := &http.Client{Timeout: shipHTTPClientTimeout, CheckRedirect: neverFollow, Transport: c.transport()}
res, err := client.Do(req)
if err != nil {
return nil, err
@@ -583,6 +588,15 @@ func (c *consoleClient) doStream(ctx context.Context, method, path string, body
return res, nil
}
+// transport is the client's plan-warning transport, or the default one
+// for a consoleClient built without newConsoleClient.
+func (c *consoleClient) transport() http.RoundTripper {
+ if c.warn == nil {
+ return http.DefaultTransport
+ }
+ return c.warn
+}
+
// neverFollow is the one redirect policy every console client uses.
func neverFollow(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
diff --git a/cmd/console/main.go b/cmd/console/main.go
index d78578a29..773114ee3 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -603,6 +603,7 @@ func serve() {
// The plan limits pass (internal/console/planlimits.go): publishes each
// account's limits record. A no-op with CARLOS_PLAN_CATALOG unset.
go srv.RunClaimWorker(context.Background(), "StartPlanLimitsPass")
+ go srv.RunClaimWorker(context.Background(), "StartPlanGracePass")
// The plans deployment marker (internal/console/plansmarker.go): once per
// start. Writes nothing on a deployment that never set a catalog.
go srv.RunClaimWorker(context.Background(), "PublishPlansMarker")
diff --git a/docs/site/plans.md b/docs/site/plans.md
index 006392789..c8581c6c2 100644
--- a/docs/site/plans.md
+++ b/docs/site/plans.md
@@ -53,3 +53,26 @@ carlos accounts plan --account bac --set free --sponsored limits.json --reason "
```
`limits.json` holds any of the limit names from the catalog. A sponsored limit can go above a ceiling: that is a decision you made for that account.
+
+## Warnings and grace
+
+Once an hour the console compares each account's usage with its limits, for five caps:
+
+- apps and instances running;
+- object storage;
+- emails sent today;
+- bandwidth this month;
+- awake hours this month.
+
+The figures come from what the console already records: its own app list, the monthly usage statements, the daily storage sweep and the mail counts. A cap whose limit is 0 is skipped.
+
+At 80% of a limit, the account's owners get an email, and a banner appears on every account page. A `carlos` command run against the account prints a line starting `warning:`, from a CLI new enough to print it.
+
+Going over the limit starts a grace period:
+- 7 days for apps and instances, and for storage;
+- the rest of the UTC day for email;
+- the rest of the UTC month for bandwidth and awake hours.
+
+While an account is over, its owners get one reminder a day, saying when grace ends and how to get back under: buy a pack, move to a bigger plan, or clean up.
+
+Nothing is refused, slowed or stopped yet. The console only warns and keeps the clock. It also records when an owner actually received notice: an email that was accepted for delivery, an owner viewing an account page with the banner, or an owner's CLI printing the warning. Whatever acts after grace starts only once grace has ended and an owner received notice at least 3 days earlier, so an account nobody has heard from is never cut off.
diff --git a/docs/superpowers/notes/census-proposal-plans-4-notices-grace.md b/docs/superpowers/notes/census-proposal-plans-4-notices-grace.md
new file mode 100644
index 000000000..7b818539c
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-plans-4-notices-grace.md
@@ -0,0 +1,45 @@
+# Census approval: plans-4-notices-grace
+
+Ruling `census-ruling-plans-4-notices-grace`. Every change below keeps the disposition it already has, so it needs an approval, not a decision.
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `auth.go` `consoleClient.doMultipartHeaders` | body | unchanged (1) | the upload client uses the console client's plan-warning transport (adds a request header, prints response warnings to stderr), the same timeout and no-redirect policy (Astra plans-4a finding 5). No read added. |
+| `cmd/console/main.go` `serve` | body | unchanged (3) | starts one more claim worker, StartPlanGracePass (plans 4a), beside StartPlanLimitsPass; it returns at once with no plan catalog. No read added. |
+| `internal/console/plangrace_store.go` `Store.PutCapState` | body | unchanged (1) | the upsert keeps notice already recorded for the same episode (same period and first over) instead of overwriting it (Astra plans-4a finding 1). Same table, same one statement; no read added. |
+| `internal/console/plangrace_store.go` `Store.RecordCapNotice` | body | unchanged (1) | takes the rows as shown and updates only the matching episode (period and first over), never before the first over (Astra plans-4a finding 2). One parameterised UPDATE per shown row on the same table; no read added. |
+| `internal/console/store.go` `Store.migrate` | body | unchanged (2) | calls migratePlanGrace last, which creates the console's own plan_cap_state table (plans 4a). No read added here; the new store units are the plans-4a-store decision. |
+| `internal/console/templates/layout.html` `external` | body | unchanged (1) | the account layout renders .PlanNotices as banner lines above main content (plans 4a). No read added. |
+
+Envelopes re-pinned: `.`, `cmd/console`, `internal/console`, `internal/console/templates`, `internal/usage`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Escalate if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. An escalation goes to the census owner as a decision.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `auth.go` `consoleClient.doMultipartHeaders`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-pro-6214-service-runs;identity=the carlos CLI on the caller's own machine, as that caller: a person, or a server holding a run credential as CARLOS_SERVICE_TOKEN; no box unit runs carlos run;basis=new: consoleClient.doMultipartMethod's body moved here unchanged, plus caller-supplied request headers (a run's Idempotency-Key), set before the content type and the bearer, which they cannot override; its one site, io.ReadAll of the console's response body, is doMultipartMethod's, J4 root-input as that row was
+- `cmd/console/main.go` `serve`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=PROPOSED-scan-demand-revival;basis=Console service wires the optional callback signer and starts the claim-guarded queue worker. The same three data path literals move; it does not add a privileged reader.;rev3=PROPOSED-email-signin;identity=the console (cmd/console serve under console.service, user carlos-console);basis=passes CARLOS_CONSOLE_NAME to NewServer as Config.ConsoleName, the name the console's emails use; the same three /data literals at the same offsets; no read added;rev3=PROPOSED-s3-change-index;identity=the console (cmd/console serve under console.service, user carlos-console);basis=arms the record view when CARLOS_CHANGE_INDEX=read (armChangeIndex) for the run and seed sweeps and starts its backstop loop; the same three /data literals at the same offsets; no read added;rev3=census-ruling-db-region-forward-2;identity=the console (cmd/console serve under console.service, user carlos-console);basis=parses CARLOS_DB_FORWARD (dbForward) into Config.DBForward and builds its http.Server with console.NewHTTPServer, the same two timeouts; the same three /data literals at the same offsets; no read added;rev3=census-ruling-sec-sidecar-create-gate;basis=serve now parses CARLOS_SIDECAR_ACCOUNTS (sidecarAccounts, a pure env parse with log.Fatalf on a bad or empty-list value) before opening anything and passes it into console.Config.SidecarAccounts. No read was added: the same 3 root read sites.;rev3=census-ruling-sec-mail-user-boundary;basis=reads CARLOS_MAIL_USER_BOUNDARY and passes it to mail.NewAWSProvisioner; runs the one-shot boundary sweep behind CARLOS_MAIL_BOUNDARY_SWEEP=1, refused under CARLOS_HOST_CLAIM;rev3=census-ruling-pro-6214-service-runs;basis=the console (cmd/console serve, user carlos-console): reads CARLOS_RUN_KEYS, an environment variable, into Config.RunKeysEnabled; keyed run creates are refused 503 keys_not_ready unless it is on; the same three /data literals; no read added
+- `internal/console/plangrace_store.go` `Store.PutCapState`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-plans-4a-store;basis=root-input; console SQL on its own plan_cap_state table, as its store siblings (J4); plans 4a warnings and grace, which refuse nothing
+- `internal/console/plangrace_store.go` `Store.RecordCapNotice`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-plans-4a-store;basis=root-input; console SQL on its own plan_cap_state table, as its store siblings (J4); plans 4a warnings and grace, which refuse nothing
+- `internal/console/store.go` `Store.migrate`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-email-signin;identity=the console (cmd/console serve under console.service, user carlos-console);basis=adds the sessions.method column (default keymail, the backfill) and calls migrateEmailSignin; SQLite DDL on CONSOLE_DB; the existing site moves
+- `internal/console/templates/layout.html` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=PROPOSED-console-switcher-filter;basis=Account switcher adds a client-side filter box and a scrolling list; whole embedded template remains frozen as legacy UI input.;rev3=PROPOSED-email-signin;identity=the console (cmd/console serve under console.service, user carlos-console);basis=CSS only: email inputs styled as text inputs and sign-in form labels; whole embedded template remains frozen as legacy UI input;rev3=PROPOSED-console-brand-name;identity=the console (cmd/console serve under console.service, user carlos-console);basis=the tab title and header brand name the deployment ({{.Brand}}, CARLOS_CONSOLE_NAME); no new input.
+
+Seal: `72dc835c04caf5b2b49cc6ecbfd865bb3123b997ee932e8ab7c0df239935a26b` → `43e430a3b3edf9333bfe2c64f24ca9e4c04475dc45ae4983d4e8bcab6a9c0bc4`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-plans-4-notices-grace.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
+## Decision (hand-written, census-ruling-plans-4a-store)
+
+There are six new console store units. The scanner counts SQL as a root read, so each is a new unit, and a new unit is a decision. They have their own overlay, `internal/provision/testdata/plan14-root-reads-plans-4a-store.tsv`, chained just before this one (seal `539ae875…` → `72dc835c…`). Each is classed `legacy`/`accepted-legacy` as "console SQL on its own table, as its store siblings (J4)", the same disposition Plan 1 gave `Store.AccountPlan` and `Store.SetAccountPlan`.
+
+| unit | reads | what it does |
+|---|---|---|
+| `internal/console/plangrace_store.go` `Store.migratePlanGrace` | `file:Exec` | creates the console's own `plan_cap_state` table |
+| `Store.CapStates` | `file:Query` | reads an account's cap rows |
+| `Store.PutCapState` | `file:Exec` | upserts one row |
+| `Store.DeleteCapState` | `file:Exec` | deletes a row for a cap the plan no longer has |
+| `Store.RecordCapNotice` | `file:Exec` | sets notice_at on the account's over rows that have none |
+| `internal/console/mailcounts.go` `Store.AccountSends` | `file:QueryRowContext` | sums the account's sends for one UTC day from `mail_sender_counts` |
+
+None of them takes a path or a value a tenant controls beyond the account id the console already resolved, and nothing they read grants anything. Plan 4a only warns.
+
+Also reachable now, with no census site: the grace pass reads the account's monthly usage statement and the daily storage sweep from the bucket (`usage.GetStatement`, `accountStoreBytes`). Both are objects the console's own economics pass writes. The CLI gates (`apiPrincipalAccount`, `apiAccountAppSaying`) add a response header from the account's own rows.
diff --git a/docs/superpowers/notes/plans-4a-ledger.md b/docs/superpowers/notes/plans-4a-ledger.md
new file mode 100644
index 000000000..8e8f48be9
--- /dev/null
+++ b/docs/superpowers/notes/plans-4a-ledger.md
@@ -0,0 +1,21 @@
+# SDD ledger — plan: docs/superpowers/plans/2026-10-25-plans-4a-warnings-and-grace.md
+Pre-flight: T2 produces measureCaps/capMeasure, T3 consumes them (match); T1 produces CapStates/RecordCapNotice/capState/afterGraceDue, T3-T5 consume (match); T3 produces planNoticesOf/planNoticeText, T4/T5 consume (match). No conflicts.
+Task 1: complete (commits 113a2c4..82a5b0f, tests: go test ./internal/console/ -run 'CapLevels|EvaluateCap|AfterGraceDue|CapState|RecordCapNotice|ClaimSQL|StoreGate' → ok github.com/carlosframework/platform/internal/console (cached))
+Task 2: Ruling: a storage sweep that marks any of the account's stores unswept makes the storage cap unknown (error), not a smaller total — spec §5.5 counts from the sweep and an unswept store would understate usage — cost if wrong: storage warnings pause while a store's credentials are broken.
+Task 2: complete (commits 82a5b0f..a4d9d59, tests: go test ./internal/usage/ ./internal/console/ -run 'GetStatement|AccountSends|MeasureCaps' → ok github.com/carlosframework/platform/internal/console (cached))
+Task 3: Ruling: email subject and settings link name the account by sqid ([carlos] Account <sqid>: plan usage), the storenotify precedent — no product name in platform code (provider-neutral, no tenant names) — cost if wrong: one string change after the Luna pass.
+Task 3: note: TestClaimConsoleMutationInvariant failed once uncached on an unrelated subtest, passed on rerun; worker_StartPlanGracePass probe PASS.
+Task 3: complete (commits a4d9d59..4752fde, tests: go test ./internal/console/ -run 'GracePass|EveryRegisteredClaimWorker|ClaimRoutes' → ok github.com/carlosframework/platform/internal/console 1.743s)
+Task 4: Ruling: banner tests load the account home (/a/<sqid>/) — the plan's /a/<sqid>/apps is not a route; accountPage feeds every account page, so the home page proves the shared hook — cost if wrong: none.
+Task 4: complete (commits 4752fde..9477549, tests: go test ./internal/console/ -run Banner → ok github.com/carlosframework/platform/internal/console (cached))
+Task 5: complete (commits 9477549..74f4885, tests: sh -c 'go test ./internal/console/ -run CLIWarning && go test . -run PlanWarningTransport' → ok github.com/carlosframework/platform 0.016s)
+Task 6: Ruling: CLI warnings hook both gates — apiPrincipalAccount (wrapper) and apiAccountAppSaying — rather than renaming apiPrincipalAccountSaying (which would have been a removed+new census pair); the phase-1 move door, which calls the Saying form directly, carries no warning — cost if wrong: that one door prints no plan line.
+Task 6: Ruling: the six new store units are a hand-written census decision overlay (plans-4a-store, legacy/accepted-legacy as console SQL on its own table, J4, Plan 1's disposition); approval goes to Astra with the final review per the census recipe — cost if wrong: an escalation to Paul.
+Task 6: complete (commits 74f4885..802a3fe, tests: sh -c 'GOFLAGS=-buildvcs=false go test ./internal/provision/ -run 'Plan14RootReadCensus$|Plan9B8RecordWriteCensus$'' → ok github.com/carlosframework/platform/internal/provision (cached))
+Final: fixed (1) stale upsert erased notice — TestPutCapStateKeepsConcurrentNotice RED(mutation)→GREEN, suites green
+Final: fixed (2) notice not tied to the episode shown — TestRecordCapNoticeMatchesTheEpisodeShown RED(compile)→GREEN
+Final: fixed (3) error page could count as banner notice — TestBannerNoticeOnlyWhenRendered RED(compile)→GREEN
+Final: fixed (4) expired periods due/shown — TestExpiredPeriodIsNotDueOrShown RED(mutation)→GREEN
+Final: fixed (5) upload/stream clients bypassed warnings — TestUploadAndStreamClientsPrintWarnings RED(compile)→GREEN
+Final: Ruling: test fixture overRow now dates the first over at time.Now()-1h — page views and CLI record notice at the real clock, and notice before the first over no longer counts — cost if wrong: none (fixture only).
+Final: census — Astra approved every unit and envelope technically; the six plans-4a-store dispositions are a decision for Paul (census owner).
diff --git a/docs/superpowers/plans/2026-10-25-plans-4a-warnings-and-grace.md b/docs/superpowers/plans/2026-10-25-plans-4a-warnings-and-grace.md
new file mode 100644
index 000000000..a103b6836
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-25-plans-4a-warnings-and-grace.md
@@ -0,0 +1,324 @@
+# Plans 4a: Warnings, Grace and Notice Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Under a plan catalog, the console measures each account against its effective limits every hour, and warns owners at 80% (console banner, `carlos` CLI line, email). It keeps a grace clock per cap, records when an owner actually received notice, and sends a daily reminder while over. It never cuts anything off. After-grace stages are Plan 4b; they read this plan's state through one predicate.
+
+**Architecture:**
+- **Store and rules:** a new console table, `plan_cap_state`, holds one row per account per cap. A pure function, `evaluateCap`, turns (previous row, measurement, now) into the next row.
+- **Measuring:** an hourly claim worker, `StartPlanGracePass`, measures from what the console already records: running things, monthly usage statements, storage days and mail counts.
+- **Shown three ways:** the same rows feed the account-page banner, a CLI response header, and the owner emails.
+- **Notice:** recorded only by those three channels, and only for an owner.
+
+**Tech Stack:** Go; `internal/console`, `internal/usage`, the `carlos` CLI at the repo root (`auth.go`).
+
+**Spec:** `docs/superpowers/specs/2026-10-20-plans-caps-packs-design.md`:
+- §6 (warnings, grace, notice) is the whole of this plan.
+- Figures come from §5.2 (awake hours), §5.5 (storage), §5.6 (email) and §5.7 (bandwidth).
+- §12 step 3 ("watch a week of warnings with after-grace stages disabled") is why the after-grace stages are a separate plan.
+
+The plan builds on Plans 1, 2, 3a and 3b, all merged.
+
+## Scope split (Plan 4)
+
+Plan 4 in the plan list ("notices, grace, measured caps, the lapse lifecycle, throttling, the awake ceiling") is three subsystems, each shipping on its own:
+- **4a (this plan):** measure, warn, grace clock, notice, reminders. Nothing is refused or slowed.
+- **4b:** after-grace stages, gated on `afterGraceDue`:
+ - the email pause at 2x;
+ - the storage `Deny s3:PutObject`;
+ - the bandwidth and awake-hours throttle state in the limits record, plus edge throttling;
+ - closing WebSockets and the 15-minute continuous-awake ceiling;
+ - running things over the cap disabled, newest first.
+- **4c:** the lapse lifecycle (§9.2):
+ - disabled, then deleted 90 days later through the Trash, with reminders at 30, 7 and 1 days;
+ - paid-only features left over (custom domains, fleets, sidecars beyond the cap, always-on on a fleet the app has left);
+ - the account's choice of what to keep.
+
+Disk per running thing is not measured here. It needs the box quota mechanism (Plan 5).
+
+## Global Constraints
+
+- **No catalog, no change.**
+ - `StartPlanGracePass` returns at once when `cfg.PlanCatalog == nil`.
+ - No header, no banner, no row and no email.
+ - Every entry point checks `EffectiveLimits(acct)` and treats nil as "plans off".
+- **Nothing is refused, throttled, stopped or deleted by this plan.**
+- **Caps measured**, with their IDs. These are stable strings, stored and sent:
+ - `running_things` (count);
+ - `storage` (bytes, account);
+ - `email` (sends, UTC day);
+ - `bandwidth` (bytes, month);
+ - `awake_hours` (hours, month).
+- A cap whose effective limit is ≤ 0 is not offered and has no row. For example, `storage` on a plan without self-serve storage.
+- **Grace periods (§6):**
+ - `running_things` and `storage`: 7 days from first over.
+ - `email`: until the next UTC midnight.
+ - `bandwidth` and `awake_hours`: until the first instant of the next UTC month.
+- **Levels:**
+ - `ok`: under 80%.
+ - `warn`: `used*5 >= limit*4` and `used <= limit`.
+ - `over`: `used > limit`.
+ - `ceiling`: `used >= 2*limit`, for `email`, `bandwidth` and `awake_hours` only.
+- **Notice (§6, codex 1.4):**
+ - Only notice received **after the cap went over** counts.
+ - It is recorded only for an owner, and only by:
+ - an email that `deliver` accepted;
+ - an owner loading an account page that showed the banner;
+ - an owner's CLI request that declared it prints warnings.
+ - After-grace needs grace ended and notice at least 72 h old.
+- **Fail soft:** a measurement that can't be read leaves that cap's row unchanged and logs once per pass. It never clears a clock.
+- **Copy:** every banner, CLI and email string sits in `planNoticeCopy` (`internal/console/plancaps_copy.go`). Copy review is a Luna pass (gpt-5.6-luna via codex) against Paul's house rules, not a served deck (Paul, 2026-10-25). No em dashes. The CLI line is lower case.
+- **Census:**
+ - the new table goes in `claimSQLTables` (`store_gate.go:183`, `NonApp`);
+ - the new worker goes in `claim_workers.go`, the `cmd/console/main.go` `RunClaimWorker` call, `testdata/claim-routes.txt`, a claim fixture and a probe;
+ - the console envelope is re-pinned through `make census-card` and `make census-propose`.
+- **Tests:** touched packages only, with `-run`; CI runs the full suite. Tests use `planNow` and inject `now`.
+
+## Review Focus
+
+1. **A clock must not reset by itself.** Re-evaluating, restarting the console, or failing to read a measurement must keep `first_over`, `grace_ends` and `notice_at`. Only falling under the limit or a new period clears them. Pinned in Task 1 (`TestEvaluateCapIsStable`) and Task 3 (`TestGracePassSkipsUnreadableMeasurements`).
+2. **A new period starts clean.** A new UTC day for `email`, or a new month for `bandwidth` and `awake_hours`, clears the row. Only those caps; counts and sizes never roll. Pinned in Task 1 (`TestEvaluateCapNewPeriodClears`).
+3. **Notice before the cap went over does not count, and neither does a member's notice.** Pinned in Task 1 (`TestRecordCapNoticeOnlyWhenOver`) and Task 4 (`TestBannerRecordsNoticeForOwnersOnly`).
+4. **One reminder per day, not one per pass**, and no email at all when mail isn't configured. Pinned in Task 3 (`TestGracePassRemindsOncePerDay`, `TestGracePassWithoutMailRecordsNoNotice`).
+5. **An old CLI that never prints the warning earns no notice.** Pinned in Task 5 (`TestCLIWarningNoticeNeedsTheDeclaration`).
+
+---
+
+### Task 1: State table and grace rules
+
+**Files:**
+- Create: `internal/console/plangrace.go` (types, `evaluateCap`, `afterGraceDue`).
+- Create: `internal/console/plangrace_store.go` (table and Store methods).
+- Modify: `internal/console/store.go` (call `migratePlanGrace()` beside the other `migrateX()` calls, ~:530-548).
+- Modify: `internal/console/store_gate.go:183` (`claimSQLTables` gets `plan_cap_state`, `NonApp: "per-account plan cap state"`).
+- Test: `internal/console/plangrace_test.go`.
+
+**Interfaces:**
+- Produces:
+ ```go
+ type capID string // "running_things", "storage", "email", "bandwidth", "awake_hours"
+ type capLevel string // "ok", "warn", "over", "ceiling"
+ type capState struct {
+ AccountID int64; Cap capID; Period string // "" counts/sizes, "2006-01-02" email, "2006-01" monthly
+ Level capLevel; Used, Limit int64
+ FirstOver, GraceEnds, WarnedAt, RemindedAt, NoticeAt time.Time // zero = unset
+ UpdatedAt time.Time
+ }
+ func capPeriod(c capID, now time.Time) string
+ func evaluateCap(prev *capState, c capID, used, limit int64, now time.Time) capState
+ func afterGraceDue(st capState, now time.Time) bool
+ func (st *Store) CapStates(accountID int64) ([]capState, error)
+ func (st *Store) PutCapState(s capState) error // upsert on (account_id, cap)
+ func (st *Store) DeleteCapState(accountID int64, c capID) error
+ func (st *Store) RecordCapNotice(accountID int64, caps []capID, at time.Time) error // sets notice_at only where level in (over, ceiling) and notice_at unset
+ ```
+ `evaluateCap` rules:
+ - `prev` nil, or `prev.Period != capPeriod(c, now)`: start fresh.
+ - Level comes from the thresholds in Global Constraints.
+ - `FirstOver` is set on the first `over`/`ceiling` and kept while it stays over.
+ - `GraceEnds` comes from `FirstOver` (7 days; the next UTC midnight; the next UTC month).
+ - Dropping to `warn` or `ok` clears `FirstOver`, `GraceEnds` and `NoticeAt`.
+ - `WarnedAt` and `RemindedAt` carry over unchanged; the pass sets them.
+- `afterGraceDue`: level `over`/`ceiling`, `!now.Before(GraceEnds)`, `NoticeAt` set and `!NoticeAt.After(now.Add(-72*time.Hour))`.
+
+- [ ] **Step 1: Write the failing tests**
+ ```go
+ func TestCapLevels(t *testing.T) // limit 100: used 79 ok, 80 warn, 100 warn, 101 over; email used 200 ceiling; storage used 200 over (no ceiling level)
+ func TestEvaluateCapGraceEnds(t *testing.T) // planNow: running_things +7d; email next UTC midnight; bandwidth 1st of next UTC month 00:00
+ func TestEvaluateCapKeepsFirstOverWhileOver(t *testing.T)
+ func TestEvaluateCapUnderClearsClocks(t *testing.T) // over then 90%: FirstOver, GraceEnds, NoticeAt zero
+ func TestEvaluateCapNewPeriodClears(t *testing.T) // email row from yesterday, bandwidth row from last month: fresh; running_things row from last month: kept
+ func TestEvaluateCapIsStable(t *testing.T) // same prev, used, limit at a later now in the same period: FirstOver, GraceEnds, NoticeAt unchanged
+ func TestAfterGraceDue(t *testing.T) // grace not ended: false; ended, no notice: false; notice 71h old: false; 72h: true
+ func TestCapStateRoundTrip(t *testing.T) // PutCapState then CapStates returns it; times survive at second precision
+ func TestRecordCapNoticeOnlyWhenOver(t *testing.T) // warn row: unchanged; over row: notice set; second call: first time kept
+ ```
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'CapLevels|EvaluateCap|AfterGraceDue|CapState|RecordCapNotice'`. Expected: FAIL (undefined).
+- [ ] **Step 3: Implement** the table `plan_cap_state(account_id INTEGER, cap TEXT, period TEXT, level TEXT, used INTEGER, cap_limit INTEGER, first_over INTEGER, grace_ends INTEGER, warned_at INTEGER, reminded_at INTEGER, notice_at INTEGER, updated_at INTEGER, PRIMARY KEY(account_id, cap))`, with times as unix seconds and 0 for unset. Then implement the functions above.
+- [ ] **Step 4: Run** the tests again. Expected: PASS. Also run `go test ./internal/console/ -run 'ClaimSQL|StoreGate'`. Expected: PASS.
+- [ ] **Step 5: Commit** `console: plan cap state and grace rules (plans 4a)`.
+
+### Task 2: Measurements
+
+**Files:**
+- Create: `internal/console/planmeasure.go`.
+- Modify: `internal/usage/statement.go` (add `GetStatement`).
+- Modify: `internal/console/mailcounts.go` (add `AccountSends`).
+- Test: `internal/console/planmeasure_test.go`, `internal/usage/statement_test.go`.
+
+**Interfaces:**
+- Consumes: `runningThings(ctx, acct)` (`plancaps.go:50`), `usage.StatementKey`, `usage.StorageDayKey`, `usage.MeterInstanceHours`, `usage.MeterEgressGB`.
+- Produces:
+ ```go
+ // usage
+ func GetStatement(ctx context.Context, s release.Store, acct, month string) (*Statement, error) // os.ErrNotExist passes through
+ // console
+ func (st *Store) AccountSends(ctx context.Context, account, day string) (int64, error) // SUM(sends) over mail_sender_counts for the account and UTC day
+ type capMeasure struct{ Used, Limit int64 }
+ func (s *Server) measureCaps(ctx context.Context, acct *Account, l *plans.Limits, now time.Time) (map[capID]capMeasure, map[capID]error)
+ ```
+ `measureCaps` measures only caps whose limit is > 0. The sources:
+ - `running_things`: `runningThings`.
+ - `awake_hours`: `floor(Meters["instance_hours"])` of `capPeriod(awake_hours, now)`'s statement.
+ - `bandwidth`: `Meters["egress_gb"] * 1e9`, rounded down.
+ - `storage`: the sum of `StoreBytes` over `Apps` keys with prefix `acct.Sqid+"/"`, from the newest storage day file found looking back up to 3 days from `now` (the `storeSize` precedent, `apistore.go:297`).
+ - `email`: `AccountSends(acct.Sqid, now.UTC().Format("2006-01-02"))`.
+
+ A missing statement for the current month means `awake_hours` and `bandwidth` are measured as 0: nothing used yet is a true zero. No storage day file in 3 days is an error for `storage`. Any other read error goes in the error map for that cap only.
+
+- [ ] **Step 1: Write the failing tests**
+ ```go
+ func TestGetStatementRoundTrip(t *testing.T) // UpsertStatement then GetStatement equal; missing month: errors.Is(err, os.ErrNotExist)
+ func TestAccountSendsSumsSendersAndApps(t *testing.T) // two apps, two senders, two days: today's sum only
+ func TestMeasureCapsFromRecordedUsage(t *testing.T) // statement instance_hours 12.7 -> 12; egress_gb 1.5 -> 1_500_000_000; storage day with acct/a 10, acct/b 5, other/x 99 -> 15; 2 sends today; running things = fixture count
+ func TestMeasureCapsSkipsZeroLimits(t *testing.T) // StorageBytes 0: no storage key in either map
+ func TestMeasureCapsNoStatementIsZero(t *testing.T)
+ func TestMeasureCapsStorageDayMissingIsAnError(t *testing.T)
+ ```
+- [ ] **Step 2: Run** `go test ./internal/usage/ ./internal/console/ -run 'GetStatement|AccountSends|MeasureCaps'`. Expected: FAIL.
+- [ ] **Step 3: Implement** the three functions.
+- [ ] **Step 4: Run** again. Expected: PASS.
+- [ ] **Step 5: Commit** `console: measure plan caps from recorded usage (plans 4a)`.
+
+### Task 3: The grace pass and owner email
+
+**Files:**
+- Create: `internal/console/plangracepass.go`.
+- Modify: `internal/console/plancaps_copy.go` (`planNoticeCopy` and `planNoticeText`, below).
+- Modify: `internal/console/claim_workers.go:17`, `cmd/console/main.go` (~:605, `go srv.RunClaimWorker(context.Background(), "StartPlanGracePass")`), `internal/console/testdata/claim-routes.txt` (`worker StartPlanGracePass`), and the claim fixture and probe beside `StartPlanLimitsPass`'s.
+- Test: `internal/console/plangracepass_test.go`.
+
+**Interfaces:**
+- Consumes: Task 1 and Task 2; `s.deliver(ctx, to, subject, body, keymailShare)` (`delivery.go:41`); `s.store.Members(accountID)`, filtering on `Role == RoleOwner`.
+- Produces:
+ ```go
+ func (s *Server) StartPlanGracePass(ctx context.Context) // nil catalog: return; else hourly ticker calling planGracePass(ctx, time.Now())
+ func (s *Server) planGracePass(ctx context.Context, now time.Time)
+ type planNotice struct{ Cap capID; Level capLevel; Used, Limit int64; GraceEnds time.Time }
+ func planNoticesOf(states []capState) []planNotice // level warn, over or ceiling, in capID order above
+ func planNoticeText(n planNotice, surface string) string // surface "banner", "cli", "email"; looks up planNoticeCopy
+ ```
+ For each account from `s.store.Accounts()` whose `EffectiveLimits` is not nil:
+ - `measureCaps`, then `evaluateCap` per measured cap, then `PutCapState`.
+ - A cap with a measurement error is left untouched.
+ - A row for a cap no longer offered (limit ≤ 0) is deleted.
+
+ Email goes to each owner, at most one message per account per pass, listing every cap that triggers. A cap triggers when:
+ - it first reaches `warn` in this period (`WarnedAt` zero);
+ - it first reaches `over`/`ceiling` (`RemindedAt` zero, or set before `FirstOver`);
+ - it is `over`/`ceiling` and `RemindedAt` is at least 24 h before `now`.
+
+ When at least one owner's `deliver` returns nil:
+ - set `WarnedAt` and `RemindedAt` to `now` on the triggering caps;
+ - call `RecordCapNotice` for those that are over.
+
+ When every owner's delivery fails, nothing is set, and the next pass tries again.
+- `planNoticeCopy` keys, drafts until the Luna pass:
+ - `banner.warn`, `banner.over`;
+ - `cli.warn`, `cli.over`;
+ - `email.subject`, `email.warn`, `email.over`, `email.ways_out`.
+
+ Each over line names the cap, used and limit in human units (GB, hours, sends, things) and the grace end date. `email.ways_out` lists the three ways out: buy a pack, upgrade, or clean up (§6).
+
+- [ ] **Step 1: Write the failing tests** (fixture: `newConsoleFixture`, `examplePlanCatalog`, a stub `sendFederated` or mailer recording sends; `planNow`)
+ ```go
+ func TestGracePassOffWithoutACatalog(t *testing.T) // no rows, no sends
+ func TestGracePassWarnsOnceAt80Percent(t *testing.T) // free account at 80% running things: one email to the owner, row warn with WarnedAt; second pass: no email
+ func TestGracePassOverStartsGraceAndRecordsNotice(t *testing.T) // over: GraceEnds = planNow+7d; delivered: NoticeAt = planNow
+ func TestGracePassRemindsOncePerDay(t *testing.T) // passes at +1h: no email; +24h: one reminder
+ func TestGracePassWithoutMailRecordsNoNotice(t *testing.T) // every deliver errors: NoticeAt zero, RemindedAt zero
+ func TestGracePassSkipsUnreadableMeasurements(t *testing.T) // over row exists; storage day files removed: row unchanged
+ func TestGracePassMembersGetNoEmail(t *testing.T) // member (not owner) receives nothing
+ func TestEveryRegisteredClaimWorkerIsStarted(t *testing.T) // existing test, still passing with the new worker
+ ```
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'GracePass|EveryRegisteredClaimWorker|ClaimRoutes'`. Expected: FAIL.
+- [ ] **Step 3: Implement** the pass, the copy map, the worker registration and the claim wiring.
+- [ ] **Step 4: Run** again. Expected: PASS.
+- [ ] **Step 5: Commit** `console: hourly plan grace pass with owner warnings (plans 4a)`.
+
+### Task 4: Console banner
+
+**Files:**
+- Modify: `internal/console/server.go`: add the `page` struct field `PlanNotices []string` (~:1810), and fill it in `accountPage` (~:3327).
+- Modify: `internal/console/templates/layout.html` (a `.banner` list above `<main>` content, ~:593).
+- Test: `internal/console/plangrace_view_test.go`.
+
+**Interfaces:**
+- Consumes: `CapStates`, `planNoticesOf`, `planNoticeText(n, "banner")`, `RecordCapNotice`.
+- Produces: `func (s *Server) planBanner(acct *Account, role string, now time.Time) []string`.
+ - It is nil when plans are off or there are no notices.
+ - When `role == RoleOwner` and a notice is `over`/`ceiling`, it records notice for those caps.
+ - A store error is logged and yields no banner; the page still renders.
+
+- [ ] **Step 1: Write the failing tests**
+ ```go
+ func TestBannerShowsPlanNotices(t *testing.T) // over row: GET /a/<sqid>/apps body contains the banner.over text
+ func TestBannerRecordsNoticeForOwnersOnly(t *testing.T) // member view: NoticeAt zero; owner view: NoticeAt set
+ func TestBannerWithoutACatalogUnchanged(t *testing.T) // no catalog: no banner markup
+ ```
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'Banner'`. Expected: FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** again. Expected: PASS.
+- [ ] **Step 5: Commit** `console: plan notice banner on account pages (plans 4a)`.
+
+### Task 5: CLI warning line
+
+**Files:**
+- Modify: `internal/console/apicli.go`, `apiPrincipalAccountSaying` (:209). After a successful resolve, call `s.writePlanWarnings(w, r, p, acct)`.
+- Modify: `auth.go:397` (`newConsoleClient`): wrap the transport.
+- Create: `planwarnings.go` at the repo root (the CLI transport).
+- Test: `internal/console/plangrace_cli_test.go`, `planwarnings_test.go`.
+
+**Interfaces:**
+- Produces:
+ ```go
+ // console
+ const planWarningsAccept = "X-Carlos-Plan-Warnings" // request: "1" means this CLI prints them
+ const planWarningHeader = "X-Carlos-Plan-Warning" // response: one value per notice, planNoticeText(n, "cli")
+ func (s *Server) writePlanWarnings(w http.ResponseWriter, r *http.Request, p Principal, acct *Account)
+ // CLI
+ type planWarningTransport struct{ base http.RoundTripper; out io.Writer; seen map[string]bool; mu sync.Mutex }
+ func (t *planWarningTransport) RoundTrip(req *http.Request) (*http.Response, error) // sets planWarningsAccept: 1; prints each new response value as "warning: <text>\n" to out (os.Stderr), once per process
+ ```
+ `writePlanWarnings` writes nothing unless the request carries `planWarningsAccept: 1`. It records notice only when `p.Kind == PrincipalUser` and `p.Address` is an owner of `acct` (`Members`), and only for `over`/`ceiling` caps.
+- [ ] **Step 1: Write the failing tests**
+ ```go
+ func TestCLIWarningHeaderUnderAPlan(t *testing.T) // over row + accept header: response carries the cli.over text
+ func TestCLIWarningNoticeNeedsTheDeclaration(t *testing.T) // owner request without the accept header: no header, NoticeAt zero; with it: set
+ func TestCLIWarningServiceEarnsNoNotice(t *testing.T) // service principal with accept header: header sent, NoticeAt zero
+ func TestCLIWarningWithoutACatalogUnchanged(t *testing.T)
+ func TestPlanWarningTransportPrintsOnce(t *testing.T) // two responses with the same value: printed once; request carries the accept header
+ ```
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'CLIWarning'` and `go test . -run 'PlanWarningTransport'`. Expected: FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** again. Expected: PASS.
+- [ ] **Step 5: Commit** `console, cli: plan warning line on CLI commands (plans 4a)`.
+
+### Task 6: Copy, docs, census and gates
+
+- [ ] Luna copy pass (Paul, 2026-10-25). Commit a brief with the house rules (no em dashes; a full stop and a new sentence; lower case for the CLI line; human text only) and every `planNoticeCopy` string with an example rendering. Apply Luna's changes, and show Paul only the strings it flags.
+- [ ] Add a "Warnings and grace" section to `docs/site/plans.md`, covering:
+ - the five caps, the 80% warning and the grace periods;
+ - what counts as notice;
+ - that nothing is cut off yet.
+- [ ] Census:
+ - Run `make census-card`, then `make census-propose NAME=plans-4-notices-grace CLAIMS=<file>`.
+ - Add a record-write census layer only if `TestPlan9B8RecordWriteCensus` names a site. This plan writes no bucket record.
+ - Astra approves the card (the cross-model reviewer, per the census recipe), and the verdict is recorded on #280. Only escalations and decisions go to Paul.
+- [ ] Merge main, push, wait for green CI, then Astra's whole-branch review.
+
+## Done when
+
+Every task's tests pass and Review Focus 1–5 are pinned. The census card is approved by Astra. CI is green after merging current main, and Astra's whole-branch review has no open Critical or Important finding.
+
+## Astra review (2026-10-25)
+
+Findings in `docs/superpowers/specs/CODEX-FINDINGS-PLANS-4A-CODE.md`: five Important, all fixed in one pass, each test-first.
+
+1. **The pass's upsert erased concurrent notice.** `PutCapState` now keeps notice already recorded for the same episode (same period and same first over). Covered by `TestPutCapStateKeepsConcurrentNotice`.
+2. **Notice was not tied to the episode shown.** `RecordCapNotice` now takes the rows as they were shown. It updates only the matching episode, and never with a time before the first over. Covered by `TestRecordCapNoticeMatchesTheEpisodeShown`.
+3. **An error page could count as notice.** `planBanner` records nothing now. `render` records notice only after it has written a page carrying the banner. Covered by `TestBannerNoticeOnlyWhenRendered`.
+4. **Expired periods stayed due.** `afterGraceDue` requires the current period, and `planNoticesOf(states, now)` hides rows from an ended day or month. Covered by `TestExpiredPeriodIsNotDueOrShown`.
+5. **Upload and stream clients skipped warnings.** One `planWarningTransport` per console client serves the JSON, upload and stream requests. Covered by `TestUploadAndStreamClientsPrintWarnings`.
+
+Census: Astra approved every unit and envelope technically. The six `plans-4a-store` dispositions are still a decision for the census owner.
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-PLANS-4A-CODE.md b/docs/superpowers/specs/CODEX-FINDINGS-PLANS-4A-CODE.md
new file mode 100644
index 000000000..a5092e5a8
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-FINDINGS-PLANS-4A-CODE.md
@@ -0,0 +1,53 @@
+Reviewed `8fdccd30d76124f7245d15a7604ec9d240e6755f` against `606afcb9c2ab7749ba7b5d54f5d93a54018f8bcd`. Five **Important** findings; no Critical findings.
+
+1. **Important — the hourly pass can erase recorded notice.**
+ [plangrace_store.go:82](/home/paulca/.cache/tmp/claude-1001/plans-4-notices-grace/internal/console/plangrace_store.go:82) unconditionally replaces `notice_at`. If the pass reads a row, an owner’s page or CLI request records notice, and the pass then upserts its snapshot, notice returns to zero. The email-marking upsert has the same problem. This violates Review Focus 1 without any usage or period change. Preserve concurrent notice within the same over-cap episode, using an atomic update or transaction.
+
+2. **Important — notice is not tied to the episode actually displayed.**
+ [plangrace_store.go:108](/home/paulca/.cache/tmp/claude-1001/plans-4-notices-grace/internal/console/plangrace_store.go:108) checks only account, cap, level and an empty notice timestamp. Across midnight, a request can read yesterday’s over-email row, the pass can replace it with today’s newly over row, and the request can credit yesterday’s warning to today’s episode. The supplied timestamp can even precede the new `first_over`. Match the observed period and episode when recording notice, and reject timestamps before `first_over`.
+
+3. **Important — an error page can count as banner notice.**
+ [plangracepass.go:242](/home/paulca/.cache/tmp/claude-1001/plans-4-notices-grace/internal/console/plangracepass.go:242) records notice while constructing page data. On the account home, this happens before `AppsIn` and `Assemble`; either can fail, causing [server.go:3246](/home/paulca/.cache/tmp/claude-1001/plans-4-notices-grace/internal/console/server.go:3246) to render a separate error page without the banner. An owner who never received the warning therefore starts the notice clock. Record notice only on the rendering path that actually serves the banner.
+
+4. **Important — expired periods remain eligible for `afterGraceDue`.**
+ [plangrace.go:122](/home/paulca/.cache/tmp/claude-1001/plans-4-notices-grace/internal/console/plangrace.go:122) does not compare `st.Period` with the current period. An October bandwidth row with notice received on October 25 becomes eligible on November 1, although November must start clean. This persists until successful reevaluation, and measurement failures deliberately retain the old row. Since Plan 4b consumes this predicate, it must reject expired daily/monthly periods. Warning readers also currently display those expired rows.
+
+5. **Important — upload and streaming clients bypass warnings.**
+ [auth.go:406](/home/paulca/.cache/tmp/claude-1001/plans-4-notices-grace/auth.go:406) installs the transport only on the JSON client. `doMultipartHeaders` and `doStream` construct separate clients at lines 533 and 575. A `carlos ship` with explicit account and app flags can make only the multipart request, so it neither requests nor prints the account warning. Share the warning transport with these clients while preserving their existing streaming deadlines and redirect policy.
+
+The SQL interleavings in findings 1–2 were reproduced using an in-memory SQLite database. Targeted Go tests could not start: the read-only sandbox denied creation of Go’s build directory.
+
+The other Review Focus checks look correct in sequential execution: evaluation preserves clocks within a period, clears them on recovery or rollover, and never rolls counts or sizes; members and undeclared old CLI requests earn no notice; successful reminders are spaced by 24 hours; unavailable delivery does not record email notice. Measurements use decimal GB, floor awake hours, treat missing statements as zero, and reject unswept storage. Owner filtering and account-scoped email data are intact. Plans-off guards suppress rows and warning output. The hourly reads are console-side; the pass adds no per-box polling, though it also lists instance keys for running-things counts.
+
+Census verdicts below answer the root-read safety question separately from these correctness findings.
+
+| Unit | Verdict and basis |
+|---|---|
+| [cmd/console/main.go:606](/home/paulca/.cache/tmp/claude-1001/plans-4-notices-grace/cmd/console/main.go:606), `serve` | **Approve.** Adds the registered worker; existing data paths and service identity remain unchanged. |
+| [store.go:552](/home/paulca/.cache/tmp/claude-1001/plans-4-notices-grace/internal/console/store.go:552), `Store.migrate` | **Approve.** Calls fixed-schema DDL on the existing console database. |
+| [layout.html:594](/home/paulca/.cache/tmp/claude-1001/plans-4-notices-grace/internal/console/templates/layout.html:594), `external` | **Approve.** Renders escaped strings through the embedded template; no new path or execution input. |
+| [plangrace_store.go:9](/home/paulca/.cache/tmp/claude-1001/plans-4-notices-grace/internal/console/plangrace_store.go:9), `Store.migratePlanGrace` | **Approve technically.** Literal DDL for the console’s own table. |
+| [plangrace_store.go:43](/home/paulca/.cache/tmp/claude-1001/plans-4-notices-grace/internal/console/plangrace_store.go:43), `Store.CapStates` | **Approve technically.** Parameterized account-scoped query. |
+| [plangrace_store.go:75](/home/paulca/.cache/tmp/claude-1001/plans-4-notices-grace/internal/console/plangrace_store.go:75), `Store.PutCapState` | **Approve technically.** Parameterized state write; no new privileged input path. |
+| [plangrace_store.go:90](/home/paulca/.cache/tmp/claude-1001/plans-4-notices-grace/internal/console/plangrace_store.go:90), `Store.DeleteCapState` | **Approve technically.** Parameterized deletion scoped to account and cap. |
+| [plangrace_store.go:98](/home/paulca/.cache/tmp/claude-1001/plans-4-notices-grace/internal/console/plangrace_store.go:98), `Store.RecordCapNotice` | **Approve technically.** Dynamic SQL contains placeholder punctuation only; values remain bound parameters. |
+| [mailcounts.go:325](/home/paulca/.cache/tmp/claude-1001/plans-4-notices-grace/internal/console/mailcounts.go:325), `Store.AccountSends` | **Approve technically.** Parameterized account/day aggregate over existing console data. |
+
+The six new `plans-4a-store` dispositions remain census-owner decisions under the repository policy; technical approval does not substitute for that classification ruling.
+
+| Re-pinned envelope | Verdict |
+|---|---|
+| `.` | **Approve.** Transport wrapper adds header handling and stderr output; no privileged reader added. |
+| `cmd/console` | **Approve.** Worker startup preserves existing authority boundaries. |
+| `internal/console` | **Approve.** Fixed-table SQL, authenticated warning gates, owner-only delivery, and usage reads keyed by resolved account and server-generated dates; no root input boundary weakened. |
+| `internal/console/templates` | **Approve.** Embedded, escaped banner rendering. |
+| `internal/usage` | **Approve.** Statement read uses the existing store and key shape; the new caller supplies resolved account and calendar month. |
+
+Independently verified all nine unit digests, five envelope fingerprints, legacy fingerprints, and both overlay seals:
+
+- `plans-4a-store`: `539ae875…` → `72dc835c…`
+- `plans-4-notices-grace`: `72dc835c…` → `ed240f74…`
+
+HEAD and the working tree remain unchanged. Copy wording was not reviewed.
+
+**Verdict: changes required.**
\ No newline at end of file
diff --git a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-PLANS-4A-CODE.md b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-PLANS-4A-CODE.md
new file mode 100644
index 000000000..fe04b59a1
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-PLANS-4A-CODE.md
@@ -0,0 +1,50 @@
+# Whole-branch code review brief: Plans 4a (warnings, grace and notice)
+
+You are a senior Go reviewer on the carlos platform, and the census's
+cross-model reviewer for this branch. Review branch `plans-4-notices-grace`,
+range `113a2c4c..HEAD` excluding the merges of main (`git diff 606afcb9c2ab7749ba7b5d54f5d93a54018f8bcd..HEAD`
+shows the branch's own change against the merge base). Read-only: do not
+modify the working tree, index, HEAD or branches. You may run `go test`
+with GOFLAGS=-buildvcs=false, targeted with -run.
+
+Requirements: the spec docs/superpowers/specs/2026-10-20-plans-caps-packs-design.md
+§6 (warnings, grace, notice; section 3 decisions are not to be argued
+with); the plan docs/superpowers/plans/2026-10-25-plans-4a-warnings-and-grace.md,
+including its Global Constraints and Review Focus; the executor's
+`Ruling:` lines in docs/superpowers/notes/plans-4a-ledger.md. Plan 4a only
+warns: after-grace stages are Plan 4b, which reads afterGraceDue.
+
+Grade by effect. Check each Review Focus line deliberately:
+1. a clock (first_over, grace_ends, notice_at) never resets by itself;
+2. a new period (UTC day for email, UTC month for bandwidth and awake
+ hours) starts clean, and counts and sizes never roll;
+3. notice before the cap went over, or a member's notice, never counts;
+4. one reminder a day, not one per pass; no email when mail is not
+ configured, and no notice then;
+5. an old CLI that never prints the warning earns no notice.
+
+Also look hard at:
+- plans off changes nothing: no rows, no header, no banner, no mail;
+- measurement correctness: units (GB = 1e9), unswept stores, a missing
+ statement, the storage lookback;
+- concurrency between the hourly pass and page views and CLI requests
+ recording notice;
+- email content: owner addresses only, no other account's data;
+- the CLI transport: the request header is a promise, so is every
+ response warning printed; does it change any other request behaviour
+ (redirects, streaming uploads, timeouts)?
+- cost: the pass reads one statement and up to 3 storage day files per
+ account per hour. Is that acceptable against "no new per-box polling"?
+ It is console-side, not per box.
+
+Census: answer the card's review question for every unit and envelope in
+docs/superpowers/notes/census-proposal-plans-4-notices-grace.md, including
+the hand-written decision overlay plans-4a-store. Does any root read now
+open, run, query or follow a path or input a tenant, app or box agent can
+create, write or name, or weaken a check the basis relies on? Give
+approve or escalate per unit, and check the overlay seals and fingerprints.
+
+Answer: findings graded Critical / Important / Minor, each with file:line
+and a concrete failure scenario; then the census verdicts; then a
+verdict: accept, accept with fixes, or changes required. Do not review
+the wording (Luna-approved copy in plancaps_copy.go).
diff --git a/docs/superpowers/specs/LUNA-COPY-BRIEF-PLANS-4A.md b/docs/superpowers/specs/LUNA-COPY-BRIEF-PLANS-4A.md
new file mode 100644
index 000000000..08c4733ef
--- /dev/null
+++ b/docs/superpowers/specs/LUNA-COPY-BRIEF-PLANS-4A.md
@@ -0,0 +1,45 @@
+# Copy pass brief: plan warnings (plans 4a)
+
+You are reviewing user-facing strings for a hosting console (the carlos platform). Paul, the owner, delegated this review to you instead of reading every string himself. Apply his house rules and return improved strings.
+
+## House rules
+
+- No em dashes or en dashes used as dashes. Where you would use one, end the sentence with a full stop and start a new one.
+- Plain words, short sentences, no jargon, no marketing tone, no exclamation marks.
+- CLI strings (keys starting `cli.`) are entirely lower case, with no full stop at the very end. Banner and email strings use normal sentence case.
+- Keep every `%s` and `%d` placeholder, in the same order and count. `%%` is a literal percent sign.
+- Do not name the product (no "Carloku"); the platform is generic. `[carlos]` in the email subject is the platform's mail tag and stays.
+- Facts that must stay true: nothing is cut off or slowed by these notices; when a cap is over there is a grace period, which ends on the date shown; the three ways out are buying a pack, moving to a bigger plan, or cleaning up; 80% of a limit triggers the first warning.
+
+## How the strings combine
+
+`usage.*` fills the first `%s` of banner/cli/email lines. Over lines get the grace end date (for example `2 November 2026`) as the second `%s`. An email is `email.intro`, a blank line, one `email.warn` or `email.over` line per cap, a blank line, then `email.ways_out` with the settings link.
+
+Example renderings (current text):
+
+- banner, over: This account is over its plan: 2 GB of 1 GB object storage. Nothing changes until 2 November 2026. To stay within it, buy a pack, move to a bigger plan, or clean up.
+- cli, warn: warning: this account has used 4 of 5 apps and instances
+- email, over line: - 1200 of 1000 emails today, over the limit. Nothing changes until 26 October 2026.
+
+## Strings
+
+| key | current |
+|---|---|
+| `usage.running_things` | %d of %d apps and instances |
+| `usage.storage` | %s of %s object storage |
+| `usage.email` | %d of %d emails today |
+| `usage.bandwidth` | %s of %s bandwidth this month |
+| `usage.awake_hours` | %d of %d awake hours this month |
+| `banner.warn` | This account has used %s. If it goes over, nothing changes for a grace period. |
+| `banner.over` | This account is over its plan: %s. Nothing changes until %s. To stay within it, buy a pack, move to a bigger plan, or clean up. |
+| `cli.warn` | this account has used %s |
+| `cli.over` | this account is over its plan: %s. nothing changes until %s. buy a pack, move to a bigger plan, or clean up |
+| `email.subject` | [carlos] Account %s: plan usage |
+| `email.intro` | Account %s is near or over what its plan includes: |
+| `email.warn` | - %s. |
+| `email.over` | - %s, over the limit. Nothing changes until %s. |
+| `email.ways_out` | To stay within the plan, buy a pack, move to a bigger plan, or clean up.\n\nAccount settings:\n%s |
+
+## Answer
+
+Return a Markdown table with columns `key`, `new`, `why` for every key, `new` equal to `current` where no change is needed. Then a section `Flags` listing anything you think Paul must decide (facts you could not verify, ambiguous placeholders). Do not edit any files.
diff --git a/docs/superpowers/specs/LUNA-COPY-RESULT-PLANS-4A.md b/docs/superpowers/specs/LUNA-COPY-RESULT-PLANS-4A.md
new file mode 100644
index 000000000..004014c78
--- /dev/null
+++ b/docs/superpowers/specs/LUNA-COPY-RESULT-PLANS-4A.md
@@ -0,0 +1,21 @@
+| key | new | why |
+|---|---|---|
+| `usage.running_things` | `%d of %d apps and instances` | No change needed |
+| `usage.storage` | `%s of %s object storage` | No change needed |
+| `usage.email` | `%d of %d emails today` | No change needed |
+| `usage.bandwidth` | `%s of %s bandwidth this month` | No change needed |
+| `usage.awake_hours` | `%d of %d awake hours this month` | No change needed |
+| `banner.warn` | `This account has used %s. If it goes over, nothing changes during the grace period.` | More direct wording |
+| `banner.over` | `This account is over its plan: %s. Nothing changes until %s. To stay within the plan, buy a pack, move to a bigger plan, or clean up.` | Names the plan clearly |
+| `cli.warn` | `this account has used %s` | No change needed |
+| `cli.over` | `this account is over its plan: %s. nothing changes until %s. buy a pack, move to a bigger plan, or clean up` | No change needed |
+| `email.subject` | `[carlos] Account %s: plan usage` | No change needed |
+| `email.intro` | `Account %s is near or over its plan limits:` | Makes the meaning clearer |
+| `email.warn` | `- %s.` | No change needed |
+| `email.over` | `- %s, over the limit. Nothing changes until %s.` | No change needed |
+| `email.ways_out` | `To stay within the plan, buy a pack, move to a bigger plan, or clean up.\n\nAccount settings:\n%s` | No change needed |
+
+## Flags
+
+- No unresolved placeholder issues.
+- The 80% warning threshold is a product rule, not something these strings need to state.
\ No newline at end of file
diff --git a/internal/console/apicli.go b/internal/console/apicli.go
index f292ef9a8..c2e3b660e 100644
--- a/internal/console/apicli.go
+++ b/internal/console/apicli.go
@@ -86,6 +86,7 @@ func (s *Server) apiAccountAppSaying(w http.ResponseWriter, r *http.Request, has
http.NotFound(w, r)
return "", nil, "", false
}
+ s.writePlanWarnings(w, r, p, acct) // plans 4a, as apiPrincipalAccount
return auditActor(p, acct), acct, app, true
}
@@ -181,7 +182,13 @@ func (s *Server) serviceBinding(p Principal) (*Account, bool) {
// settle an ambiguity can never itself be ambiguous. It never widens access
// — a non-member's probe meets the same 404 either way.
func (s *Server) apiPrincipalAccount(w http.ResponseWriter, r *http.Request) (Principal, *Account, bool) {
- return s.apiPrincipalAccountSaying(w, r, mainGateCopy())
+ p, acct, ok := s.apiPrincipalAccountSaying(w, r, mainGateCopy())
+ if ok {
+ // Every reply the main gate admits carries the account's plan
+ // warnings (plans 4a), for a CLI that prints them.
+ s.writePlanWarnings(w, r, p, acct)
+ }
+ return p, acct, ok
}
// gateCopy is what the shared CLI gates say when they refuse in a sentence
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 1f5c8f848..222fb071f 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -1948,6 +1948,7 @@ var claimFixtures = map[string]claimFixture{
"worker StartGeoipJobs": claimNonApp("GeoIP orphan sweep, D1 expiry and feed status under control/geoip/: the platform database, no app"),
"worker StartHostReports": claimNonApp("this console's census report (status/consoles) and roster activation release"),
"worker StartInfraPass": claimNonApp("the deployment's infrastructure inventory snapshot"),
+ "worker StartPlanGracePass": claimNonApp("an account's plan cap warnings and grace clocks in plan_cap_state, keyed by account; names no app"),
"worker StartPlanLimitsPass": claimNonApp("account plan rows and their limits records under accounts/<sqid>/limits.json; names no app"),
"worker PublishPlansMarker": claimNonApp("the plans deployment marker (control/plans.json): whether boxes read limits; names no app"),
"worker StartClaimRecoveryPass": {door: &claimDoor{
diff --git a/internal/console/claim_invariant_probes_worker_test.go b/internal/console/claim_invariant_probes_worker_test.go
index a79737061..65f1ef5d9 100644
--- a/internal/console/claim_invariant_probes_worker_test.go
+++ b/internal/console/claim_invariant_probes_worker_test.go
@@ -205,6 +205,20 @@ var claimWorkerProbes = map[string]claimProbe{
return ""
},
},
+ "worker StartPlanGracePass": {
+ setup: func(t *testing.T, cx *claimCase) { cx.srv.cfg.PlanCatalog = examplePlanCatalog(t) },
+ do: claimWorkerReply("StartPlanGracePass"),
+ effect: func(t *testing.T, cx *claimCase, r claimReply) string {
+ acct, err := cx.srv.store.AccountBySqid("bab")
+ if err != nil || acct == nil {
+ return "no bab account"
+ }
+ if states, err := cx.srv.store.CapStates(acct.ID); err != nil || len(states) == 0 {
+ return "no plan cap state was written for bab"
+ }
+ return ""
+ },
+ },
"worker StartPlanLimitsPass": {
setup: func(t *testing.T, cx *claimCase) { cx.srv.cfg.PlanCatalog = examplePlanCatalog(t) },
do: claimWorkerReply("StartPlanLimitsPass"),
diff --git a/internal/console/claim_workers.go b/internal/console/claim_workers.go
index ed947d88c..1f4c6d7d6 100644
--- a/internal/console/claim_workers.go
+++ b/internal/console/claim_workers.go
@@ -15,6 +15,7 @@ func (s *Server) registerClaimWorkers() {
"StartScanDrain": s.StartScanDrain,
"StartExpiryPass": s.StartExpiryPass,
"StartPlanLimitsPass": s.StartPlanLimitsPass,
+ "StartPlanGracePass": s.StartPlanGracePass,
"PublishPlansMarker": s.PublishPlansMarker,
"StartRunSweep": s.StartRunSweep,
"StartSeedsPass": s.StartSeedsPass,
diff --git a/internal/console/mailcounts.go b/internal/console/mailcounts.go
index 4952baab3..25e9e6c47 100644
--- a/internal/console/mailcounts.go
+++ b/internal/console/mailcounts.go
@@ -319,3 +319,12 @@ func mailAuditSubject(app, sender string) string {
// comment used to state without exception): it is computed from PER-DAY
// counts, so "never auto-resumes" turned an ordinary tier limit into a
// permanent one — see the day-roll check above.
+
+// AccountSends is the account's sends for one UTC day over every app and
+// sender: the account-wide figure a plan's email cap reads (spec §5.6).
+func (s *Store) AccountSends(ctx context.Context, account, day string) (int64, error) {
+ var n int64
+ err := s.db.QueryRowContext(ctx, `SELECT COALESCE(SUM(sends), 0) FROM mail_sender_counts
+ WHERE account = ? AND day = ?`, account, day).Scan(&n)
+ return n, err
+}
diff --git a/internal/console/plancaps_copy.go b/internal/console/plancaps_copy.go
index 81475dd29..1282ea191 100644
--- a/internal/console/plancaps_copy.go
+++ b/internal/console/plancaps_copy.go
@@ -24,3 +24,23 @@ var capCopy = map[string]string{
// planCheckFailedCopy is the approved answer when an account's plan could
// not be read (copy review 2026-10-22, cli.err.plan_check_failed).
const planCheckFailedCopy = "could not check this account's plan. Try again"
+
+// planNoticeCopy holds the plan warning and grace notices (plans 4a),
+// approved by delegation: a Luna pass on the house rules (Paul, 2026-10-25;
+// docs/superpowers/specs/LUNA-COPY-RESULT-PLANS-4A.md).
+var planNoticeCopy = map[string]string{
+ "usage.running_things": "%d of %d apps and instances",
+ "usage.storage": "%s of %s object storage",
+ "usage.email": "%d of %d emails today",
+ "usage.bandwidth": "%s of %s bandwidth this month",
+ "usage.awake_hours": "%d of %d awake hours this month",
+ "banner.warn": "This account has used %s. If it goes over, nothing changes during the grace period.",
+ "banner.over": "This account is over its plan: %s. Nothing changes until %s. To stay within the plan, buy a pack, move to a bigger plan, or clean up.",
+ "cli.warn": "this account has used %s",
+ "cli.over": "this account is over its plan: %s. nothing changes until %s. buy a pack, move to a bigger plan, or clean up",
+ "email.subject": "[carlos] Account %s: plan usage",
+ "email.intro": "Account %s is near or over its plan limits:",
+ "email.warn": "- %s.",
+ "email.over": "- %s, over the limit. Nothing changes until %s.",
+ "email.ways_out": "To stay within the plan, buy a pack, move to a bigger plan, or clean up.\n\nAccount settings:\n%s",
+}
diff --git a/internal/console/plangrace.go b/internal/console/plangrace.go
new file mode 100644
index 000000000..5d5def9c7
--- /dev/null
+++ b/internal/console/plangrace.go
@@ -0,0 +1,127 @@
+package console
+
+import "time"
+
+// Plans 4a (spec §6): one engine for warnings, grace and notice. A row per
+// account per cap says where the account stands; evaluateCap moves it on
+// from a fresh measurement, and afterGraceDue is the one question Plan 4b's
+// after-grace stages ask of it. Nothing here refuses or slows anything.
+
+// capID names a measured cap. The strings are stored and sent; keep them.
+type capID string
+
+const (
+ capRunningThings capID = "running_things" // count
+ capStorage capID = "storage" // bytes, per account
+ capEmail capID = "email" // sends, per UTC day
+ capBandwidth capID = "bandwidth" // bytes, per UTC month
+ capAwakeHours capID = "awake_hours" // hours, per UTC month
+)
+
+// capOrder is the order caps are listed in, everywhere.
+var capOrder = []capID{capRunningThings, capStorage, capEmail, capBandwidth, capAwakeHours}
+
+// capLevel is how close to its limit an account is on one cap.
+type capLevel string
+
+const (
+ levelOK capLevel = "ok" // under 80%
+ levelWarn capLevel = "warn" // 80% up to the limit
+ levelOver capLevel = "over" // past the limit: in grace
+ levelCeiling capLevel = "ceiling" // 2x the limit, for caps whose grace is "up to 2x"
+)
+
+func (l capLevel) over() bool { return l == levelOver || l == levelCeiling }
+
+// capState is one plan_cap_state row. A zero time is unset.
+type capState struct {
+ AccountID int64
+ Cap capID
+ Period string // "" counts and sizes, "2006-01-02" email, "2006-01" monthly
+ Level capLevel
+ Used, Limit int64
+ FirstOver time.Time // when this period's over began
+ GraceEnds time.Time
+ WarnedAt time.Time // the 80% warning went out this period
+ RemindedAt time.Time // the last over notice or reminder went out
+ NoticeAt time.Time // an owner received notice after the cap went over
+ UpdatedAt time.Time
+}
+
+// capPeriod is the window a cap's usage counts over: a daily cap rolls at
+// UTC midnight, a monthly one at the UTC month, counts and sizes never.
+func capPeriod(c capID, now time.Time) string {
+ switch c {
+ case capEmail:
+ return now.UTC().Format("2006-01-02")
+ case capBandwidth, capAwakeHours:
+ return now.UTC().Format("2006-01")
+ }
+ return ""
+}
+
+// hasCeiling: email, bandwidth and awake hours give grace "up to 2x"
+// (spec §6), so 2x is a level of its own. Counts and sizes do not.
+func hasCeiling(c capID) bool {
+ return c == capEmail || c == capBandwidth || c == capAwakeHours
+}
+
+// graceEnd is when grace started at first runs out (spec §6): 7 days for
+// counts and sizes, the rest of the UTC day for email, the rest of the
+// UTC month for bandwidth and awake hours.
+func graceEnd(c capID, first time.Time) time.Time {
+ u := first.UTC()
+ switch c {
+ case capEmail:
+ return time.Date(u.Year(), u.Month(), u.Day()+1, 0, 0, 0, 0, time.UTC)
+ case capBandwidth, capAwakeHours:
+ return time.Date(u.Year(), u.Month()+1, 1, 0, 0, 0, 0, time.UTC)
+ }
+ return u.Add(7 * 24 * time.Hour)
+}
+
+func levelOf(c capID, used, limit int64) capLevel {
+ switch {
+ case hasCeiling(c) && used >= 2*limit:
+ return levelCeiling
+ case used > limit:
+ return levelOver
+ case used*5 >= limit*4:
+ return levelWarn
+ }
+ return levelOK
+}
+
+// evaluateCap is the next row for cap c given a fresh measurement. A row
+// from an earlier period is not carried; within one, the over clock runs
+// from the first over and stops only when usage falls back under the
+// limit. WarnedAt and RemindedAt are the grace pass's to set.
+func evaluateCap(prev *capState, c capID, used, limit int64, now time.Time) capState {
+ next := capState{Cap: c, Period: capPeriod(c, now), Used: used, Limit: limit, UpdatedAt: now}
+ if prev != nil {
+ next.AccountID = prev.AccountID
+ if prev.Period == next.Period {
+ next.FirstOver, next.GraceEnds, next.NoticeAt = prev.FirstOver, prev.GraceEnds, prev.NoticeAt
+ next.WarnedAt, next.RemindedAt = prev.WarnedAt, prev.RemindedAt
+ }
+ }
+ next.Level = levelOf(c, used, limit)
+ if !next.Level.over() {
+ next.FirstOver, next.GraceEnds, next.NoticeAt = time.Time{}, time.Time{}, time.Time{}
+ return next
+ }
+ if next.FirstOver.IsZero() {
+ next.FirstOver = now
+ next.GraceEnds = graceEnd(c, now)
+ }
+ return next
+}
+
+// afterGraceDue is whether an after-grace stage may start (spec §6): over
+// in the current period (a row from an ended day or month is never due,
+// Astra plans-4a finding 4), grace run out, and an owner received notice
+// at least 3 days before now.
+func afterGraceDue(st capState, now time.Time) bool {
+ return st.Period == capPeriod(st.Cap, now) && st.Level.over() && !st.GraceEnds.IsZero() && !now.Before(st.GraceEnds) &&
+ !st.NoticeAt.IsZero() && !st.NoticeAt.After(now.Add(-72*time.Hour))
+}
diff --git a/internal/console/plangrace_cli_test.go b/internal/console/plangrace_cli_test.go
new file mode 100644
index 000000000..105b1a4ca
--- /dev/null
+++ b/internal/console/plangrace_cli_test.go
@@ -0,0 +1,100 @@
+package console
+
+import (
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// cliWarnings GETs an account-scoped CLI door and returns its plan warning
+// header values.
+func cliWarnings(t *testing.T, fx *consoleFixture, token string, accept bool) []string {
+ t.Helper()
+ req, err := http.NewRequest(http.MethodGet, fx.ts.URL+"/api/cli/apps/bab/list", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Authorization", "Bearer "+token)
+ if accept {
+ req.Header.Set(planWarningsAccept, "1")
+ }
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("GET list = %d", resp.StatusCode)
+ }
+ return resp.Header.Values(planWarningHeader)
+}
+
+func TestCLIWarningHeaderUnderAPlan(t *testing.T) {
+ fx := newConsoleFixture(t)
+ overRow(t, fx)
+ token := cliToken(t, fx, "paul@keymail.dev", "code-cli-warn")
+ got := cliWarnings(t, fx, token, true)
+ if len(got) != 1 || !strings.HasPrefix(got[0], "this account is over its plan: 2 GB of 1 GB object storage") {
+ t.Fatalf("warning header = %q", got)
+ }
+}
+
+func TestCLIWarningNoticeNeedsTheDeclaration(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := overRow(t, fx)
+ token := cliToken(t, fx, "paul@keymail.dev", "code-cli-decl")
+ if got := cliWarnings(t, fx, token, false); len(got) != 0 {
+ t.Fatalf("warning sent to a CLI that does not print it: %q", got)
+ }
+ if st, _ := capRow(t, fx, acct, capStorage); !st.NoticeAt.IsZero() {
+ t.Fatal("notice recorded for a CLI that does not print warnings")
+ }
+ cliWarnings(t, fx, token, true)
+ if st, _ := capRow(t, fx, acct, capStorage); st.NoticeAt.IsZero() {
+ t.Fatal("an owner's declaring CLI recorded no notice")
+ }
+}
+
+func TestCLIWarningServiceEarnsNoNotice(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := overRow(t, fx)
+ token := serviceToken(t, fx.st, acct.ID, "ci", "", svcrole.Publish)
+ if got := cliWarnings(t, fx, token, true); len(got) != 1 {
+ t.Fatalf("service saw %q, want the warning", got)
+ }
+ if st, _ := capRow(t, fx, acct, capStorage); !st.NoticeAt.IsZero() {
+ t.Fatal("a service credential recorded notice")
+ }
+}
+
+func TestCLIWarningWithoutACatalogUnchanged(t *testing.T) {
+ fx := newConsoleFixture(t)
+ overRow(t, fx)
+ fx.srv.cfg.PlanCatalog = nil
+ token := cliToken(t, fx, "paul@keymail.dev", "code-cli-off")
+ if got := cliWarnings(t, fx, token, true); len(got) != 0 {
+ t.Fatalf("warning with plans off: %q", got)
+ }
+}
+
+// App-scoped doors carry the warnings too: they resolve through
+// apiAccountAppSaying, not apiPrincipalAccount.
+func TestCLIWarningOnAppScopedDoors(t *testing.T) {
+ fx := newConsoleFixture(t)
+ overRow(t, fx)
+ shipVersion(t, fx, "kass", "v9")
+ token := cliToken(t, fx, "paul@keymail.dev", "code-cli-app")
+ req, _ := http.NewRequest(http.MethodGet, fx.ts.URL+"/api/cli/apps/bab/kass/channels", nil)
+ req.Header.Set("Authorization", "Bearer "+token)
+ req.Header.Set(planWarningsAccept, "1")
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ if got := resp.Header.Values(planWarningHeader); resp.StatusCode != http.StatusOK || len(got) != 1 {
+ t.Fatalf("app door = %d, warnings %q", resp.StatusCode, got)
+ }
+}
diff --git a/internal/console/plangrace_store.go b/internal/console/plangrace_store.go
new file mode 100644
index 000000000..d4eeae170
--- /dev/null
+++ b/internal/console/plangrace_store.go
@@ -0,0 +1,117 @@
+package console
+
+import "time"
+
+// Plans 4a's own table, kept here so the feature is one file to read.
+func (s *Store) migratePlanGrace() error {
+ _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS plan_cap_state (
+ account_id INTEGER NOT NULL,
+ cap TEXT NOT NULL,
+ period TEXT NOT NULL DEFAULT '',
+ level TEXT NOT NULL,
+ used INTEGER NOT NULL,
+ cap_limit INTEGER NOT NULL,
+ first_over INTEGER NOT NULL DEFAULT 0,
+ grace_ends INTEGER NOT NULL DEFAULT 0,
+ warned_at INTEGER NOT NULL DEFAULT 0,
+ reminded_at INTEGER NOT NULL DEFAULT 0,
+ notice_at INTEGER NOT NULL DEFAULT 0,
+ updated_at INTEGER NOT NULL,
+ PRIMARY KEY (account_id, cap)
+);`)
+ return err
+}
+
+func unixOrZero(t time.Time) int64 {
+ if t.IsZero() {
+ return 0
+ }
+ return t.Unix()
+}
+
+func timeOrZero(sec int64) time.Time {
+ if sec == 0 {
+ return time.Time{}
+ }
+ return time.Unix(sec, 0).UTC()
+}
+
+// CapStates is every cap row for the account, in capOrder.
+func (s *Store) CapStates(accountID int64) ([]capState, error) {
+ rows, err := s.db.Query(`SELECT cap, period, level, used, cap_limit, first_over, grace_ends,
+ warned_at, reminded_at, notice_at, updated_at FROM plan_cap_state WHERE account_id = ?`, accountID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ byCap := map[capID]capState{}
+ for rows.Next() {
+ st := capState{AccountID: accountID}
+ var first, grace, warned, reminded, notice, updated int64
+ if err := rows.Scan(&st.Cap, &st.Period, &st.Level, &st.Used, &st.Limit, &first, &grace,
+ &warned, &reminded, &notice, &updated); err != nil {
+ return nil, err
+ }
+ st.FirstOver, st.GraceEnds, st.WarnedAt = timeOrZero(first), timeOrZero(grace), timeOrZero(warned)
+ st.RemindedAt, st.NoticeAt, st.UpdatedAt = timeOrZero(reminded), timeOrZero(notice), timeOrZero(updated)
+ byCap[st.Cap] = st
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ var out []capState
+ for _, c := range capOrder {
+ if st, ok := byCap[c]; ok {
+ out = append(out, st)
+ }
+ }
+ return out, nil
+}
+
+// PutCapState writes the row for (s.AccountID, s.Cap), replacing any, except
+// that notice already recorded for the same episode (same period, same
+// first over) is kept: a page view or CLI request may record notice
+// between the pass's read and this write (Astra plans-4a finding 1).
+func (s *Store) PutCapState(st capState) error {
+ _, err := s.db.Exec(`INSERT INTO plan_cap_state (account_id, cap, period, level, used, cap_limit,
+ first_over, grace_ends, warned_at, reminded_at, notice_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(account_id, cap) DO UPDATE SET period = excluded.period, level = excluded.level,
+ used = excluded.used, cap_limit = excluded.cap_limit, first_over = excluded.first_over,
+ grace_ends = excluded.grace_ends, warned_at = excluded.warned_at, reminded_at = excluded.reminded_at,
+ notice_at = CASE
+ WHEN plan_cap_state.period = excluded.period AND plan_cap_state.first_over = excluded.first_over
+ AND excluded.first_over <> 0 AND plan_cap_state.notice_at <> 0
+ AND (excluded.notice_at = 0 OR plan_cap_state.notice_at < excluded.notice_at)
+ THEN plan_cap_state.notice_at ELSE excluded.notice_at END,
+ updated_at = excluded.updated_at`,
+ st.AccountID, string(st.Cap), st.Period, string(st.Level), st.Used, st.Limit,
+ unixOrZero(st.FirstOver), unixOrZero(st.GraceEnds), unixOrZero(st.WarnedAt),
+ unixOrZero(st.RemindedAt), unixOrZero(st.NoticeAt), unixOrZero(st.UpdatedAt))
+ return err
+}
+
+// DeleteCapState drops the account's row for a cap it no longer has.
+func (s *Store) DeleteCapState(accountID int64, c capID) error {
+ _, err := s.db.Exec(`DELETE FROM plan_cap_state WHERE account_id = ? AND cap = ?`, accountID, string(c))
+ return err
+}
+
+// RecordCapNotice records that an owner received notice, at `at`, of the
+// caps in seen: the rows as the owner was shown them. Notice counts only
+// for the episode shown (same period and first over, Astra plans-4a
+// finding 2), only once the cap was over and not before it went over
+// (spec §6), and the first such notice is kept.
+func (s *Store) RecordCapNotice(accountID int64, seen []capState, at time.Time) error {
+ for _, st := range seen {
+ if !st.Level.over() || st.FirstOver.IsZero() || at.Before(st.FirstOver) {
+ continue
+ }
+ if _, err := s.db.Exec(`UPDATE plan_cap_state SET notice_at = ? WHERE account_id = ? AND cap = ?
+ AND period = ? AND first_over = ? AND level IN ('over', 'ceiling') AND notice_at = 0`,
+ at.Unix(), accountID, string(st.Cap), st.Period, st.FirstOver.Unix()); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/internal/console/plangrace_test.go b/internal/console/plangrace_test.go
new file mode 100644
index 000000000..4243c0082
--- /dev/null
+++ b/internal/console/plangrace_test.go
@@ -0,0 +1,240 @@
+package console
+
+import (
+ "testing"
+ "time"
+)
+
+func TestCapLevels(t *testing.T) {
+ for _, c := range []struct {
+ cap capID
+ used int64
+ want capLevel
+ }{
+ {capRunningThings, 79, levelOK}, {capRunningThings, 80, levelWarn}, {capRunningThings, 100, levelWarn},
+ {capRunningThings, 101, levelOver}, {capEmail, 200, levelCeiling}, {capStorage, 200, levelOver},
+ {capBandwidth, 250, levelCeiling}, {capAwakeHours, 199, levelOver},
+ } {
+ if got := evaluateCap(nil, c.cap, c.used, 100, planNow).Level; got != c.want {
+ t.Errorf("%s used %d of 100 = %s, want %s", c.cap, c.used, got, c.want)
+ }
+ }
+}
+
+func TestEvaluateCapGraceEnds(t *testing.T) {
+ now := planNow.UTC()
+ day := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, time.UTC)
+ month := time.Date(now.Year(), now.Month()+1, 1, 0, 0, 0, 0, time.UTC)
+ for _, c := range []struct {
+ cap capID
+ want time.Time
+ }{
+ {capRunningThings, now.Add(7 * 24 * time.Hour)}, {capStorage, now.Add(7 * 24 * time.Hour)},
+ {capEmail, day}, {capBandwidth, month}, {capAwakeHours, month},
+ } {
+ st := evaluateCap(nil, c.cap, 150, 100, now)
+ if !st.GraceEnds.Equal(c.want) || !st.FirstOver.Equal(now) {
+ t.Errorf("%s: FirstOver %v GraceEnds %v, want %v and %v", c.cap, st.FirstOver, st.GraceEnds, now, c.want)
+ }
+ }
+}
+
+func TestEvaluateCapKeepsFirstOverWhileOver(t *testing.T) {
+ first := evaluateCap(nil, capRunningThings, 4, 3, planNow)
+ later := evaluateCap(&first, capRunningThings, 5, 3, planNow.Add(3*24*time.Hour))
+ if !later.FirstOver.Equal(first.FirstOver) || !later.GraceEnds.Equal(first.GraceEnds) {
+ t.Fatalf("still over: FirstOver %v GraceEnds %v, want %v %v", later.FirstOver, later.GraceEnds, first.FirstOver, first.GraceEnds)
+ }
+}
+
+func TestEvaluateCapUnderClearsClocks(t *testing.T) {
+ over := evaluateCap(nil, capStorage, 150, 100, planNow)
+ over.NoticeAt = planNow
+ under := evaluateCap(&over, capStorage, 90, 100, planNow.Add(time.Hour))
+ if under.Level != levelWarn || !under.FirstOver.IsZero() || !under.GraceEnds.IsZero() || !under.NoticeAt.IsZero() {
+ t.Fatalf("back under: %+v, want warn with clocks cleared", under)
+ }
+}
+
+func TestEvaluateCapNewPeriodClears(t *testing.T) {
+ now := planNow.UTC()
+ email := evaluateCap(nil, capEmail, 150, 100, now.Add(-24*time.Hour))
+ email.WarnedAt, email.NoticeAt = now.Add(-24*time.Hour), now.Add(-24*time.Hour)
+ if got := evaluateCap(&email, capEmail, 10, 100, now); got.Level != levelOK || !got.WarnedAt.IsZero() || !got.NoticeAt.IsZero() {
+ t.Errorf("email on a new day = %+v, want a fresh row", got)
+ }
+ bw := evaluateCap(nil, capBandwidth, 150, 100, now.AddDate(0, -1, 0))
+ bw.NoticeAt = bw.FirstOver
+ if got := evaluateCap(&bw, capBandwidth, 150, 100, now); !got.NoticeAt.IsZero() || !got.FirstOver.Equal(now) {
+ t.Errorf("bandwidth in a new month = %+v, want clocks from now", got)
+ }
+ rt := evaluateCap(nil, capRunningThings, 4, 3, now.AddDate(0, -1, 0))
+ if got := evaluateCap(&rt, capRunningThings, 4, 3, now); !got.FirstOver.Equal(rt.FirstOver) {
+ t.Errorf("running things a month on: FirstOver %v, want %v (counts never roll)", got.FirstOver, rt.FirstOver)
+ }
+}
+
+func TestEvaluateCapIsStable(t *testing.T) {
+ first := evaluateCap(nil, capEmail, 150, 100, planNow)
+ first.NoticeAt, first.WarnedAt, first.RemindedAt = planNow, planNow, planNow
+ again := evaluateCap(&first, capEmail, 150, 100, planNow.Add(time.Minute))
+ if !again.FirstOver.Equal(first.FirstOver) || !again.GraceEnds.Equal(first.GraceEnds) || !again.NoticeAt.Equal(first.NoticeAt) ||
+ !again.WarnedAt.Equal(first.WarnedAt) || !again.RemindedAt.Equal(first.RemindedAt) {
+ t.Fatalf("re-evaluated = %+v, want the clocks of %+v", again, first)
+ }
+}
+
+func TestAfterGraceDue(t *testing.T) {
+ st := evaluateCap(nil, capStorage, 150, 100, planNow)
+ ended := st.GraceEnds
+ if afterGraceDue(st, ended.Add(-time.Second)) {
+ t.Error("due before grace ended")
+ }
+ if afterGraceDue(st, ended) {
+ t.Error("due with no notice")
+ }
+ st.NoticeAt = ended.Add(-71 * time.Hour)
+ if afterGraceDue(st, ended) {
+ t.Error("due with notice 71h old")
+ }
+ st.NoticeAt = ended.Add(-72 * time.Hour)
+ if !afterGraceDue(st, ended) {
+ t.Error("not due with grace ended and notice 72h old")
+ }
+}
+
+func TestCapStateRoundTrip(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct, _ := fx.st.AccountBySqid(fx.sqid)
+ st := evaluateCap(nil, capBandwidth, 150, 100, planNow)
+ st.AccountID, st.WarnedAt = acct.ID, planNow
+ if err := fx.st.PutCapState(st); err != nil {
+ t.Fatal(err)
+ }
+ got, err := fx.st.CapStates(acct.ID)
+ if err != nil || len(got) != 1 {
+ t.Fatalf("CapStates = %v, %v", got, err)
+ }
+ g := got[0]
+ if g.Cap != capBandwidth || g.Level != levelOver || g.Used != 150 || g.Limit != 100 || g.Period != st.Period ||
+ !g.FirstOver.Equal(st.FirstOver.Truncate(time.Second)) || !g.GraceEnds.Equal(st.GraceEnds) ||
+ !g.WarnedAt.Equal(planNow) || !g.NoticeAt.IsZero() {
+ t.Fatalf("round trip = %+v, want %+v", g, st)
+ }
+ if err := fx.st.DeleteCapState(acct.ID, capBandwidth); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := fx.st.CapStates(acct.ID); len(got) != 0 {
+ t.Fatalf("after delete = %v", got)
+ }
+}
+
+func TestRecordCapNoticeOnlyWhenOver(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct, _ := fx.st.AccountBySqid(fx.sqid)
+ warn := evaluateCap(nil, capEmail, 85, 100, planNow)
+ over := evaluateCap(nil, capStorage, 150, 100, planNow)
+ warn.AccountID, over.AccountID = acct.ID, acct.ID
+ for _, s := range []capState{warn, over} {
+ if err := fx.st.PutCapState(s); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := fx.st.RecordCapNotice(acct.ID, []capState{warn, over}, planNow); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.RecordCapNotice(acct.ID, []capState{over}, planNow.Add(time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ got, _ := fx.st.CapStates(acct.ID)
+ for _, g := range got {
+ switch g.Cap {
+ case capEmail:
+ if !g.NoticeAt.IsZero() {
+ t.Errorf("warn row got notice %v", g.NoticeAt)
+ }
+ case capStorage:
+ if !g.NoticeAt.Equal(planNow) {
+ t.Errorf("over row notice = %v, want the first, %v", g.NoticeAt, planNow)
+ }
+ }
+ }
+}
+
+// Astra plans-4a finding 1: the pass's snapshot upsert must not erase
+// notice recorded between its read and its write, within one episode.
+func TestPutCapStateKeepsConcurrentNotice(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct, _ := fx.st.AccountBySqid(fx.sqid)
+ st := evaluateCap(nil, capStorage, 150, 100, planNow)
+ st.AccountID = acct.ID
+ if err := fx.st.PutCapState(st); err != nil {
+ t.Fatal(err)
+ }
+ snapshot := st // the pass read this before the owner's page view
+ if err := fx.st.RecordCapNotice(acct.ID, []capState{st}, planNow.Add(time.Minute)); err != nil {
+ t.Fatal(err)
+ }
+ snapshot.Used, snapshot.UpdatedAt = 160, planNow.Add(2*time.Minute)
+ if err := fx.st.PutCapState(snapshot); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := capRow(t, fx, acct, capStorage); !got.NoticeAt.Equal(planNow.Add(time.Minute).UTC().Truncate(time.Second)) {
+ t.Fatalf("notice after a stale upsert = %v, want the recorded one", got.NoticeAt)
+ }
+ // A new episode (a different first over) replaces it.
+ fresh := evaluateCap(nil, capStorage, 150, 100, planNow.Add(48*time.Hour))
+ fresh.AccountID = acct.ID
+ if err := fx.st.PutCapState(fresh); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := capRow(t, fx, acct, capStorage); !got.NoticeAt.IsZero() {
+ t.Fatalf("new episode kept the old notice %v", got.NoticeAt)
+ }
+}
+
+// Finding 2: notice counts only for the episode the owner was shown.
+func TestRecordCapNoticeMatchesTheEpisodeShown(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct, _ := fx.st.AccountBySqid(fx.sqid)
+ yesterday := evaluateCap(nil, capEmail, 150, 100, planNow.Add(-24*time.Hour))
+ yesterday.AccountID = acct.ID
+ if err := fx.st.PutCapState(yesterday); err != nil {
+ t.Fatal(err)
+ }
+ today := evaluateCap(nil, capEmail, 150, 100, planNow)
+ today.AccountID = acct.ID
+ if err := fx.st.PutCapState(today); err != nil { // the pass rolled the day after the page read yesterday's row
+ t.Fatal(err)
+ }
+ if err := fx.st.RecordCapNotice(acct.ID, []capState{yesterday}, planNow); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := capRow(t, fx, acct, capEmail); !got.NoticeAt.IsZero() {
+ t.Fatalf("yesterday's warning counted as notice for today: %v", got.NoticeAt)
+ }
+ if err := fx.st.RecordCapNotice(acct.ID, []capState{today}, planNow.Add(-time.Minute)); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := capRow(t, fx, acct, capEmail); !got.NoticeAt.IsZero() {
+ t.Fatalf("notice dated before the first over counted: %v", got.NoticeAt)
+ }
+}
+
+// Finding 4: a daily or monthly row from an ended period is never due,
+// and is not shown.
+func TestExpiredPeriodIsNotDueOrShown(t *testing.T) {
+ oct := time.Date(2026, 10, 20, 12, 0, 0, 0, time.UTC)
+ st := evaluateCap(nil, capBandwidth, 150, 100, oct)
+ st.NoticeAt = oct.Add(5 * 24 * time.Hour)
+ nov := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)
+ if afterGraceDue(st, nov) {
+ t.Error("October's bandwidth row is due in November")
+ }
+ if got := planNoticesOf([]capState{st}, nov); len(got) != 0 {
+ t.Errorf("October's row shown in November: %v", got)
+ }
+ if got := planNoticesOf([]capState{st}, oct.Add(time.Hour)); len(got) != 1 {
+ t.Errorf("current row not shown: %v", got)
+ }
+}
diff --git a/internal/console/plangrace_view_test.go b/internal/console/plangrace_view_test.go
new file mode 100644
index 000000000..c35342f57
--- /dev/null
+++ b/internal/console/plangrace_view_test.go
@@ -0,0 +1,90 @@
+package console
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+// overRow puts the ops account over its storage cap under the example
+// catalog.
+func overRow(t *testing.T, fx *consoleFixture) *Account {
+ t.Helper()
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct, _ := fx.st.AccountBySqid(fx.sqid)
+ // The real clock: page views and CLI requests record notice at
+ // time.Now(), which must not fall before the first over.
+ st := evaluateCap(nil, capStorage, 2_000_000_000, 1_000_000_000, time.Now().Add(-time.Hour))
+ st.AccountID = acct.ID
+ if err := fx.st.PutCapState(st); err != nil {
+ t.Fatal(err)
+ }
+ return acct
+}
+
+func TestBannerShowsPlanNotices(t *testing.T) {
+ fx := newConsoleFixture(t)
+ overRow(t, fx)
+ c := signInPaul(t, fx)
+ _, _, body := get(t, c, fx.u("/"))
+ if !strings.Contains(body, "This account is over its plan: 2 GB of 1 GB object storage") {
+ t.Fatalf("account page has no plan banner:\n%s", body)
+ }
+}
+
+func TestBannerRecordsNoticeForOwnersOnly(t *testing.T) {
+ fx, _, _ := memberFixture(t)
+ acct := overRow(t, fx)
+ kim := newBrowser(t)
+ fx.setUser("kim@keymail.dev")
+ signUp(t, fx, kim, "code-kim-banner")
+ if _, _, body := get(t, kim, fx.u("/")); !strings.Contains(body, "over its plan") {
+ t.Fatal("a member sees no banner")
+ }
+ if st, _ := capRow(t, fx, acct, capStorage); !st.NoticeAt.IsZero() {
+ t.Fatalf("a member's page view recorded notice: %v", st.NoticeAt)
+ }
+ fx.setUser("paul@keymail.dev")
+ owner := signInPaul(t, fx)
+ get(t, owner, fx.u("/"))
+ if st, _ := capRow(t, fx, acct, capStorage); st.NoticeAt.IsZero() {
+ t.Fatal("an owner's page view recorded no notice")
+ }
+}
+
+func TestBannerWithoutACatalogUnchanged(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct, _ := fx.st.AccountBySqid(fx.sqid)
+ st := evaluateCap(nil, capStorage, 2_000_000_000, 1_000_000_000, planNow)
+ st.AccountID = acct.ID
+ if err := fx.st.PutCapState(st); err != nil { // a row left from when plans were on
+ t.Fatal(err)
+ }
+ c := signInPaul(t, fx)
+ if _, _, body := get(t, c, fx.u("/")); strings.Contains(body, "over its plan") {
+ t.Fatal("plan banner with no catalog")
+ }
+}
+
+// Finding 3: notice is the banner actually served, not the page data built.
+func TestBannerNoticeOnlyWhenRendered(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := overRow(t, fx)
+ req := httptest.NewRequest(http.MethodGet, fx.u("/"), nil)
+ rec := httptest.NewRecorder()
+ p := fx.srv.accountPage(rec, req, "paul@keymail.dev", "csrf", acct, RoleOwner)
+ if st, _ := capRow(t, fx, acct, capStorage); !st.NoticeAt.IsZero() {
+ t.Fatal("building page data recorded notice")
+ }
+ fx.srv.renderMessage(rec, req, http.StatusInternalServerError, "Error", "boom") // an error page instead
+ if st, _ := capRow(t, fx, acct, capStorage); !st.NoticeAt.IsZero() {
+ t.Fatal("an error page recorded notice")
+ }
+ p.Title, p.Msg = "Apps", "ok"
+ fx.srv.render(httptest.NewRecorder(), http.StatusOK, "message", p)
+ if st, _ := capRow(t, fx, acct, capStorage); st.NoticeAt.IsZero() {
+ t.Fatal("a rendered banner recorded no notice")
+ }
+}
diff --git a/internal/console/plangracepass.go b/internal/console/plangracepass.go
new file mode 100644
index 000000000..9e126ab88
--- /dev/null
+++ b/internal/console/plangracepass.go
@@ -0,0 +1,311 @@
+package console
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// planGracePassInterval is how often the grace pass measures. The figures
+// it reads move hourly (the economics pass) or daily (the storage sweep).
+const planGracePassInterval = time.Hour
+
+// planNoticeDeliveryTimeout bounds one owner email.
+const planNoticeDeliveryTimeout = 15 * time.Second
+
+// StartPlanGracePass measures every plan-governed account against its
+// effective limits, keeps each cap's grace clock and warns owners (plans
+// 4a, spec §6): now, then hourly. With no catalog it does nothing at all.
+func (s *Server) StartPlanGracePass(ctx context.Context) {
+ if s.cfg.Releases == nil || s.cfg.PlanCatalog == nil {
+ return
+ }
+ t := time.NewTicker(planGracePassInterval)
+ defer t.Stop()
+ for {
+ s.planGracePass(ctx, time.Now())
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ }
+ }
+}
+
+// planGracePass is one pass at the given clock. One account's failure
+// never stops the others; a cap that cannot be measured keeps its row.
+func (s *Server) planGracePass(ctx context.Context, now time.Time) {
+ if s.cfg.Releases == nil || s.cfg.PlanCatalog == nil {
+ return
+ }
+ accts, err := s.store.Accounts()
+ if err != nil {
+ log.Printf("console: plan grace: accounts: %v", err)
+ return
+ }
+ for i := range accts {
+ if ctx.Err() != nil {
+ return
+ }
+ if err := s.planGraceAccount(ctx, &accts[i], now); err != nil {
+ log.Printf("console: plan grace %s: %v", accts[i].Sqid, err)
+ }
+ }
+}
+
+func (s *Server) planGraceAccount(ctx context.Context, acct *Account, now time.Time) error {
+ l, err := s.EffectiveLimits(acct)
+ if err != nil || l == nil {
+ return err
+ }
+ prev, err := s.store.CapStates(acct.ID)
+ if err != nil {
+ return err
+ }
+ byCap := map[capID]*capState{}
+ for i := range prev {
+ byCap[prev[i].Cap] = &prev[i]
+ }
+ measures, errs := s.measureCaps(ctx, acct, l, now)
+ var states []capState
+ for _, c := range capOrder {
+ m, measured := measures[c]
+ switch {
+ case measured:
+ st := evaluateCap(byCap[c], c, m.Used, m.Limit, now)
+ st.AccountID = acct.ID
+ if err := s.store.PutCapState(st); err != nil {
+ return err
+ }
+ states = append(states, st)
+ case errs[c] != nil:
+ log.Printf("console: plan grace %s: %s: %v (row kept)", acct.Sqid, c, errs[c])
+ if p := byCap[c]; p != nil {
+ states = append(states, *p)
+ }
+ case byCap[c] != nil:
+ if err := s.store.DeleteCapState(acct.ID, c); err != nil {
+ return err
+ }
+ }
+ }
+ return s.notifyPlanOwners(ctx, acct, states, now)
+}
+
+// noticeDue is whether st should go out in this pass's email: the first
+// 80% warning of the period, the first over, then a reminder a day.
+func noticeDue(st capState, now time.Time) bool {
+ switch {
+ case st.Level == levelWarn:
+ return st.WarnedAt.IsZero()
+ case st.Level.over():
+ return st.RemindedAt.IsZero() || st.RemindedAt.Before(st.FirstOver) || !now.Before(st.RemindedAt.Add(24*time.Hour))
+ }
+ return false
+}
+
+// notifyPlanOwners sends one email per owner listing every cap that is
+// due. Marks are set, and notice recorded, only when at least one owner's
+// delivery was accepted; otherwise the next pass tries again.
+func (s *Server) notifyPlanOwners(ctx context.Context, acct *Account, states []capState, now time.Time) error {
+ var due []capState
+ for _, st := range states {
+ if noticeDue(st, now) {
+ due = append(due, st)
+ }
+ }
+ if len(due) == 0 || (s.consoleMail == nil && s.sendFederated == nil) {
+ return nil
+ }
+ members, err := s.store.Members(acct.ID)
+ if err != nil {
+ return err
+ }
+ subject, body := s.planNoticeEmail(acct, due)
+ delivered := false
+ for _, m := range members {
+ if m.Role != RoleOwner {
+ continue
+ }
+ dctx, cancel := context.WithTimeout(ctx, planNoticeDeliveryTimeout)
+ _, err := s.deliver(dctx, m.Name, subject, body, planNoticeDeliveryTimeout*4/5)
+ cancel()
+ if err != nil {
+ log.Printf("console: plan grace %s: notice to %s: %v", acct.Sqid, m.Name, err)
+ continue
+ }
+ delivered = true
+ }
+ if !delivered {
+ return nil
+ }
+ for _, st := range due {
+ if st.WarnedAt.IsZero() {
+ st.WarnedAt = now
+ }
+ if st.Level.over() {
+ st.RemindedAt = now
+ }
+ if err := s.store.PutCapState(st); err != nil {
+ return err
+ }
+ }
+ return s.store.RecordCapNotice(acct.ID, due, now)
+}
+
+func (s *Server) planNoticeEmail(acct *Account, due []capState) (string, string) {
+ lines := []string{fmt.Sprintf(planNoticeCopy["email.intro"], acct.Sqid), ""}
+ for _, n := range planNoticesOf(due, time.Now()) {
+ lines = append(lines, planNoticeText(n, "email"))
+ }
+ settings := s.cfg.Origin + "/a/" + url.PathEscape(acct.Sqid) + "/settings"
+ lines = append(lines, "", fmt.Sprintf(planNoticeCopy["email.ways_out"], settings))
+ return fmt.Sprintf(planNoticeCopy["email.subject"], acct.Sqid), strings.Join(lines, "\n") + "\n"
+}
+
+// planNotice is one cap worth telling someone about.
+type planNotice struct {
+ Cap capID
+ Level capLevel
+ Used, Limit int64
+ GraceEnds time.Time
+}
+
+// planNoticesOf is the caps at warn or over in the current period, in
+// capOrder. A row left from an ended day or month is not shown.
+func planNoticesOf(states []capState, now time.Time) []planNotice {
+ var out []planNotice
+ for _, c := range capOrder {
+ for _, st := range states {
+ if st.Cap == c && st.Period == capPeriod(c, now) && (st.Level == levelWarn || st.Level.over()) {
+ out = append(out, planNotice{Cap: st.Cap, Level: st.Level, Used: st.Used, Limit: st.Limit, GraceEnds: st.GraceEnds})
+ }
+ }
+ }
+ return out
+}
+
+// planNoticeText renders one notice for a surface: "banner", "cli" or
+// "email".
+func planNoticeText(n planNotice, surface string) string {
+ use := usagePhrase(n)
+ if n.Level.over() {
+ return fmt.Sprintf(planNoticeCopy[surface+".over"], use, n.GraceEnds.UTC().Format("2 January 2006"))
+ }
+ return fmt.Sprintf(planNoticeCopy[surface+".warn"], use)
+}
+
+func usagePhrase(n planNotice) string {
+ f := planNoticeCopy["usage."+string(n.Cap)]
+ switch n.Cap {
+ case capStorage, capBandwidth:
+ return fmt.Sprintf(f, humanGB(n.Used), humanGB(n.Limit))
+ }
+ return fmt.Sprintf(f, n.Used, n.Limit)
+}
+
+// humanGB is bytes as gigabytes (1e9) to one decimal place, without a
+// trailing ".0".
+func humanGB(b int64) string {
+ s := strconv.FormatFloat(float64(b)/1e9, 'f', 1, 64)
+ return strings.TrimSuffix(s, ".0") + " GB"
+}
+
+// planBanner is the account page's plan warnings, one line per cap at warn
+// or over, and the rows behind them when the viewer is an owner. It records
+// nothing: notice is the banner actually served, so render records it once
+// the page is written (Astra plans-4a finding 3). A store error shows no
+// banner and never fails the page.
+func (s *Server) planBanner(acct *Account, role string, now time.Time) ([]string, []capState) {
+ if s.cfg.PlanCatalog == nil {
+ return nil, nil
+ }
+ states, err := s.store.CapStates(acct.ID)
+ if err != nil {
+ log.Printf("console: plan banner %s: %v", acct.Sqid, err)
+ return nil, nil
+ }
+ var lines []string
+ for _, n := range planNoticesOf(states, now) {
+ lines = append(lines, planNoticeText(n, "banner"))
+ }
+ if role != RoleOwner || len(lines) == 0 {
+ return lines, nil
+ }
+ return lines, shownStates(states, now)
+}
+
+// shownStates is the rows planNoticesOf shows, for recording notice.
+func shownStates(states []capState, now time.Time) []capState {
+ var out []capState
+ for _, st := range states {
+ if st.Period == capPeriod(st.Cap, now) && st.Level.over() {
+ out = append(out, st)
+ }
+ }
+ return out
+}
+
+// recordBannerNotice records notice for a page whose banner was served to
+// an owner.
+func (s *Server) recordBannerNotice(accountID int64, seen []capState, now time.Time) {
+ if len(seen) == 0 {
+ return
+ }
+ if err := s.store.RecordCapNotice(accountID, seen, now); err != nil {
+ log.Printf("console: plan banner %d: notice: %v", accountID, err)
+ }
+}
+
+// planWarningsAccept is the request header by which a CLI says it prints
+// plan warnings; planWarningHeader carries one warning per value back.
+const (
+ planWarningsAccept = "X-Carlos-Plan-Warnings"
+ planWarningHeader = "X-Carlos-Plan-Warning"
+)
+
+// writePlanWarnings adds the account's plan warnings to a CLI reply, but
+// only for a CLI that declared it prints them: an older one would drop the
+// header, and must earn no notice. A person who owns the account receiving
+// a cap that is over is notice received (spec §6); a service is not.
+func (s *Server) writePlanWarnings(w http.ResponseWriter, r *http.Request, p Principal, acct *Account) {
+ if s.cfg.PlanCatalog == nil || r.Header.Get(planWarningsAccept) != "1" {
+ return
+ }
+ states, err := s.store.CapStates(acct.ID)
+ if err != nil {
+ log.Printf("console: plan warnings %s: %v", acct.Sqid, err)
+ return
+ }
+ now := time.Now()
+ for _, n := range planNoticesOf(states, now) {
+ w.Header().Add(planWarningHeader, planNoticeText(n, "cli"))
+ }
+ seen := shownStates(states, now)
+ if len(seen) == 0 || p.Kind != PrincipalUser || !s.isOwner(acct, p.Address) {
+ return
+ }
+ if err := s.store.RecordCapNotice(acct.ID, seen, now); err != nil {
+ log.Printf("console: plan warnings %s: notice: %v", acct.Sqid, err)
+ }
+}
+
+// isOwner is whether addr owns acct. A lookup failure is "no".
+func (s *Server) isOwner(acct *Account, addr string) bool {
+ members, err := s.store.Members(acct.ID)
+ if err != nil {
+ log.Printf("console: plan warnings %s: members: %v", acct.Sqid, err)
+ return false
+ }
+ for _, m := range members {
+ if m.Role == RoleOwner && strings.EqualFold(m.Name, addr) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/console/plangracepass_test.go b/internal/console/plangracepass_test.go
new file mode 100644
index 000000000..39c0f06d3
--- /dev/null
+++ b/internal/console/plangracepass_test.go
@@ -0,0 +1,146 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+ "time"
+)
+
+// graceFixture turns plans on with the ops account at its running-things
+// cap (warn), owners reachable by a fake console mailer.
+func graceFixture(t *testing.T) (*consoleFixture, *Account, *fakeConsoleMail) {
+ t.Helper()
+ fx := newConsoleFixture(t)
+ acct := atRunningCap(t, fx, 5)
+ mailer := &fakeConsoleMail{ready: true}
+ fx.srv.consoleMail = mailer
+ fx.srv.sendFederated = nil
+ return fx, acct, mailer
+}
+
+func capRow(t *testing.T, fx *consoleFixture, acct *Account, c capID) (capState, bool) {
+ t.Helper()
+ states, err := fx.st.CapStates(acct.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, s := range states {
+ if s.Cap == c {
+ return s, true
+ }
+ }
+ return capState{}, false
+}
+
+func goOver(t *testing.T, fx *consoleFixture, acct *Account) {
+ t.Helper()
+ capsApp(t, fx, acct, "overflow")
+}
+
+func TestGracePassOffWithoutACatalog(t *testing.T) {
+ fx := newConsoleFixture(t)
+ mailer := &fakeConsoleMail{ready: true}
+ fx.srv.consoleMail = mailer
+ fx.srv.planGracePass(context.Background(), planNow)
+ acct, _ := fx.st.AccountBySqid(fx.sqid)
+ if states, _ := fx.st.CapStates(acct.ID); len(states) != 0 {
+ t.Fatalf("rows with plans off: %v", states)
+ }
+ if len(mailer.sentCopy()) != 0 {
+ t.Fatal("mail with plans off")
+ }
+}
+
+func TestGracePassWarnsOnceAt80Percent(t *testing.T) {
+ fx, acct, mailer := graceFixture(t)
+ fx.srv.planGracePass(context.Background(), planNow)
+ st, ok := capRow(t, fx, acct, capRunningThings)
+ if !ok || st.Level != levelWarn || !st.WarnedAt.Equal(planNow.UTC().Truncate(time.Second)) {
+ t.Fatalf("row = %+v, %v, want warn with WarnedAt", st, ok)
+ }
+ sent := mailer.sentCopy()
+ if len(sent) != 1 || !strings.HasPrefix(sent[0], "paul@keymail.dev|") {
+ t.Fatalf("sent = %v, want one email to the owner", sent)
+ }
+ fx.srv.planGracePass(context.Background(), planNow.Add(time.Hour))
+ if n := len(mailer.sentCopy()); n != 1 {
+ t.Fatalf("second pass sent %d emails in all, want still 1", n)
+ }
+}
+
+func TestGracePassOverStartsGraceAndRecordsNotice(t *testing.T) {
+ fx, acct, mailer := graceFixture(t)
+ goOver(t, fx, acct)
+ fx.srv.planGracePass(context.Background(), planNow)
+ st, _ := capRow(t, fx, acct, capRunningThings)
+ if st.Level != levelOver || !st.GraceEnds.Equal(planNow.Add(7*24*time.Hour).UTC().Truncate(time.Second)) {
+ t.Fatalf("row = %+v, want over with 7 days of grace", st)
+ }
+ if !st.NoticeAt.Equal(planNow.UTC().Truncate(time.Second)) {
+ t.Fatalf("NoticeAt = %v, want the delivered email's time", st.NoticeAt)
+ }
+ if len(mailer.sentCopy()) != 1 {
+ t.Fatalf("sent = %v", mailer.sentCopy())
+ }
+}
+
+func TestGracePassRemindsOncePerDay(t *testing.T) {
+ fx, acct, mailer := graceFixture(t)
+ goOver(t, fx, acct)
+ ctx := context.Background()
+ fx.srv.planGracePass(ctx, planNow)
+ fx.srv.planGracePass(ctx, planNow.Add(time.Hour))
+ if n := len(mailer.sentCopy()); n != 1 {
+ t.Fatalf("after an hour: %d emails, want 1", n)
+ }
+ fx.srv.planGracePass(ctx, planNow.Add(24*time.Hour))
+ if n := len(mailer.sentCopy()); n != 2 {
+ t.Fatalf("after a day: %d emails, want 2", n)
+ }
+}
+
+func TestGracePassWithoutMailRecordsNoNotice(t *testing.T) {
+ fx, acct, mailer := graceFixture(t)
+ mailer.err = errors.New("ses down")
+ goOver(t, fx, acct)
+ fx.srv.planGracePass(context.Background(), planNow)
+ st, _ := capRow(t, fx, acct, capRunningThings)
+ if !st.NoticeAt.IsZero() || !st.RemindedAt.IsZero() || !st.WarnedAt.IsZero() {
+ t.Fatalf("row after failed delivery = %+v, want no notice and nothing marked sent", st)
+ }
+ if st.Level != levelOver || st.GraceEnds.IsZero() {
+ t.Fatalf("grace clock did not start: %+v", st)
+ }
+}
+
+func TestGracePassSkipsUnreadableMeasurements(t *testing.T) {
+ fx, acct, _ := graceFixture(t)
+ over := evaluateCap(nil, capStorage, 2<<30, 1<<30, planNow.Add(-48*time.Hour))
+ over.AccountID, over.NoticeAt = acct.ID, planNow.Add(-24*time.Hour)
+ if err := fx.st.PutCapState(over); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.SetAccountPlan(acct.ID, "personal", nil, "operator", nil, "test", "ops@example.com", planNow); err != nil {
+ t.Fatal(err)
+ }
+ fx.srv.planGracePass(context.Background(), planNow) // no storage sweep exists: storage is unknown
+ st, ok := capRow(t, fx, acct, capStorage)
+ if !ok || st.Level != levelOver || !st.FirstOver.Equal(over.FirstOver.Truncate(time.Second)) || st.NoticeAt.IsZero() {
+ t.Fatalf("storage row after an unreadable sweep = %+v, %v, want it unchanged", st, ok)
+ }
+}
+
+func TestGracePassMembersGetNoEmail(t *testing.T) {
+ fx, acct, mailer := graceFixture(t)
+ if err := fx.st.AddMember(acct.ID, "kim@keymail.dev", RoleMember, planNow); err != nil {
+ t.Fatal(err)
+ }
+ fx.srv.planGracePass(context.Background(), planNow)
+ for _, s := range mailer.sentCopy() {
+ if strings.HasPrefix(s, "kim@keymail.dev|") {
+ t.Fatalf("a member was emailed: %v", s)
+ }
+ }
+}
diff --git a/internal/console/planmeasure.go b/internal/console/planmeasure.go
new file mode 100644
index 000000000..4b6edd7da
--- /dev/null
+++ b/internal/console/planmeasure.go
@@ -0,0 +1,105 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "math"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/plans"
+ "github.com/carlosframework/platform/internal/usage"
+)
+
+// capMeasure is one cap's usage against the account's effective limit.
+type capMeasure struct{ Used, Limit int64 }
+
+// planStorageLookback is how many days back the storage cap looks for the
+// daily sweep, the storeSize precedent (apistore.go).
+const planStorageLookback = 3
+
+// measureCaps measures every cap the account's limits offer (a limit above
+// zero), from what the console already records (plans 4a, spec §6). A cap
+// that cannot be read lands in the error map, not the result: the grace
+// pass leaves its row alone rather than read a failure as zero.
+func (s *Server) measureCaps(ctx context.Context, acct *Account, l *plans.Limits, now time.Time) (map[capID]capMeasure, map[capID]error) {
+ got, errs := map[capID]capMeasure{}, map[capID]error{}
+ put := func(c capID, used, limit int64, err error) {
+ if err != nil {
+ errs[c] = err
+ return
+ }
+ got[c] = capMeasure{Used: used, Limit: limit}
+ }
+ if l.RunningThings > 0 {
+ n, err := s.runningThings(ctx, acct)
+ put(capRunningThings, int64(n), int64(l.RunningThings), err)
+ }
+ if l.AwakeHoursMonth > 0 || l.BandwidthBytesMonth > 0 {
+ meters, err := s.monthMeters(ctx, acct, now)
+ if l.AwakeHoursMonth > 0 {
+ put(capAwakeHours, int64(math.Floor(meters[usage.MeterInstanceHours])), int64(l.AwakeHoursMonth), err)
+ }
+ if l.BandwidthBytesMonth > 0 {
+ put(capBandwidth, int64(math.Floor(meters[usage.MeterEgressGB]*1e9)), l.BandwidthBytesMonth, err)
+ }
+ }
+ if l.StorageBytes > 0 {
+ n, err := s.accountStoreBytes(ctx, acct, now)
+ put(capStorage, n, l.StorageBytes, err)
+ }
+ if l.EmailPerDay > 0 {
+ n, err := s.store.AccountSends(ctx, acct.Sqid, usage.DayOf(now))
+ put(capEmail, n, int64(l.EmailPerDay), err)
+ }
+ return got, errs
+}
+
+// monthMeters is this UTC month's statement meters. No statement yet means
+// nothing used yet: a true zero, not an unknown.
+func (s *Server) monthMeters(ctx context.Context, acct *Account, now time.Time) (map[string]float64, error) {
+ st, err := usage.GetStatement(ctx, s.cfg.Releases, acct.Sqid, capPeriod(capBandwidth, now))
+ if errors.Is(err, os.ErrNotExist) {
+ return map[string]float64{}, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return st.Meters, nil
+}
+
+// accountStoreBytes sums the account's object-store bytes from the newest
+// daily storage sweep in the last planStorageLookback days. No sweep, or a
+// store the sweep could not size, is unknown rather than a smaller total.
+func (s *Server) accountStoreBytes(ctx context.Context, acct *Account, now time.Time) (int64, error) {
+ prefix := acct.Sqid + "/"
+ for i := 0; i < planStorageLookback; i++ {
+ key := usage.StorageDayKey(usage.DayOf(now.AddDate(0, 0, -i)))
+ raw, _, err := s.cfg.Releases.Get(ctx, key)
+ if errors.Is(err, os.ErrNotExist) {
+ continue
+ }
+ if err != nil {
+ return 0, err
+ }
+ var day usage.StorageDay
+ if err := json.Unmarshal(raw, &day); err != nil {
+ return 0, fmt.Errorf("%s: %w", key, err)
+ }
+ var total int64
+ for k, a := range day.Apps {
+ if !strings.HasPrefix(k, prefix) {
+ continue
+ }
+ if a.StoreUnswept {
+ return 0, fmt.Errorf("%s: store %s was not sized", key, k)
+ }
+ total += a.StoreBytes
+ }
+ return total, nil
+ }
+ return 0, fmt.Errorf("no storage sweep in the last %d days", planStorageLookback)
+}
diff --git a/internal/console/planmeasure_test.go b/internal/console/planmeasure_test.go
new file mode 100644
index 000000000..f00b329fd
--- /dev/null
+++ b/internal/console/planmeasure_test.go
@@ -0,0 +1,129 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/plans"
+ "github.com/carlosframework/platform/internal/usage"
+)
+
+// measureLimits offers every measured cap.
+func measureLimits() *plans.Limits {
+ return &plans.Limits{RunningThings: 3, StorageBytes: 1 << 30, EmailPerDay: 50,
+ BandwidthBytesMonth: 10_000_000_000, AwakeHoursMonth: 100}
+}
+
+func putStorageDay(t *testing.T, fx *consoleFixture, date string, apps map[string]usage.AppStorage) {
+ t.Helper()
+ b, _ := json.Marshal(usage.StorageDay{V: 1, Date: date, Apps: apps})
+ if _, err := fx.rel.Put(context.Background(), usage.StorageDayKey(date), b, ""); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestAccountSendsSumsSendersAndApps(t *testing.T) {
+ fx := newConsoleFixture(t)
+ ctx := context.Background()
+ today := usage.DayOf(planNow)
+ yesterday := usage.DayOf(planNow.AddDate(0, 0, -1))
+ for _, e := range []struct{ app, sender, day string }{
+ {"blog", "a", today}, {"blog", "b", today}, {"shop", "", today}, {"blog", "a", yesterday},
+ } {
+ if err := fx.st.RecordMailEvent(ctx, fx.sqid, e.app, e.sender, e.day, "Send"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := fx.st.RecordMailEvent(ctx, "zzzzz", "blog", "a", today, "Send"); err != nil {
+ t.Fatal(err)
+ }
+ if n, err := fx.st.AccountSends(ctx, fx.sqid, today); err != nil || n != 3 {
+ t.Fatalf("AccountSends today = %d, %v, want 3", n, err)
+ }
+}
+
+func TestMeasureCapsFromRecordedUsage(t *testing.T) {
+ fx := newConsoleFixture(t)
+ ctx := context.Background()
+ acct, _ := fx.st.AccountBySqid(fx.sqid)
+ if err := usage.UpsertStatement(ctx, fx.rel, usage.Statement{V: 1, Account: fx.sqid, Month: capPeriod(capBandwidth, planNow),
+ Meters: map[string]float64{usage.MeterInstanceHours: 12.7, usage.MeterEgressGB: 1.5}}); err != nil {
+ t.Fatal(err)
+ }
+ putStorageDay(t, fx, usage.DayOf(planNow.AddDate(0, 0, -1)), map[string]usage.AppStorage{
+ fx.sqid + "/a": {StoreBytes: 10, StoreProvisioned: true}, fx.sqid + "/b": {StoreBytes: 5, StoreProvisioned: true},
+ "zzzzz/x": {StoreBytes: 99, StoreProvisioned: true},
+ })
+ for i := 0; i < 2; i++ {
+ if err := fx.st.RecordMailEvent(ctx, fx.sqid, "blog", "", usage.DayOf(planNow), "Send"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ running, err := fx.srv.runningThings(ctx, acct)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, errs := fx.srv.measureCaps(ctx, acct, measureLimits(), planNow)
+ if len(errs) != 0 {
+ t.Fatalf("errors = %v", errs)
+ }
+ want := map[capID]int64{capRunningThings: int64(running), capAwakeHours: 12, capBandwidth: 1_500_000_000, capStorage: 15, capEmail: 2}
+ for c, w := range want {
+ if got[c].Used != w {
+ t.Errorf("%s used = %d, want %d", c, got[c].Used, w)
+ }
+ }
+ if got[capStorage].Limit != 1<<30 || got[capAwakeHours].Limit != 100 {
+ t.Errorf("limits = %+v", got)
+ }
+}
+
+func TestMeasureCapsSkipsZeroLimits(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct, _ := fx.st.AccountBySqid(fx.sqid)
+ l := measureLimits()
+ l.StorageBytes = 0
+ got, errs := fx.srv.measureCaps(context.Background(), acct, l, planNow)
+ if _, ok := got[capStorage]; ok {
+ t.Error("storage measured with a zero limit")
+ }
+ if _, ok := errs[capStorage]; ok {
+ t.Error("storage errored with a zero limit")
+ }
+}
+
+func TestMeasureCapsNoStatementIsZero(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct, _ := fx.st.AccountBySqid(fx.sqid)
+ got, errs := fx.srv.measureCaps(context.Background(), acct, measureLimits(), planNow)
+ if errs[capAwakeHours] != nil || errs[capBandwidth] != nil {
+ t.Fatalf("errors = %v", errs)
+ }
+ if m, ok := got[capAwakeHours]; !ok || m.Used != 0 {
+ t.Errorf("awake hours with no statement = %+v, %v, want measured 0", m, ok)
+ }
+}
+
+func TestMeasureCapsStorageDayMissingIsAnError(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct, _ := fx.st.AccountBySqid(fx.sqid)
+ got, errs := fx.srv.measureCaps(context.Background(), acct, measureLimits(), planNow)
+ if errs[capStorage] == nil {
+ t.Error("storage with no day file in 3 days: no error")
+ }
+ if _, ok := got[capStorage]; ok {
+ t.Error("storage measured with no day file")
+ }
+}
+
+func TestMeasureCapsUnsweptStoreIsAnError(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct, _ := fx.st.AccountBySqid(fx.sqid)
+ putStorageDay(t, fx, usage.DayOf(planNow), map[string]usage.AppStorage{
+ fx.sqid + "/a": {StoreBytes: 10, StoreProvisioned: true}, fx.sqid + "/b": {StoreUnswept: true, StoreProvisioned: true},
+ })
+ if _, errs := fx.srv.measureCaps(context.Background(), acct, measureLimits(), planNow); errs[capStorage] == nil {
+ t.Error("an unswept store measured as a known total")
+ }
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index a2c0eaaad..7d06a3500 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1876,8 +1876,15 @@ type page struct {
Msg string // generic message page body
- Flash string // one-shot success notice (cookie-carried across a redirect)
- FlashErr string // one-shot error notice
+ Flash string // one-shot success notice (cookie-carried across a redirect)
+ // PlanNotices are the account's plan warnings (plans 4a), one banner
+ // line each; nil when plans are off or nothing is near a limit.
+ PlanNotices []string
+ // planSeen are the over rows behind PlanNotices when the viewer owns
+ // the account; render records them as notice once the page is written.
+ planSeen []capState
+ planAcctID int64
+ FlashErr string // one-shot error notice
Apps []appRow // account home
Detail *AppView // /a/{sqid}/apps/{app}
@@ -2200,7 +2207,9 @@ func (s *Server) render(w http.ResponseWriter, status int, name string, p page)
w.WriteHeader(status)
if err := templates.ExecuteTemplate(w, name, p); err != nil {
log.Printf("console: render %s: %v", name, err)
+ return
}
+ s.recordBannerNotice(p.planAcctID, p.planSeen, time.Now()) // plans 4a: the banner was served
}
func (s *Server) renderMessage(w http.ResponseWriter, r *http.Request, status int, title, msg string) {
@@ -3355,6 +3364,8 @@ func (s *Server) accountPage(w http.ResponseWriter, r *http.Request, addr, raw s
p.Accounts[i].Seg = preferredSeg(p.Accounts, &p.Accounts[i])
}
p.Nav = "/a/" + url.PathEscape(preferredSeg(p.Accounts, acct))
+ p.PlanNotices, p.planSeen = s.planBanner(acct, role, time.Now())
+ p.planAcctID = acct.ID
return p
}
diff --git a/internal/console/store.go b/internal/console/store.go
index 2f83cc562..17a8619b5 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -545,7 +545,11 @@ func (s *Store) migrate() error {
return err
}
// Door keys' own tables (doorkeys_store.go), for the same reason.
- return s.migrateDoorKeys()
+ if err := s.migrateDoorKeys(); err != nil {
+ return err
+ }
+ // Plans 4a's cap state (plangrace_store.go), for the same reason.
+ return s.migratePlanGrace()
}
// mailCountsBackfillVersion is the user_version this migration stamps. The
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go
index 679c3a742..5e1311baa 100644
--- a/internal/console/store_gate.go
+++ b/internal/console/store_gate.go
@@ -209,6 +209,7 @@ var claimSQLTables = map[string]claimSQLTable{
"memberships": {NonApp: "account membership, keyed by account and address; names no app"},
"invites": {NonApp: "account invites, keyed by account and address; names no app"},
"account_plans": {NonApp: "an account's plan and packs, keyed by account; names no app"},
+ "plan_cap_state": {NonApp: "an account's plan cap warnings and grace clocks, keyed by account; names no app"},
"alert_seen": {NonApp: "operator alert memory, keyed by box, rule and address"},
"claim_loss_pages": {NonApp: "claim recovery page attempts per loss record and condition, and scan progress; no app state or lifecycle authority"},
"move_pages": {NonApp: "the move pass's last page attempt per finding (rule names the host and the move); no app column"},
diff --git a/internal/console/templates/layout.html b/internal/console/templates/layout.html
index 3f4e63949..8d3884f33 100644
--- a/internal/console/templates/layout.html
+++ b/internal/console/templates/layout.html
@@ -591,7 +591,8 @@
</nav>{{end}}
</header>
<main>
-{{end}}
+{{range .PlanNotices}}<p class="banner">{{.}}</p>
+{{end}}{{end}}
{{define "bottom"}}
</main>
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 64854389d..2394aa035 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -301,6 +301,7 @@ worker StartGeoipJobs
worker StartHostReports
worker StartInfraPass
worker StartMailEventPush
+worker StartPlanGracePass
worker StartPlanLimitsPass
worker StartRelay
worker StartRunSweep
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index c439211d0..024e21cd2 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -19,3 +19,5 @@ plan14-root-reads-rootfs-apps-1.tsv 9cf49b684449c9b4c8b2356afa1ec0a7bb6403011de0
plan14-root-reads-edge-request-records-decisions.tsv c6dfb1753f33c96aee894496c2e7e8e9d87cea4f0ff61cb15dbbd8e78ed5021b
plan14-root-reads-edge-request-records.tsv 84cb1e17c2f9cabddcc1e6ed5b39b00ffa70395639b4418c2cc5cf9b444b3eee
plan14-root-reads-data-lifecycle-336.tsv 539ae875b4a089bc6512ae2e047fa9e353e8b760c18312b81ec3400e5e1f6d48
+plan14-root-reads-plans-4a-store.tsv 72dc835c04caf5b2b49cc6ecbfd865bb3123b997ee932e8ab7c0df239935a26b
+plan14-root-reads-plans-4-notices-grace.tsv 43e430a3b3edf9333bfe2c64f24ca9e4c04475dc45ae4983d4e8bcab6a9c0bc4
diff --git a/internal/provision/testdata/plan14-root-reads-plans-4-notices-grace.tsv b/internal/provision/testdata/plan14-root-reads-plans-4-notices-grace.tsv
new file mode 100644
index 000000000..a199b3249
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-plans-4-notices-grace.tsv
@@ -0,0 +1,19 @@
+# Census overlay plans-4-notices-grace, written by census-propose (#369). census-ruling-plans-4-notices-grace, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-plans-4-notices-grace.md.
+# 6 body, 0 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy 6e2f8266b9c9221cdfb17d4fcf80850e42b2d0c2f1d8942f0caf8ec7ab7ce922 auth.go consoleClient.doMultipartHeaders legacy accepted-legacy accepted-legacy;rev3=census-ruling-pro-6214-service-runs;identity=the carlos CLI on the caller's own machine, as that caller: a person, or a server holding a run credential as CARLOS_SERVICE_TOKEN; no box unit runs carlos run;basis=new: consoleClient.doMultipartMethod's body moved here unchanged, plus caller-supplied request headers (a run's Idempotency-Key), set before the content type and the bearer, which they cannot override; its one site, io.ReadAll of the console's response body, is doMultipartMethod's, J4 root-input as that row was;rev3=census-ruling-plans-4-notices-grace;basis=the upload client uses the console client's plan-warning transport (adds a request header, prints response warnings to stderr), the same timeout and no-redirect policy (Astra plans-4a finding 5). No read added. file:ReadAll@1444 ee551468bd7212e7274f9d730b44ce4238b49300b53ee278919f1b5cb78c1b0d
+@legacy 2f0f5af4e34aba5036f0859b93672647d00b20674a5584e138d549b4a0470a77 cmd/console/main.go serve legacy accepted-legacy accepted-legacy;rev3=PROPOSED-scan-demand-revival;basis=Console service wires the optional callback signer and starts the claim-guarded queue worker. The same three data path literals move; it does not add a privileged reader.;rev3=PROPOSED-email-signin;identity=the console (cmd/console serve under console.service, user carlos-console);basis=passes CARLOS_CONSOLE_NAME to NewServer as Config.ConsoleName, the name the console's emails use; the same three /data literals at the same offsets; no read added;rev3=PROPOSED-s3-change-index;identity=the console (cmd/console serve under console.service, user carlos-console);basis=arms the record view when CARLOS_CHANGE_INDEX=read (armChangeIndex) for the run and seed sweeps and starts its backstop loop; the same three /data literals at the same offsets; no read added;rev3=census-ruling-db-region-forward-2;identity=the console (cmd/console serve under console.service, user carlos-console);basis=parses CARLOS_DB_FORWARD (dbForward) into Config.DBForward and builds its http.Server with console.NewHTTPServer, the same two timeouts; the same three /data literals at the same offsets; no read added;rev3=census-ruling-sec-sidecar-create-gate;basis=serve now parses CARLOS_SIDECAR_ACCOUNTS (sidecarAccounts, a pure env parse with log.Fatalf on a bad or empty-list value) before opening anything and passes it into console.Config.SidecarAccounts. No read was added: the same 3 root read sites.;rev3=census-ruling-sec-mail-user-boundary;basis=reads CARLOS_MAIL_USER_BOUNDARY and passes it to mail.NewAWSProvisioner; runs the one-shot boundary sweep behind CARLOS_MAIL_BOUNDARY_SWEEP=1, refused under CARLOS_HOST_CLAIM;rev3=census-ruling-pro-6214-service-runs;basis=the console (cmd/console serve, user carlos-console): reads CARLOS_RUN_KEYS, an environment variable, into Config.RunKeysEnabled; keyed run creates are refused 503 keys_not_ready unless it is on; the same three /data literals; no read added;rev3=census-ruling-plans-4-notices-grace;basis=starts one more claim worker, StartPlanGracePass (plans 4a), beside StartPlanLimitsPass; it returns at once with no plan catalog. No read added. data-literal@4601,data-literal@5702,data-literal@5939 349665021854fbb10f1a091f8b76a066c2ec565c02b001bb9a88cd28e7ab9a20
+@legacy 1e53d248b8ade24b47c7f3a8ae4220ef0d32ee2cc08b593361c4d9846f6e67c3 internal/console/plangrace_store.go Store.PutCapState legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4a-store;basis=root-input; console SQL on its own plan_cap_state table, as its store siblings (J4); plans 4a warnings and grace, which refuse nothing;rev3=census-ruling-plans-4-notices-grace;basis=the upsert keeps notice already recorded for the same episode (same period and first over) instead of overwriting it (Astra plans-4a finding 1). Same table, same one statement; no read added. file:Exec@60 4baf1db18c1032ab1c3345698c685c8bd45deb8a13167b24980e826ec93a08f4
+@legacy ed155196c4385de84da7c752a4ad92fa0636e3b25bb11433d18202aefdb51420 internal/console/plangrace_store.go Store.RecordCapNotice legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4a-store;basis=root-input; console SQL on its own plan_cap_state table, as its store siblings (J4); plans 4a warnings and grace, which refuse nothing;rev3=census-ruling-plans-4-notices-grace;basis=takes the rows as shown and updates only the matching episode (period and first over), never before the first over (Astra plans-4a finding 2). One parameterised UPDATE per shown row on the same table; no read added. file:Exec@222 806dafee3937e3b79a0c306652b08d0d9b19e27115fd576cb66164124fd64df0
+@legacy fcb52ef5b07b838596659cdefd7951e12d75dcbfd561e35a7ad0c32634430e7b internal/console/store.go Store.migrate legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-email-signin;identity=the console (cmd/console serve under console.service, user carlos-console);basis=adds the sessions.method column (default keymail, the backfill) and calls migrateEmailSignin; SQLite DDL on CONSOLE_DB; the existing site moves;rev3=census-ruling-plans-4-notices-grace;basis=calls migratePlanGrace last, which creates the console's own plan_cap_state table (plans 4a). No read added here; the new store units are the plans-4a-store decision. file:Exec@12017,file:Exec@18103 0f08bad811be1e11fa9c1d135fbb5bf99120afa850a8f595a39e6612f7d6c69f
+@legacy 28f23b6734a5104bbb023381c91fc7bd0f16e528a2a959ff8c1faa74cb60a93e internal/console/templates/layout.html external legacy accepted-legacy accepted-legacy;rev3=PROPOSED-console-switcher-filter;basis=Account switcher adds a client-side filter box and a scrolling list; whole embedded template remains frozen as legacy UI input.;rev3=PROPOSED-email-signin;identity=the console (cmd/console serve under console.service, user carlos-console);basis=CSS only: email inputs styled as text inputs and sign-in form labels; whole embedded template remains frozen as legacy UI input;rev3=PROPOSED-console-brand-name;identity=the console (cmd/console serve under console.service, user carlos-console);basis=the tab title and header brand name the deployment ({{.Brand}}, CARLOS_CONSOLE_NAME); no new input.;rev3=census-ruling-plans-4-notices-grace;basis=the account layout renders .PlanNotices as banner lines above main content (plans 4a). No read added. file:external@0 62edee2f256bfe22e8dd026b24e61e3b6f2e1f045a6dda3c301ef16211e2fae6
+auth.go consoleClient.doMultipartHeaders legacy accepted-legacy accepted-legacy;rev3=census-ruling-pro-6214-service-runs;identity=the carlos CLI on the caller's own machine, as that caller: a person, or a server holding a run credential as CARLOS_SERVICE_TOKEN; no box unit runs carlos run;basis=new: consoleClient.doMultipartMethod's body moved here unchanged, plus caller-supplied request headers (a run's Idempotency-Key), set before the content type and the bearer, which they cannot override; its one site, io.ReadAll of the console's response body, is doMultipartMethod's, J4 root-input as that row was;rev3=census-ruling-plans-4-notices-grace;basis=the upload client uses the console client's plan-warning transport (adds a request header, prints response warnings to stderr), the same timeout and no-redirect policy (Astra plans-4a finding 5). No read added. file:ReadAll@1444 ee551468bd7212e7274f9d730b44ce4238b49300b53ee278919f1b5cb78c1b0d
+cmd/console/main.go serve legacy accepted-legacy accepted-legacy;rev3=PROPOSED-scan-demand-revival;basis=Console service wires the optional callback signer and starts the claim-guarded queue worker. The same three data path literals move; it does not add a privileged reader.;rev3=PROPOSED-email-signin;identity=the console (cmd/console serve under console.service, user carlos-console);basis=passes CARLOS_CONSOLE_NAME to NewServer as Config.ConsoleName, the name the console's emails use; the same three /data literals at the same offsets; no read added;rev3=PROPOSED-s3-change-index;identity=the console (cmd/console serve under console.service, user carlos-console);basis=arms the record view when CARLOS_CHANGE_INDEX=read (armChangeIndex) for the run and seed sweeps and starts its backstop loop; the same three /data literals at the same offsets; no read added;rev3=census-ruling-db-region-forward-2;identity=the console (cmd/console serve under console.service, user carlos-console);basis=parses CARLOS_DB_FORWARD (dbForward) into Config.DBForward and builds its http.Server with console.NewHTTPServer, the same two timeouts; the same three /data literals at the same offsets; no read added;rev3=census-ruling-sec-sidecar-create-gate;basis=serve now parses CARLOS_SIDECAR_ACCOUNTS (sidecarAccounts, a pure env parse with log.Fatalf on a bad or empty-list value) before opening anything and passes it into console.Config.SidecarAccounts. No read was added: the same 3 root read sites.;rev3=census-ruling-sec-mail-user-boundary;basis=reads CARLOS_MAIL_USER_BOUNDARY and passes it to mail.NewAWSProvisioner; runs the one-shot boundary sweep behind CARLOS_MAIL_BOUNDARY_SWEEP=1, refused under CARLOS_HOST_CLAIM;rev3=census-ruling-pro-6214-service-runs;basis=the console (cmd/console serve, user carlos-console): reads CARLOS_RUN_KEYS, an environment variable, into Config.RunKeysEnabled; keyed run creates are refused 503 keys_not_ready unless it is on; the same three /data literals; no read added;rev3=census-ruling-plans-4-notices-grace;basis=starts one more claim worker, StartPlanGracePass (plans 4a), beside StartPlanLimitsPass; it returns at once with no plan catalog. No read added. data-literal@4601,data-literal@5702,data-literal@5939 349665021854fbb10f1a091f8b76a066c2ec565c02b001bb9a88cd28e7ab9a20
+internal/console/plangrace_store.go Store.PutCapState legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4a-store;basis=root-input; console SQL on its own plan_cap_state table, as its store siblings (J4); plans 4a warnings and grace, which refuse nothing;rev3=census-ruling-plans-4-notices-grace;basis=the upsert keeps notice already recorded for the same episode (same period and first over) instead of overwriting it (Astra plans-4a finding 1). Same table, same one statement; no read added. file:Exec@60 4baf1db18c1032ab1c3345698c685c8bd45deb8a13167b24980e826ec93a08f4
+internal/console/plangrace_store.go Store.RecordCapNotice legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4a-store;basis=root-input; console SQL on its own plan_cap_state table, as its store siblings (J4); plans 4a warnings and grace, which refuse nothing;rev3=census-ruling-plans-4-notices-grace;basis=takes the rows as shown and updates only the matching episode (period and first over), never before the first over (Astra plans-4a finding 2). One parameterised UPDATE per shown row on the same table; no read added. file:Exec@222 806dafee3937e3b79a0c306652b08d0d9b19e27115fd576cb66164124fd64df0
+internal/console/store.go Store.migrate legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-email-signin;identity=the console (cmd/console serve under console.service, user carlos-console);basis=adds the sessions.method column (default keymail, the backfill) and calls migrateEmailSignin; SQLite DDL on CONSOLE_DB; the existing site moves;rev3=census-ruling-plans-4-notices-grace;basis=calls migratePlanGrace last, which creates the console's own plan_cap_state table (plans 4a). No read added here; the new store units are the plans-4a-store decision. file:Exec@12017,file:Exec@18103 0f08bad811be1e11fa9c1d135fbb5bf99120afa850a8f595a39e6612f7d6c69f
+internal/console/templates/layout.html external legacy accepted-legacy accepted-legacy;rev3=PROPOSED-console-switcher-filter;basis=Account switcher adds a client-side filter box and a scrolling list; whole embedded template remains frozen as legacy UI input.;rev3=PROPOSED-email-signin;identity=the console (cmd/console serve under console.service, user carlos-console);basis=CSS only: email inputs styled as text inputs and sign-in form labels; whole embedded template remains frozen as legacy UI input;rev3=PROPOSED-console-brand-name;identity=the console (cmd/console serve under console.service, user carlos-console);basis=the tab title and header brand name the deployment ({{.Brand}}, CARLOS_CONSOLE_NAME); no new input.;rev3=census-ruling-plans-4-notices-grace;basis=the account layout renders .PlanNotices as banner lines above main content (plans 4a). No read added. file:external@0 62edee2f256bfe22e8dd026b24e61e3b6f2e1f045a6dda3c301ef16211e2fae6
+@coverage . 52254ae8c81593fbb774e758140a654216b7629cd63704c5a2efe6b168da240a
+@coverage cmd/console 7346c4e7936cf939707bf66a1ddb609622572b17abb3571c404bd1aac9742c14
+@coverage internal/console 72005c420b22f2e42309aacf124f5dc5df015291d3e8527d83ca6bf342dc73d9
+@coverage internal/console/templates 628dd940845d129612b0b1ae59852e65b96c8f6e15693fcac7239610a7c8d132
+@coverage internal/usage 6134ad82fbb3f6806661c55bb559ed47b6a85ad280647b67a7d4675aa4e68b99
diff --git a/internal/provision/testdata/plan14-root-reads-plans-4a-store.tsv b/internal/provision/testdata/plan14-root-reads-plans-4a-store.tsv
new file mode 100644
index 000000000..dfdd1db71
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-plans-4a-store.tsv
@@ -0,0 +1,13 @@
+# Census overlay plans-4a-store, written by hand: six new console store units (SQL on the console's own plan_cap_state and mail_sender_counts tables), a decision. census-ruling-plans-4a-store; the card is docs/superpowers/notes/census-proposal-plans-4-notices-grace.md.
+@legacy 3bdef10f3fc3277287387a115a90e1549ffa3f2fe614ae7e7d6ae36acb9f84b8 internal/console/mailcounts.go Store.AccountSends legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4a-store;basis=root-input; console SQL on its own mail_sender_counts table, as its store siblings (J4); plans 4a warnings and grace, which refuse nothing file:QueryRowContext@109 901f89c947b45dba210d5f860d96f30696744afe120bc5a66fe048c976a1d691
+@legacy 1306de09cff6b65ee627e37b67b62102f0be4536997f9794c69dd8ce1770d0bc internal/console/plangrace_store.go Store.CapStates legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4a-store;basis=root-input; console SQL on its own plan_cap_state table, as its store siblings (J4); plans 4a warnings and grace, which refuse nothing file:Query@79 12c6c0df016be8a16a97da7f7307f3aeaf116605d688857977d0d59fffe5a1c1
+@legacy 41a55882792ca279152e7747ea35adf89efc413a53b8dd42c28c0c85ca7dd1bf internal/console/plangrace_store.go Store.DeleteCapState legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4a-store;basis=root-input; console SQL on its own plan_cap_state table, as its store siblings (J4); plans 4a warnings and grace, which refuse nothing file:Exec@76 641e6b8a6d08f0befb880f2c04cf506c1b95bb3cbd2a3c86e19cf5512283e75b
+@legacy e6751eb3b2841ae63c247636266739f285057766bc7fc72beba2ecb1926e7a4a internal/console/plangrace_store.go Store.PutCapState legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4a-store;basis=root-input; console SQL on its own plan_cap_state table, as its store siblings (J4); plans 4a warnings and grace, which refuse nothing file:Exec@60 b7c6bf1f1bf4a5587cab0a23836e4433ad367bd2e148aa53fdbc0f522f0aaa85
+@legacy 514219eedb6fe2f8ab6ba9ebc3c5ac9b7e6ec7322aaf0d2ffdc330814bad3fff internal/console/plangrace_store.go Store.RecordCapNotice legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4a-store;basis=root-input; console SQL on its own plan_cap_state table, as its store siblings (J4); plans 4a warnings and grace, which refuse nothing file:Exec@285 42f630f5adc4ad617f6201c2d407e867ecab5599488468e6cfbc6cb4916a8606
+@legacy b77e8dee37604d47c32229a191b8e663ad1995f9ad3f4b7b2d63e9e71a92f4f2 internal/console/plangrace_store.go Store.migratePlanGrace legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4a-store;basis=root-input; console SQL on its own plan_cap_state table, as its store siblings (J4); plans 4a warnings and grace, which refuse nothing file:Exec@54 ccf9ead5bb0aa421863a9d379a543ff26ffe41e1b268cba0b6259137a1b5eac8
+internal/console/mailcounts.go Store.AccountSends legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4a-store;basis=root-input; console SQL on its own mail_sender_counts table, as its store siblings (J4); plans 4a warnings and grace, which refuse nothing file:QueryRowContext@109 901f89c947b45dba210d5f860d96f30696744afe120bc5a66fe048c976a1d691
+internal/console/plangrace_store.go Store.CapStates legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4a-store;basis=root-input; console SQL on its own plan_cap_state table, as its store siblings (J4); plans 4a warnings and grace, which refuse nothing file:Query@79 12c6c0df016be8a16a97da7f7307f3aeaf116605d688857977d0d59fffe5a1c1
+internal/console/plangrace_store.go Store.DeleteCapState legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4a-store;basis=root-input; console SQL on its own plan_cap_state table, as its store siblings (J4); plans 4a warnings and grace, which refuse nothing file:Exec@76 641e6b8a6d08f0befb880f2c04cf506c1b95bb3cbd2a3c86e19cf5512283e75b
+internal/console/plangrace_store.go Store.PutCapState legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4a-store;basis=root-input; console SQL on its own plan_cap_state table, as its store siblings (J4); plans 4a warnings and grace, which refuse nothing file:Exec@60 b7c6bf1f1bf4a5587cab0a23836e4433ad367bd2e148aa53fdbc0f522f0aaa85
+internal/console/plangrace_store.go Store.RecordCapNotice legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4a-store;basis=root-input; console SQL on its own plan_cap_state table, as its store siblings (J4); plans 4a warnings and grace, which refuse nothing file:Exec@285 42f630f5adc4ad617f6201c2d407e867ecab5599488468e6cfbc6cb4916a8606
+internal/console/plangrace_store.go Store.migratePlanGrace legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4a-store;basis=root-input; console SQL on its own plan_cap_state table, as its store siblings (J4); plans 4a warnings and grace, which refuse nothing file:Exec@54 ccf9ead5bb0aa421863a9d379a543ff26ffe41e1b268cba0b6259137a1b5eac8
diff --git a/internal/usage/statement.go b/internal/usage/statement.go
index 7822bb876..668ede1f1 100644
--- a/internal/usage/statement.go
+++ b/internal/usage/statement.go
@@ -76,3 +76,18 @@ func CreateDayObject(ctx context.Context, s release.Store, key string, v any) (b
}
return true, nil
}
+
+// GetStatement reads an account's month statement. A month with none yet
+// is os.ErrNotExist, passed through for the caller to read as "nothing
+// used yet".
+func GetStatement(ctx context.Context, s release.Store, acct, month string) (*Statement, error) {
+ raw, _, err := s.Get(ctx, StatementKey(acct, month))
+ if err != nil {
+ return nil, err
+ }
+ var st Statement
+ if err := json.Unmarshal(raw, &st); err != nil {
+ return nil, fmt.Errorf("usage: %s: %w", StatementKey(acct, month), err)
+ }
+ return &st, nil
+}
diff --git a/internal/usage/statement_test.go b/internal/usage/statement_test.go
new file mode 100644
index 000000000..8226a0679
--- /dev/null
+++ b/internal/usage/statement_test.go
@@ -0,0 +1,26 @@
+package usage
+
+import (
+ "context"
+ "errors"
+ "os"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestGetStatementRoundTrip(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ want := Statement{V: 1, Account: "abc", Month: "2026-10", Meters: map[string]float64{MeterInstanceHours: 12.5}, CoveredDays: 3, DaysInMonth: 31}
+ if err := UpsertStatement(ctx, s, want); err != nil {
+ t.Fatal(err)
+ }
+ got, err := GetStatement(ctx, s, "abc", "2026-10")
+ if err != nil || got.Meters[MeterInstanceHours] != 12.5 || got.Account != "abc" || got.Month != "2026-10" {
+ t.Fatalf("GetStatement = %+v, %v", got, err)
+ }
+ if _, err := GetStatement(ctx, s, "abc", "2026-09"); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("missing month = %v, want os.ErrNotExist", err)
+ }
+}
diff --git a/planwarnings.go b/planwarnings.go
new file mode 100644
index 000000000..3b0802034
--- /dev/null
+++ b/planwarnings.go
@@ -0,0 +1,46 @@
+package main
+
+import (
+ "fmt"
+ "io"
+ "net/http"
+ "sync"
+)
+
+// planWarningTransport tells the console this CLI prints plan warnings,
+// and prints each warning the console sends back, once per run (plans 4a).
+// The console counts a warning an owner's CLI printed as notice received,
+// so the request header is a promise this transport keeps.
+type planWarningTransport struct {
+ base http.RoundTripper
+ out io.Writer
+
+ mu sync.Mutex
+ seen map[string]bool
+}
+
+func (t *planWarningTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ req = req.Clone(req.Context())
+ req.Header.Set("X-Carlos-Plan-Warnings", "1")
+ base := t.base
+ if base == nil {
+ base = http.DefaultTransport
+ }
+ resp, err := base.RoundTrip(req)
+ if err != nil {
+ return resp, err
+ }
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ for _, w := range resp.Header.Values("X-Carlos-Plan-Warning") {
+ if t.seen == nil {
+ t.seen = map[string]bool{}
+ }
+ if t.seen[w] {
+ continue
+ }
+ t.seen[w] = true
+ fmt.Fprintf(t.out, "warning: %s\n", w)
+ }
+ return resp, nil
+}
diff --git a/planwarnings_test.go b/planwarnings_test.go
new file mode 100644
index 000000000..f1189a029
--- /dev/null
+++ b/planwarnings_test.go
@@ -0,0 +1,75 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "io"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+type stubRT struct {
+ got []http.Header
+}
+
+func (s *stubRT) RoundTrip(req *http.Request) (*http.Response, error) {
+ s.got = append(s.got, req.Header.Clone())
+ h := http.Header{}
+ h.Add("X-Carlos-Plan-Warning", "this account has used 4 of 5 apps and instances")
+ return &http.Response{StatusCode: 200, Header: h, Body: io.NopCloser(strings.NewReader("{}")), Request: req}, nil
+}
+
+func TestPlanWarningTransportPrintsOnce(t *testing.T) {
+ var out bytes.Buffer
+ stub := &stubRT{}
+ tr := &planWarningTransport{base: stub, out: &out}
+ for i := 0; i < 2; i++ {
+ req, _ := http.NewRequest(http.MethodGet, "http://console.example/api/cli/apps", nil)
+ resp, err := tr.RoundTrip(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ }
+ if got := out.String(); got != "warning: this account has used 4 of 5 apps and instances\n" {
+ t.Fatalf("printed %q, want the warning once", got)
+ }
+ for _, h := range stub.got {
+ if h.Get("X-Carlos-Plan-Warnings") != "1" {
+ t.Fatalf("request did not declare that this CLI prints warnings: %v", h)
+ }
+ }
+}
+
+// Finding 5: the upload and stream clients carry the warning transport too.
+func TestUploadAndStreamClientsPrintWarnings(t *testing.T) {
+ var seen []string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ seen = append(seen, r.Header.Get("X-Carlos-Plan-Warnings"))
+ w.Header().Add("X-Carlos-Plan-Warning", "this account has used "+r.URL.Path)
+ w.WriteHeader(200)
+ }))
+ defer srv.Close()
+ var out bytes.Buffer
+ c := newConsoleClient(srv.URL, "tok")
+ c.warn.out = &out
+ if _, _, err := c.doMultipart(context.Background(), "/up", func(*multipart.Writer) error { return nil }); err != nil {
+ t.Fatal(err)
+ }
+ res, err := c.doStream(context.Background(), http.MethodGet, "/down", nil, -1, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+ if got := out.String(); !strings.Contains(got, "used /up") || !strings.Contains(got, "used /down") {
+ t.Fatalf("printed %q, want both warnings", got)
+ }
+ for _, h := range seen {
+ if h != "1" {
+ t.Fatalf("a request did not declare that this CLI prints warnings: %q", seen)
+ }
+ }
+}