carlos / platform Public

plans 4a: warnings, grace and notice plan

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 6d6c8b6c39b976e98b39dd1e2c98a0a76eafddca parent 8c899da
1 file changed, +312 −0
  • docs/superpowers/plans/2026-10-25-plans-4a-warnings-and-grace.md +312 −0

CI failed — run details

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..1c96a0b0b
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-25-plans-4a-warnings-and-grace.md
@@ -0,0 +1,312 @@
+# 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`) and goes through copy review before merge. 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 copy review:
+ - `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
+
+- [ ] Extract every `planNoticeCopy` string with an example rendering of each, then run the copy-review skill. Apply the result verbatim and re-run the Task 3 to Task 5 tests.
+- [ ] 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.
+ - Ask Paul to approve the card.
+- [ ] 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. Copy is approved and the census card is approved. CI is green after merging current main, and Astra's whole-branch review has no open Critical or Important finding.