carlos / platform Public

plan: console Protection tab (spec approved by Paul)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 381294a6f0b52128ae898397bf7c7274939331ae parent f2b88b4
2 files changed, +385 −1
  • docs/superpowers/plans/2026-10-30-console-protection-tab.md +384 −0
  • docs/superpowers/specs/2026-10-30-console-protection-tab-design.md +1 −1
diff --git a/docs/superpowers/plans/2026-10-30-console-protection-tab.md b/docs/superpowers/plans/2026-10-30-console-protection-tab.md
new file mode 100644
index 000000000..900b093c8
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-30-console-protection-tab.md
@@ -0,0 +1,384 @@
+# Console Protection Tab 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:** A per-app Protection tab and an operator page that say plainly how much bad traffic edge protection caught.
+
+**Architecture:** The edge counts protection checks and matches into the per-host usage counters it already flushes every 5 minutes (`usage/edge/<box>/days/<date>.json`), plus a per-day group tally and the box's protection mode. The console reads those day objects (root and fleet boxes) through the settled-day cache, sums them per app over whole UTC days, and renders a tab, an operator page and a JSON door.
+
+**Tech Stack:** Go, `html/template`, the console's existing store and cache layers.
+
+**Spec:** `docs/superpowers/specs/2026-10-30-console-protection-tab-design.md` (rev 2, approved by Paul 2026-10-30). Read it first; this plan argues from it.
+
+## Global Constraints
+
+- No new storage writes. Counters ride the existing `usage.UpsertEdgeDay` 5-minute conditional put; a flush with no rows and no group tallies writes nothing (spec §3.3).
+- Every new JSON field on stored objects is additive and `omitempty`; an object written before them parses with them zero (spec §5).
+- Burst-mode rules (`edgeguard.ModeBurst`, the `probe/admin` group) are never counted as caught (spec §2).
+- The share's denominator is `guard_checked`, never `Requests` (spec §3.1).
+- A host's protection counters reset when its owner (account, app) changes; the daily group tally is keyed by host, account and app (spec §3.1).
+- Windows are whole UTC days: 7 (default) or 30, including today (spec §3.2).
+- A fleet box's row counts only when its account is the fleet's owning account (`registry.Fleet.Account`). A fleet box writes what it likes under its own prefix; its rows may vouch only for its own account.
+- Group tally: at most 32 keys per host-owner-day; past that, counts go to `other` (spec §3.1).
+- Copy: every user-facing string comes from the approved deck `docs/superpowers/plans/2026-10-30-console-protection-tab-copy.md`, verbatim. No em dashes. Never "exactly". No tenant names anywhere.
+- Provider-neutral: only `release.Store`.
+- Tests: run only the touched packages locally, with `-run` where possible (`go test ./internal/usage/ ./internal/edge/ -run 'Guard|EdgeDay'`). CI runs the full suite. Leave `GOCACHE` at its default.
+
+## Review Focus
+
+1. **A request a tunnel delivered, or one backhauled over a verified hop.** Expected: counted once fleet-wide. Counting sits exactly where `out.guard` is set (Task 2), so it follows the guard's own rule; Task 2's test pins the tunnel case. If the hop test shows the guard runs on both legs, that is a pre-existing double count in request records too: report it on the branch, do not fix it here.
+2. **A fleet box writing rows for an account that does not own its fleet.** Expected: those rows are ignored. Task 3's test pins it.
+3. **A host that changed owner mid-day.** Expected: the new owner sees only their own counts, and the old owner keeps theirs for the earlier hours and their own group tally. Tasks 1 and 4 pin it.
+4. **A window reaching back before the release that adds counting.** Expected: "counting started on", never "nothing caught". Task 4 pins it.
+5. **An edge day over the cache's body limit or unreadable.** Expected: the read fails visibly (an error on the page), never a short total presented as complete. Task 3 pins it, following `rateLimitCounts`'s rule.
+
+---
+
+### Task 1: Stored shape: protection counters on the edge day
+
+**Files:**
+- Modify: `internal/usage/edge.go`
+- Test: `internal/usage/edge_test.go`
+- Modify (callers of the changed signature): `internal/host/usage_loop.go`, any test calling `UpsertEdgeDay` or `AddDeltas` (`grep -rn 'UpsertEdgeDay\|AddDeltas' internal`)
+
+**Interfaces:**
+- Produces:
+ - `EdgeRow` fields `GuardChecked int64 \`json:"guard_checked,omitempty"\``, `GuardWatch int64 \`json:"guard_watch,omitempty"\``, `GuardBlock int64 \`json:"guard_block,omitempty"\``. `SetOwner` resets these three alongside the rate counters.
+ - `type GuardTally struct { Host, Account, App string; Groups map[string]int64 }` with JSON keys `host`, `account`, `app`, `groups`.
+ - `func GuardKey(host, account, app string) string` returning `host + "|" + account + "|" + app`.
+ - `const GuardGroupCap = 32`, `const GuardGroupOther = "other"`.
+ - `func (t *GuardTally) Add(group string, n int64)`: adds to `group`, or to `GuardGroupOther` when `group` is new and the map already holds `GuardGroupCap` keys (`other` counts toward the cap).
+ - `EdgeDay` fields `Guard map[string]GuardTally \`json:"guard,omitempty"\`` (keyed by `GuardKey`) and `GuardModes map[string][]string \`json:"guard_modes,omitempty"\`` (hour label to sorted, de-duplicated modes).
+ - `type EdgeFlush struct { Rows map[string]EdgeRow; Guard map[string]GuardTally; Mode string }`.
+ - `func (d *EdgeDay) AddFlush(hour string, f EdgeFlush)`: replaces `AddDeltas`. Folds rows as `AddDeltas` did plus the three guard counters; merges each tally via `Add`; when `f.Mode != ""` and the flush carries any row, adds `f.Mode` to `GuardModes[hour]`.
+ - `func UpsertEdgeDay(ctx context.Context, s release.Store, box string, now time.Time, f EdgeFlush) error`: writes nothing when `len(f.Rows) == 0 && len(f.Guard) == 0`.
+
+- [ ] **Step 1: Write the failing tests** in `internal/usage/edge_test.go`:
+ - `TestAddFlushSumsGuardCounters`: two flushes for host `shop.example.com` (account `acct1`, app `shop`), each `GuardChecked: 10, GuardWatch: 2, GuardBlock: 1`, into hour `"09"`. Want row `GuardChecked 20, GuardWatch 4, GuardBlock 2`.
+ - `TestSetOwnerResetsGuardCounters`: a row with `GuardChecked 5, GuardWatch 3, GuardBlock 1` owned by `acct1/shop`, then `SetOwner("acct2", "blog")`. Want all three zero; `Requests` unchanged.
+ - `TestGuardTallyCapsAtOther`: add 40 distinct groups `g00`..`g39` with 1 each. Want `len(Groups) == 32`, `Groups["other"] == 40 - 31` (31 named plus `other`), and the total of all values 40.
+ - `TestGuardTallyKeyedByOwner`: a flush with tally for `GuardKey("shop.example.com","acct1","shop")` `{"probe/wordpress": 3}`, then one for `GuardKey("shop.example.com","acct2","blog")` `{"probe/wordpress": 2}`. Want two entries, 3 and 2: nothing erased.
+ - `TestGuardModesPerHour`: flush with one row and `Mode: "catalogue"` in hour `"09"`, then `Mode: "block"` in `"09"`, then `Mode: "catalogue"` with no rows in `"10"`. Want `GuardModes == {"09": ["block","catalogue"]}`.
+ - `TestUpsertEdgeDayEmptyFlushWritesNothing`: `EdgeFlush{Mode: "watch"}` against a store that fails the test on any `Put`.
+ - `TestEdgeDayOldShapeParses`: unmarshal a day JSON with no guard fields. Want zero counters, nil `Guard` and `GuardModes`.
+
+- [ ] **Step 2: Run them and see them fail**
+
+Run: `go test ./internal/usage/ -run 'Guard|AddFlush|EmptyFlush|OldShape'`
+Expected: FAIL (undefined fields and functions).
+
+- [ ] **Step 3: Implement the Interfaces above in `internal/usage/edge.go`**, and update `internal/host/usage_loop.go` and the tests that call `AddDeltas`/`UpsertEdgeDay` to the new signatures (the drain argument becomes `func() usage.EdgeFlush` in Task 2; in this task wrap the existing map as `usage.EdgeFlush{Rows: drain()}` so the build stays green).
+
+- [ ] **Step 4: Run the tests and see them pass**
+
+Run: `go test ./internal/usage/ ./internal/host/ -run 'Guard|AddFlush|EmptyFlush|OldShape|EdgeDay|UsageFlush'`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add internal/usage/ internal/host/usage_loop.go
+git commit -m "usage: protection counters, group tally and modes on the edge day"
+```
+
+---
+
+### Task 2: Counting at the edge
+
+**Files:**
+- Modify: `internal/edge/usagemeter.go`, `internal/edge/guard.go`, `internal/edge/edge.go` (the ServeHTTP observer defer, around the `out.guard = e.newGuardState()` site and the `m.Record(...)` call), `internal/host/usage_loop.go`, `internal/host/agent.go:1074`
+- Test: `internal/edge/usagemeter_test.go`, `internal/edge/guard_usage_test.go` (new)
+
+**Interfaces:**
+- Consumes: Task 1's `EdgeFlush`, `GuardTally`, `GuardKey`, `EdgeRow` guard fields.
+- Produces:
+ - `func (m guardMode) String() string`: `"catalogue"`, `"off"`, `"watch"`, `"block"`.
+ - `func (u *UsageMeter) SetGuardMode(mode string)`.
+ - `func (u *UsageMeter) RecordGuard(rt registry.Route, rule *edgeguard.Rule, blocked bool)`: `GuardChecked++` always; when `rule != nil && rule.Mode != edgeguard.ModeBurst`, `GuardBlock++` or `GuardWatch++` and the tally for `GuardKey(rt.Host, release.RouteAccount(rt), rt.App)` gets `string(rule.Tier)+"/"+rule.Group` plus 1. Calls `SetOwner` first, as the other Record methods do.
+ - `func (u *UsageMeter) Drain() usage.EdgeFlush`: rows, tallies and the mode set by `SetGuardMode`; resets rows and tallies.
+ - `func usageLoop(drain func() usage.EdgeFlush, am *analytics.Meter)` and `usageFlush(..., drain func() usage.EdgeFlush, ...)`.
+ - `(*Edge).EnableUsage(m)` calls `m.SetGuardMode(e.guard.String())` when `m != nil`.
+
+- [ ] **Step 1: Write the failing tests**
+ - `internal/edge/usagemeter_test.go`, `TestRecordGuardCounts`: a watch on a `probe/wordpress` rule, a block on a `hard/secrets` rule, a check with no rule, and a match on a `ModeBurst` `probe/admin` rule. Want row `GuardChecked 4, GuardWatch 1, GuardBlock 1`; tally `{"probe/wordpress":1,"hard/secrets":1}` with no `probe/admin` key.
+ - `internal/edge/guard_usage_test.go`, through a real `Edge` serving the real catalogue (production wiring, as `guard_test.go` builds one), with a `UsageMeter` enabled:
+ - `TestGuardUsageCountsAProbe`: `GET /wp-login.php` on a routed host. Want `GuardChecked 1, GuardWatch 1`, tally `probe/wordpress: 1`, flush `Mode "catalogue"`.
+ - `TestGuardUsagePlainRequestCountsChecked`: `GET /`. Want `GuardChecked 1`, no watch, no tally.
+ - `TestGuardUsageBurstRuleNotCaught`: `GET /admin`. Want `GuardChecked 1, GuardWatch 0`, no tally.
+ - `TestGuardUsageTunnelDeliveredNotCounted`: the same probe arriving as a tunnel delivery (the context `fromTunnel` reads, as `guard_test.go` sets it). Want `GuardChecked 0`.
+ - `TestGuardUsageCountsWithRecordsOff`: no request recorder enabled. Want the probe still counted.
+ - `TestGuardUsageModeOff`: an Edge with `CARLOS_EDGE_PROTECT=off`. Want `GuardChecked 0` and flush `Mode "off"`.
+ - Review Focus 1: `TestGuardUsageHopCountsOnce`: a probe backhauled over a verified hop (the setup `homemap` tests use). Want the two edges' `GuardChecked` sum to 1. If it is 2, mark the test `t.Skip` with a comment naming the pre-existing double count and record it on the branch (amadan discussion); do not change the guard's rule.
+
+- [ ] **Step 2: Run them and see them fail**
+
+Run: `go test ./internal/edge/ -run 'RecordGuard|GuardUsage'`
+Expected: FAIL (undefined `RecordGuard`, `SetGuardMode`).
+
+- [ ] **Step 3: Implement.** In the observer defer, beside `m.Record(...)` and under the same `m != nil` check but not under `!out.unbilled`, call `m.RecordGuard(up.route, rule, blocked)` when `out.guard != nil`, taking `rule` and `blocked` from `out.guard.verdict` (nil rule when there is no verdict). One call per request, so a request cannot be counted twice on one box. Update `usageLoop`/`usageFlush`/`agent.go` to the `EdgeFlush` drain.
+
+- [ ] **Step 4: Run the tests and see them pass**
+
+Run: `go test ./internal/edge/ ./internal/host/ -run 'RecordGuard|GuardUsage|UsageMeter|UsageFlush|Guard'`
+Expected: PASS (or the hop test skipped with its note).
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add internal/edge/ internal/host/
+git commit -m "edge: count protection checks and matches into the usage meter"
+```
+
+---
+
+### Task 3: One edge-day reader for root and fleet boxes
+
+**Files:**
+- Create: `internal/console/edgedays.go`
+- Modify: `internal/console/usagedays.go` (`usageDayDate`), `internal/console/apiinstances_ratelimit.go` (`rateLimitCounts`)
+- Test: `internal/console/edgedays_test.go`, `internal/console/usagedays_test.go`
+
+**Interfaces:**
+- Consumes: Task 1's `usage.EdgeDay`.
+- Produces:
+ - `type edgeDaySource struct { Day usage.EdgeDay; Fleet string; FleetAccount string }` (`Fleet == ""` for a root box).
+ - `func (s *Server) readEdgeDays(ctx context.Context, st release.Store, dates []string) ([]edgeDaySource, error)`: lists root boxes (`usage.EdgeBoxesPrefix`) and, for every fleet from the registry (`ListFleets`, as `fleetMeterBoxes` opens it), the boxes under `fleets/<name>/usage/edge/`; reads each box's day for each date through `st`. A missing object is skipped; any other read or parse error fails the call.
+ - `func rowCounts(src edgeDaySource, row usage.EdgeRow, acct, app string) bool`: true when the row is the app's (account defaulting to `release.OpsAccount` when empty, as `rateLimitCounts` does) and, for a fleet source, the row's account equals `FleetAccount`.
+ - `usageDayDate` recognises `fleets/<fleet>/usage/edge/<box>/days/<date>.json`.
+ - `rateLimitCounts` reads through `readEdgeDays` and `rowCounts`; its results for root boxes are unchanged.
+
+- [ ] **Step 1: Write the failing tests** in `internal/console/edgedays_test.go` against a memory store and a registry with fleet `f1` owned by `acct1`:
+ - `TestReadEdgeDaysRootAndFleet`: one root box and one `f1` box each with a day for `2026-11-02`. Want two sources, the fleet one with `Fleet "f1"`, `FleetAccount "acct1"`.
+ - `TestRowCountsRefusesForeignFleetRow` (Review Focus 2): a row in `f1`'s day claiming `acct2/shop`. Want `rowCounts(src, row, "acct2", "shop") == false`.
+ - `TestReadEdgeDaysParseErrorFails` (Review Focus 5): a root day holding `{not json`. Want an error, not a short result.
+ - `TestRateLimitCountsIncludesFleetBoxes`: a fleet row for `acct1`'s host with `RateShed 4`. Want `Shed 4`.
+ - In `usagedays_test.go`, `TestUsageDayDateFleetEdgeDay`: `fleets/f1/usage/edge/box-a/days/2026-11-02.json` gives `("2026-11-02", true)`; `fleets/f1/usage/edge/box-a/x/days/2026-11-02.json` gives `false`.
+
+- [ ] **Step 2: Run them and see them fail**
+
+Run: `go test ./internal/console/ -run 'ReadEdgeDays|RowCounts|RateLimitCounts|UsageDayDate'`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement the Interfaces above.**
+
+- [ ] **Step 4: Run the tests and see them pass**
+
+Run: `go test ./internal/console/ -run 'ReadEdgeDays|RowCounts|RateLimit|UsageDay'`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add internal/console/edgedays.go internal/console/edgedays_test.go internal/console/usagedays.go internal/console/usagedays_test.go internal/console/apiinstances_ratelimit.go
+git commit -m "console: one edge-day reader for root and fleet boxes; fleet rows vouch only for their own account"
+```
+
+---
+
+### Task 4: Summing a window
+
+**Files:**
+- Create: `internal/console/protection.go`
+- Test: `internal/console/protection_test.go`
+
+**Interfaces:**
+- Consumes: Task 3's `edgeDaySource`, `rowCounts`.
+- Produces:
+ - `type protectionDay struct { Date string; Checked, Watch, Block int64; Partial, NotCounted bool }` (JSON `date`, `checked`, `watch`, `block`, `partial`, `not_counted`).
+ - `type protectionSummary struct { From, To string; Days []protectionDay; Checked, Watch, Block int64; Groups map[string]int64; Modes []string; CountingSince string; Partial bool }` (JSON snake_case: `from`, `to`, `days`, `checked`, `watch`, `block`, `groups`, `modes`, `counting_since`, `partial`). `CountingSince` is `""` when no box in the window counted.
+ - `func protectionDates(days int, now time.Time) []string`: the last `days` UTC dates including today, oldest first. `days` other than 7 or 30 is read as 7.
+ - `func sumProtection(srcs []edgeDaySource, dates []string, acct, app string) protectionSummary`: per-app (`acct`, `app` non-empty) totals.
+ - `func sumProtectionAll(srcs []edgeDaySource, dates []string) (protectionSummary, []protectionAppRow)` with `type protectionAppRow struct { Account, App string; Checked, Watch, Block int64 }`, sorted by `Watch+Block` descending, then account, then app. Fleet rows are included only where `rowCounts` would accept them for their own account.
+
+ Rules, from spec §3.1:
+ - An hour counts for the app when some box has a row for it that `rowCounts` accepts.
+ - `CountingSince` is the date of the first hour in the window where any accepted row has `GuardChecked > 0`. That day is `Partial`.
+ - A day after `CountingSince` with traffic for the app (`Requests > 0`) in an hour where every accepted row has `GuardChecked == 0` is `NotCounted`. A day before `CountingSince` with traffic is `NotCounted`.
+ - `Summary.Partial` is true when any day is `Partial` or `NotCounted`.
+ - `Modes` is the sorted union of `GuardModes` over the hours where the app had accepted rows, on the boxes that had them.
+ - `Groups` sums the app's tallies (`Account`, `App` matching, and for fleet sources the fleet's account) over the window's dates.
+
+- [ ] **Step 1: Write the failing tests** in `internal/console/protection_test.go`, building `edgeDaySource` values in memory, app `acct1/shop` on host `shop.example.com`:
+ - `TestProtectionDatesWholeDays`: `protectionDates(7, 2026-11-05T13:00Z)` is `2026-10-30` to `2026-11-05`, 7 entries; `protectionDates(9, …)` gives 7.
+ - `TestSumProtectionTotals`: two boxes, hours `"09"` and `"10"` on `2026-11-05`, rows checked 100/50, watch 6/2, block 0/1, tallies `probe/wordpress: 5`, `hard/secrets: 4`. Want `Checked 150, Watch 8, Block 1`, `Groups {"probe/wordpress":5,"hard/secrets":4}`.
+ - `TestSumProtectionCountingSince` (Review Focus 4): `2026-11-03` has rows with `Requests 40, GuardChecked 0`; `2026-11-04` hour `"10"` is the first with `GuardChecked > 0`. Want `CountingSince "2026-11-04"`, `2026-11-03 NotCounted`, `2026-11-04 Partial`, `Summary.Partial true`.
+ - `TestSumProtectionNothingCaught`: all rows `GuardChecked > 0`, zero watch and block, window after counting began. Want `Watch 0, Block 0, Partial false`, `CountingSince` set.
+ - `TestSumProtectionOwnerChange` (Review Focus 3): host re-owned to `acct2/blog` at hour `"12"`, the stored rows reflecting `SetOwner`'s reset, tallies keyed per owner. Want `acct1/shop` to see only its hours and tally, `acct2/blog` only its own.
+ - `TestSumProtectionModes`: hours with `GuardModes {"09":["catalogue"],"10":["block","catalogue"]}`. Want `Modes ["block","catalogue"]`.
+ - `TestSumProtectionAllSortsApps`: three apps with caught 5, 12, 0. Want rows ordered 12, 5, 0 and summary totals the sum.
+
+- [ ] **Step 2: Run them and see them fail**
+
+Run: `go test ./internal/console/ -run 'Protection'`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement the Interfaces above.**
+
+- [ ] **Step 4: Run the tests and see them pass**
+
+Run: `go test ./internal/console/ -run 'Protection'`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add internal/console/protection.go internal/console/protection_test.go
+git commit -m "console: sum protection counts over whole UTC days"
+```
+
+---
+
+### Task 5: Copy deck and its review
+
+**Files:**
+- Create: `docs/superpowers/plans/2026-10-30-console-protection-tab-copy.md`
+- Create: `internal/console/approved_protection_copy_test.go`
+
+**Interfaces:**
+- Produces: deck rows `PT-C01`.. with approved text; `protectionCopyBuilt map[string]bool` (empty in this task; Tasks 6 and 7 add their ids); test `TestProtectionCopyDeckIsApprovedAndApplied`.
+
+The deck follows the analytics on-ramp deck's rules verbatim (`docs/superpowers/plans/2026-10-26-analytics-onramp-copy.md`, header): one table `| id | where | old | new | checked by | status |`, `where` relative to `internal/console/`. The gate copies `approved_analytics_onramp_copy_test.go`'s shape with `| PT-` rows.
+
+Draft rows (status `pending`; placeholders in braces are filled by the template):
+
+| id | where | draft |
+| --- | --- | --- |
+| PT-C01 | templates/appnav.html (tab) | Protection |
+| PT-C02 | templates/app_protection.html (watching headline) | In the last {days} days, {caught} requests to this app looked like attacks. Protection is recording them and letting them through while we check it never stops a real visitor. |
+| PT-C03 | templates/app_protection.html (blocking headline) | In the last {days} days, protection blocked {blocked} requests to this app. |
+| PT-C04 | templates/app_protection.html (mixed headline) | In the last {days} days, protection blocked {blocked} requests to this app and recorded {watched} more. |
+| PT-C05 | templates/app_protection.html (share) | That's {pct} of the {checked} requests protection checked. |
+| PT-C06 | templates/app_protection.html (nothing caught) | Nothing in the last {days} days looked like an attack. |
+| PT-C07 | templates/app_protection.html (counting since) | Protection counts started on {date}. |
+| PT-C08 | templates/app_protection.html (partial) | Some of this app's traffic in this window was served before counting started, so the real number may be higher. |
+| PT-C09 | templates/app_protection.html (off) | Protection is off on the servers that served this app. |
+| PT-C10 | templates/app_protection.html (no counts yet) | No protection counts yet for this app. They start when the servers that run it take the next release. |
+| PT-C11 | templates/app_protection.html (bars heading) | Day by day |
+| PT-C12 | templates/app_protection.html (legend) | blocked |
+| PT-C13 | templates/app_protection.html (legend) | recorded |
+| PT-C14 | templates/app_protection.html (groups heading) | What they were after |
+| PT-C15 | templates/app_protection.html (logs link) | See these requests in Logs |
+| PT-C16 | templates/app_protection.html (range) | 7 days |
+| PT-C17 | templates/app_protection.html (range) | 30 days |
+| PT-C18 | protection.go (read error) | Protection counts could not be read just now. Try again in a moment. |
+| PT-C20..C35 | protectiongroups.go (group names) | hard/traversal: Paths that try to climb out of the site's folder · hard/secrets: Secret files such as .env and .git · hard/keys: Private keys and cloud credentials · hard/dumps: Database dumps · hard/source: Editor and backup copies of PHP files · probe/admin: Admin pages · probe/cgi: Old CGI scripts and router pages · probe/devconfig: Docker and CI config files · probe/dumps: Backup and dump files · probe/java: Java server pages and consoles · probe/metadata: Cloud server metadata · probe/phpframework: PHP framework debug pages · probe/phpmyadmin: phpMyAdmin · probe/php: PHP scripts · probe/status: Server status pages · probe/wordpress: WordPress logins and admin pages |
+| PT-C36 | protectiongroups.go (other) | Other |
+| PT-C40 | templates/fleet_protection.html (title) | Protection |
+| PT-C41 | templates/fleet_protection.html (headline) | In the last {days} days, {caught} requests across {apps} apps looked like attacks. |
+| PT-C42 | templates/fleet_protection.html (table headings) | Account · App · Caught · Blocked · Share |
+
+- [ ] **Step 1: Write the deck** with the rows above, one row per group name (PT-C20 to PT-C35, in the order listed), status `pending`, `checked by` = `gate` for literal strings and the owning test name for strings with placeholders.
+- [ ] **Step 2: Write the gate test** (`TestProtectionCopyDeckIsApprovedAndApplied`): fails while any row is `pending`, and for every id in `protectionCopyBuilt` checks the `new` text appears in its file (`gate`) or the named test exists.
+- [ ] **Step 3: Run the copy review** with the `copy-review` skill on every `new` cell: launch its server, give Paul the link as a Markdown link, wait for his edits, apply them verbatim, set each row `approved`. Read `result.json` before any server restart.
+- [ ] **Step 4: Run the gate**
+
+Run: `go test ./internal/console/ -run 'TestProtectionCopyDeck'`
+Expected: PASS (all rows approved, `protectionCopyBuilt` empty).
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add docs/superpowers/plans/2026-10-30-console-protection-tab-copy.md internal/console/approved_protection_copy_test.go
+git commit -m "console: protection tab copy deck, reviewed by Paul"
+```
+
+---
+
+### Task 6: The per-app tab and its JSON door
+
+**Files:**
+- Create: `internal/console/protectionview.go`, `internal/console/protectiongroups.go`, `internal/console/templates/app_protection.html`
+- Modify: `internal/console/server.go` (routes beside the analytics ones, ~line 1868), `internal/console/templates/appnav.html` (link between Analytics and Activity), `internal/console/templates/app_logs.html` and its handler (carry `stream=edge` and `field` through the page URL), the page struct that carries `AnalyticsWin` (add protection fields)
+- Test: `internal/console/protectionview_test.go`, `internal/console/approved_protection_copy_test.go` (add ids)
+
+**Interfaces:**
+- Consumes: Tasks 3 and 4 (`readEdgeDays`, `protectionDates`, `sumProtection`), Task 5's approved text.
+- Produces:
+ - Routes `GET /a/{sqid}/apps/{app}/protection` (`handleAppProtection`, page via `s.appPage(w, r, "protection")`, same access as Analytics) and `GET /a/{sqid}/apps/{app}/protection/data` (`handleAppProtectionData`, JSON `protectionSummary` with `groups` keys unchanged).
+ - Query `range=7d|30d`; anything else is `7d` (a page never 400s over its query, as `handleAppAnalytics`).
+ - `func protectionGroupName(key string) string` in `protectiongroups.go`, from PT-C20..C36; unknown keys give PT-C36.
+ - Reads through `s.usageDayReader(now)` with `instanceStoreTimeout`.
+ - Logs link: `{Nav}/apps/{app}/logs?stream=edge&since=168h&field=kind=watch` while no block was counted in the window, `field=kind=block` otherwise.
+
+- [ ] **Step 1: Write the failing tests** in `internal/console/protectionview_test.go`, through the real server and router (as the analytics page tests do):
+ - `TestProtectionTabRendersHeadline`: a seeded root edge day with 8 watched of 150 checked today. Want status 200, PT-C02 with `8` and `7`, PT-C05 with `150`.
+ - `TestProtectionTabBlockingHeadline`: block 3, watch 0. Want PT-C03.
+ - `TestProtectionTabCountingSince`: counting starts mid-window. Want PT-C07 and PT-C08.
+ - `TestProtectionTabNoCounts`: days with traffic and no `guard_checked`. Want PT-C10 and never PT-C06.
+ - `TestProtectionTabOff`: rows with traffic, `GuardModes` only `["off"]`, no `guard_checked`. Want PT-C09 and never PT-C06.
+ - `TestProtectionTabReadErrorSaysSo`: an unparseable edge day. Want PT-C18 and no headline.
+ - `TestProtectionDataJSON`: the data door returns the summary's `checked`, `watch`, `block`, `counting_since`, `groups`.
+ - `TestProtectionTabMembersOnly`: a signed-in user without access to the account gets what Analytics gives them (same status).
+ - `TestEveryCatalogueGroupHasAName`: for every rule in `edgeguard`'s embedded catalogue, `protectionGroupName(tier+"/"+group)` is not PT-C36.
+ - `TestAppNavHasProtection`: the app nav shows PT-C01 between Analytics and Activity.
+ - `TestLogsPageCarriesEdgeFilter`: `GET …/logs?stream=edge&field=kind=watch` renders with the edge stream selected and the field filter in the data URL.
+- [ ] **Step 2: Run them and see them fail**
+
+Run: `go test ./internal/console/ -run 'ProtectionTab|ProtectionData|CatalogueGroup|AppNavHasProtection|LogsPageCarriesEdge'`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement.** Template in the Analytics tab's look (`app_analytics.html`): headline, share, day bars (blocked and recorded apart), groups table largest first, logs link, range switch. Add PT-C01..C18 and PT-C20..C36 to `protectionCopyBuilt`.
+- [ ] **Step 4: Run the tests and the copy gate and see them pass**
+
+Run: `go test ./internal/console/ -run 'Protection|CatalogueGroup|AppNav|LogsPage|TestProtectionCopyDeck'`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add internal/console/
+git commit -m "console: per-app Protection tab and its JSON door"
+```
+
+---
+
+### Task 7: The operator page
+
+**Files:**
+- Create: `internal/console/templates/fleet_protection.html`
+- Modify: `internal/console/protectionview.go`, `internal/console/server.go` (route beside `GET /fleet/economics`, ~line 1754), the operator nav template (add a link after Economics)
+- Test: `internal/console/protectionview_test.go`, `internal/console/approved_protection_copy_test.go`
+
+**Interfaces:**
+- Consumes: `readEdgeDays`, `protectionDates`, `sumProtectionAll`.
+- Produces: `GET /fleet/protection` (`handleFleetProtection`, operator access exactly as `handleEconomics` checks it, page via `s.opPage(addr, raw, "protection")`) and `GET /fleet/protection/data` (JSON `{summary, apps}`).
+ - *Plan's call (spec §4.1 leaves the spot to the builder):* its own page in the operator section, linked from the operator nav beside Economics, rather than a section inside Economics, which is about money.
+
+- [ ] **Step 1: Write the failing tests**
+ - `TestFleetProtectionOperatorsOnly`: a non-operator gets what `/fleet/economics` gives them.
+ - `TestFleetProtectionListsApps`: three apps seeded, one on a fleet box owned by its account and one fleet row claiming a foreign account. Want PT-C41 with the two legitimate apps' total and the foreign row absent from the table.
+ - `TestFleetProtectionData`: the JSON door's `apps` sorted by caught, descending.
+- [ ] **Step 2: Run them and see them fail**
+
+Run: `go test ./internal/console/ -run 'FleetProtection'`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**, adding PT-C40..C42 to `protectionCopyBuilt`.
+- [ ] **Step 4: Run the tests and the copy gate and see them pass**
+
+Run: `go test ./internal/console/ -run 'FleetProtection|TestProtectionCopyDeck'`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add internal/console/
+git commit -m "console: operator Protection page across every app"
+```
+
+---
+
+### Task 8: Branch checks before review
+
+**Files:** whatever the census asks for (`docs/superpowers/notes/census-proposal-console-protection-tab.md` and overlay, if any).
+
+- [ ] **Step 1: Census.** Run `make census-card`. If it reports changes, follow AGENTS.md "The census: the reviewer decides" (`make census-propose NAME=console-protection-tab CLAIMS=<file>`); the whole-branch reviewer decides each class.
+- [ ] **Step 2: Cross-compile.** Run `GOOS=darwin go build ./... && GOOS=windows go build ./...`. Expected: both succeed.
+- [ ] **Step 3: Touched packages.** Run `go test ./internal/usage/ ./internal/edge/ ./internal/host/ ./internal/console/`. Expected: PASS.
+- [ ] **Step 4: Object size.** In a scratch test (not committed), build an edge day with 200 hosts × 24 hours of rows carrying all three guard counters, 200 tallies of 16 groups and 24 mode entries; marshal it as the agent does. Expected: under 2 MiB, with the before and after sizes recorded in the branch description (spec §3.3; `usageDayReadCap` is 8 MiB).
+- [ ] **Step 5: Commit any census files, push, and request the whole-branch review** (Astra, at most three rounds, AGENTS.md stopping rules).
+
+```bash
+git add docs/superpowers/notes/ internal/provision/testdata/ 2>/dev/null; git commit -m "census: console protection tab" || true
+git push
+```
diff --git a/docs/superpowers/specs/2026-10-30-console-protection-tab-design.md b/docs/superpowers/specs/2026-10-30-console-protection-tab-design.md
index 9d4f99b98..bf6786c2d 100644
--- a/docs/superpowers/specs/2026-10-30-console-protection-tab-design.md
+++ b/docs/superpowers/specs/2026-10-30-console-protection-tab-design.md
@@ -1,6 +1,6 @@
# Console Protection tab: how much bad traffic the edge catches
-Status: draft for Paul, 2026-10-30, revision 2. Branch
+Status: revision 2, APPROVED by Paul 2026-10-30 ("Sounds good."). Branch
`design-console-protection-tab`. Builder check by Astra on rev 1 (8 points,
all settled as calls in §7).