| index 900b093c8..021c84707 100644 |
| --- a/docs/superpowers/plans/2026-10-30-console-protection-tab.md |
| +++ b/docs/superpowers/plans/2026-10-30-console-protection-tab.md |
| @@ -4,22 +4,25 @@ |
| |
| **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. |
| +**Architecture:** The edge counts protection checks and matches per host and owner, and flushes them with the usage counters it already writes every 5 minutes (`usage/edge/<box>/days/<date>.json`): hourly counts and a daily group tally in one record per host-owner-day, plus the box's protection mode per hour. 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. |
| |
| +**Review history:** plan rev 1 Astra R1 NOT READY (4 P1, 2 P2: tier key conversion, owner-change reconciliation, counting-start tied to the window, group-cap off by one, size gate, Logs link population). Rev 2 fixes all six; findings at `docs/superpowers/plans/CODEX-FINDINGS-CONSOLE-PROTECTION-TAB-PLAN-R1.md`. Two rounds remain (AGENTS.md stopping rules). Plan's call, refining spec §3.1 to meet its own ownership rule: the hourly protection counters live on the host-owner record beside the group tally, not on `usage.EdgeRow`, so an owner change mid-hour erases nothing and each owner's group total always equals their caught total. |
| + |
| ## 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). |
| +- No new storage writes. Counters ride the existing `usage.UpsertEdgeDay` 5-minute conditional put; a flush with no rows and no guard deltas 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). |
| +- The share's denominator is the checked count, never `Requests` (spec §3.1). |
| +- Protection counts are keyed by host, account and app together, hourly counts and daily groups alike; nothing is reset on an owner change, and `usage.EdgeRow` gains no fields (refines spec §3.1, see Review history). |
| +- Group keys are `rule.Tier.String() + "/" + rule.Group` (`reqrec.Tier` is a `uint8`; never `string(rule.Tier)`). |
| - 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). |
| +- Group tally: at most 32 keys per host-owner-day including `other`, so at most 31 named groups; a new group past that counts under `other`, an existing one keeps counting (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. |
| @@ -43,35 +46,36 @@ |
| |
| **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`. |
| + - `type GuardHour struct { Checked, Watch, Block int64 }`, JSON `checked`, `watch`, `block`, each `omitempty`. |
| + - `type GuardTally struct { Host, Account, App string; Hours map[string]GuardHour; Groups map[string]int64 }`, JSON `host`, `account`, `app`, `hours`, `groups`. One per host-owner-day. |
| + - `type GuardDelta struct { Host, Account, App string; Checked, Watch, Block int64; Groups map[string]int64 }`: what the meter accumulates between flushes for one host-owner. |
| - `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). |
| + - `func AddGroup(groups map[string]int64, group string, n int64)`: adds to an existing key; a new key is admitted only while fewer than `GuardGroupCap-1` named (non-`other`) keys exist, otherwise the count goes to `GuardGroupOther`. Used by the meter and by the day merge. |
| - `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]`. |
| + - `type EdgeFlush struct { Rows map[string]EdgeRow; Guard map[string]GuardDelta; Mode string }` (`Guard` keyed by `GuardKey`). |
| + - `func (d *EdgeDay) AddFlush(hour string, f EdgeFlush)`: replaces `AddDeltas`. Folds `Rows` exactly as `AddDeltas` did; folds each `GuardDelta` into `Guard[key]`: `Hours[hour]` gains its three counts, its groups merge via `AddGroup`. 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`. |
| + - `EdgeRow` and `SetOwner` are unchanged. |
| |
| -- [ ] **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"]}`. |
| +- [ ] **Step 1: Write the failing tests** in `internal/usage/edge_test.go` (host `shop.example.com`, account `acct1`, app `shop` unless stated): |
| + - `TestAddFlushSumsGuardHours`: two flushes into hour `"09"`, each delta `Checked 10, Watch 2, Block 1, Groups {"probe/wordpress":2,"hard/secrets":1}`. Want `Guard[key].Hours["09"] == {20,4,2}` and `Groups {"probe/wordpress":4,"hard/secrets":2}`. |
| + - `TestGuardOwnerChangeMidHourKeepsBoth` (Review Focus 3): in hour `"09"`, a delta for `acct1/shop` with `Watch 3, Groups {"probe/wordpress":3}`, then a row whose `SetOwner` moves the host to `acct2/blog` and a delta for `acct2/blog` with `Watch 2, Groups {"probe/wordpress":2}`. Want two tallies: `acct1/shop` hour `"09"` watch 3 with groups summing to 3, `acct2/blog` watch 2 with groups summing to 2. |
| + - `TestAddGroupCapsAtOther`: add 40 distinct groups `g00`..`g39` with 1 each, then `g00` again with 1. Want `len == 32`, 31 named keys, `other == 9`, `g00 == 2`, total 41. |
| + - `TestGuardModesPerHour`: flush with one row and `Mode "catalogue"` in hour `"09"`, then one row and `Mode "block"` in `"09"`, then `Mode "catalogue"` with no rows or deltas 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`. |
| + - `TestEdgeDayOldShapeParses`: unmarshal a day JSON with no guard fields. Want nil `Guard` and `GuardModes`, rows intact. |
| |
| - [ ] **Step 2: Run them and see them fail** |
| |
| -Run: `go test ./internal/usage/ -run 'Guard|AddFlush|EmptyFlush|OldShape'` |
| -Expected: FAIL (undefined fields and functions). |
| +Run: `go test ./internal/usage/ -run 'Guard|AddFlush|AddGroup|EmptyFlush|OldShape'` |
| +Expected: FAIL (undefined types 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'` |
| +Run: `go test ./internal/usage/ ./internal/host/ -run 'Guard|AddFlush|AddGroup|EmptyFlush|OldShape|EdgeDay|UsageFlush'` |
| Expected: PASS. |
| |
| - [ ] **Step 5: Commit** |
| @@ -90,25 +94,26 @@ git commit -m "usage: protection counters, group tally and modes on the edge day |
| - Test: `internal/edge/usagemeter_test.go`, `internal/edge/guard_usage_test.go` (new) |
| |
| **Interfaces:** |
| -- Consumes: Task 1's `EdgeFlush`, `GuardTally`, `GuardKey`, `EdgeRow` guard fields. |
| +- Consumes: Task 1's `EdgeFlush`, `GuardDelta`, `GuardKey`, `AddGroup`. |
| - 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 (u *UsageMeter) RecordGuard(rt registry.Route, rule *edgeguard.Rule, blocked bool)`: on the delta for `GuardKey(rt.Host, release.RouteAccount(rt), rt.App)`, `Checked++` always; when `rule != nil && rule.Mode != edgeguard.ModeBurst`, `Block++` or `Watch++` and `AddGroup(groups, rule.Tier.String()+"/"+rule.Group, 1)`. It does not touch the host's `EdgeRow`. |
| + - `func (u *UsageMeter) Drain() usage.EdgeFlush`: rows, guard deltas and the mode set by `SetGuardMode`; resets rows and deltas. |
| - `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/usagemeter_test.go`, `TestRecordGuardCounts`: rules taken from the real catalogue (`edgeguard`), not built by hand: a watch on a `probe/wordpress` rule, a block on a `hard/secrets` rule, a check with no rule, and a match on a `probe/admin` (burst) rule. Want the delta `Checked 4, Watch 1, Block 1`, groups exactly `{"probe/wordpress":1,"hard/secrets":1}`. |
| + - `TestRecordGuardOwnerChangeWithinDrain` (Review Focus 3): one match for route `acct1/shop`, then the same host as `acct2/blog`, then a match for it, all before one `Drain`. Want two deltas, each with `Watch 1` and one group count. |
| - `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`. |
| + - `TestGuardUsageCountsAProbe`: `GET /wp-login.php` on a routed host. Want delta `Checked 1, Watch 1`, groups `{"probe/wordpress":1}`, flush `Mode "catalogue"`. |
| + - `TestGuardUsagePlainRequestCountsChecked`: `GET /`. Want `Checked 1`, no watch, no groups. |
| + - `TestGuardUsageBurstRuleNotCaught`: `GET /admin`. Want `Checked 1, Watch 0`, no groups. |
| + - `TestGuardUsageTunnelDeliveredNotCounted`: the same probe arriving as a tunnel delivery (the context `fromTunnel` reads, as `guard_test.go` sets it). Want no delta. |
| - `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. |
| + - `TestGuardUsageModeOff`: an Edge with `CARLOS_EDGE_PROTECT=off`. Want no delta and flush `Mode "off"`. |
| + - Review Focus 1: `TestGuardUsageHopCountsOnce`: a probe backhauled over a verified hop (the setup `homemap` tests use). Want the two edges' `Checked` 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** |
| |
| @@ -144,12 +149,13 @@ git commit -m "edge: count protection checks and matches into the usage meter" |
| - `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`. |
| + - `func tallyCounts(src edgeDaySource, t usage.GuardTally, acct, app string) bool`: the same rule for a guard tally. |
| - `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`. |
| + - `TestRowCountsRefusesForeignFleetRow` (Review Focus 2): a row and a guard tally in `f1`'s day claiming `acct2/shop`. Want `rowCounts(...) == false` and `tallyCounts(...) == false` for `acct2/shop`; the same claiming `acct1/shop` gives true. |
| - `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`. |
| @@ -182,28 +188,32 @@ git commit -m "console: one edge-day reader for root and fleet boxes; fleet rows |
| - Test: `internal/console/protection_test.go` |
| |
| **Interfaces:** |
| -- Consumes: Task 3's `edgeDaySource`, `rowCounts`. |
| +- Consumes: Task 3's `edgeDaySource`, `rowCounts`, `tallyCounts`. |
| - 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. |
| + - `type protectionDay struct { Date string; Checked, Watch, Block int64; Partial, NotCounted, Off bool }` (JSON `date`, `checked`, `watch`, `block`, `partial`, `not_counted`, `off`). |
| + - `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`). |
| - `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`. |
| + - `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 tallies are included only where `tallyCounts` would accept them for their own account. |
| + |
| + Rules (spec §3.1, made concrete after plan R1 finding 3). Coverage is decided from what each box wrote, never from where the window starts: |
| + - **Box-hour state**, per source box and hour label: `off` when `GuardModes[hour]` is exactly `["off"]`; `counted` when `GuardModes[hour]` is any other non-empty set; `uncounted` when the box has rows in that hour but no `GuardModes` entry (an older binary wrote them). |
| + - **Switch-over hour:** a `counted` box-hour whose previous hour on the same box is `uncounted` (for hour `"00"`, the previous day's `"23"` when that day is among the sources) is also marked `switched`: the box may have changed binaries inside it. |
| + - **App hours** are the box-hours with an accepted row (`rowCounts`) whose `Requests > 0`. |
| + - **Day:** `NotCounted` when every app hour that day is `uncounted`; `Off` when every one is `off`; `Partial` when the day mixes `uncounted` with `counted` app hours, or has a `switched` app hour; otherwise complete. A day with no app hours is complete with zeros. |
| + - **`CountingSince`** is set only when the window contains an `uncounted` app hour; it is the date of the earliest `counted` app hour after the last `uncounted` one. A window wholly counted has `CountingSince ""` and says nothing about a start, so the 7- and 30-day views never disagree about it. |
| - `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. |
| + - **Counts** sum `Hours` of the accepted tallies (`tallyCounts`) over the window's dates; `Groups` sums their `Groups`. |
| + - `Modes` is the sorted union of `GuardModes` over the app's box-hours. |
| |
| - [ ] **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. |
| + - `TestSumProtectionTotals`: two boxes, hours `"09"` and `"10"` on `2026-11-05`, all `counted`, tally hours checked 100/50, watch 6/2, block 0/1, groups `probe/wordpress: 5`, `hard/secrets: 4`. Want `Checked 150, Watch 8, Block 1`, `Groups {"probe/wordpress":5,"hard/secrets":4}`, `Partial false`. |
| + - `TestSumProtectionCountingSince` (Review Focus 4): box A has rows without modes on `2026-11-03` (all hours) and on `2026-11-04` hours `"00"`-`"09"`, then modes from `"10"`. Want `2026-11-03 NotCounted`, `2026-11-04 Partial` (mixed and switched), `CountingSince "2026-11-04"`, `Summary.Partial true`. |
| + - `TestSumProtectionSameHistoryBothWindows` (plan R1 finding 3): one history, counting from `2026-10-20` (rows without modes before), now `2026-11-05`. The 30-day window gives `CountingSince "2026-10-20"`, `Partial true`; the 7-day window gives `CountingSince ""`, `Partial false`. |
| + - `TestSumProtectionNothingCaught`: all app hours `counted`, zero watch and block. Want `Watch 0, Block 0, Partial false, CountingSince ""`. |
| + - `TestSumProtectionOff`: all app hours `off`. Want every app day `Off` and `Checked 0`. |
| + - `TestSumProtectionOwnerChange` (Review Focus 3): host re-owned to `acct2/blog` in hour `"12"`, both owners' tallies present for that hour. Want `acct1/shop` to see only its tally (caught equals its group total), `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. |
| |
| @@ -261,6 +271,8 @@ Draft rows (status `pending`; placeholders in braces are filled by the template) |
| | 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-C19 | templates/app_protection.html (logs note, 30-day view) | Logs keep these requests for 7 days, so older ones are counted here but no longer listed. | |
| +| PT-C37 | templates/app_logs.html (protection filter label) | protection matches | |
| | 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 | |
| @@ -288,7 +300,7 @@ git commit -m "console: protection tab copy deck, reviewed by Paul" |
| |
| **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) |
| +- 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`, `internal/console/apilogs.go` and the Logs page handler (a `protection` filter carried through the form and the live follow), `internal/edgeguard/catalogue.go` (rule lookup by id, if none exists), 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:** |
| @@ -298,7 +310,8 @@ git commit -m "console: protection tab copy deck, reviewed by Paul" |
| - 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. |
| + - Logs filter (plan R1 finding 6): the logs door and page accept `protection=1`, which keeps only records with `Fields["kind"]` `watch` or `block` whose `Fields["rule"]` names a catalogue rule that is not `edgeguard.ModeBurst` (lookup `func edgeguard.RuleByID(id string) (*edgeguard.Rule, bool)` over the embedded catalogue, added if none exists). The page form carries it as a hidden input so submitting the form and live following keep it. |
| + - Logs link: `{Nav}/apps/{app}/logs?stream=edge&since=168h&protection=1`, the same population the counts cover. On the 30-day view, PT-C19 sits beside the link. |
| |
| - [ ] **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`. |
| @@ -311,13 +324,14 @@ git commit -m "console: protection tab copy deck, reviewed by Paul" |
| - `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. |
| + - `TestLogsProtectionFilter`: seeded edge records: a `watch` on a `probe/wordpress` rule, a `block` on a `hard/secrets` rule, a `watch` on a `probe/admin` (burst) rule, and a plain `response` record. `GET …/logs/data?stream=edge&protection=1` returns exactly the first two. |
| + - `TestLogsPageCarriesProtectionFilter`: `GET …/logs?stream=edge&protection=1` renders with the edge stream selected, PT-C37 shown, and `protection=1` in the form and in the data URL the live follow uses. |
| - [ ] **Step 2: Run them and see them fail** |
| |
| -Run: `go test ./internal/console/ -run 'ProtectionTab|ProtectionData|CatalogueGroup|AppNavHasProtection|LogsPageCarriesEdge'` |
| +Run: `go test ./internal/console/ -run 'ProtectionTab|ProtectionData|CatalogueGroup|AppNavHasProtection|LogsProtectionFilter|LogsPageCarriesProtection'` |
| 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 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..C19 and PT-C20..C37 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'` |
| @@ -375,7 +389,8 @@ git commit -m "console: operator Protection page across every app" |
| - [ ] **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 4: Object size** (plan R1 finding 5). Find the largest flagship edge day from yesterday, read-only: `aws s3 ls --profile keymail s3://<deployment bucket>/usage/edge/ --recursive | grep "/days/<yesterday>.json" | sort -k3 -n | tail -3` (the bucket is in the flagship's host env or `carloku-infrastructure`; read nothing else). Build a fixture with that object's host count, every host with 24 hours of rows, a guard tally per host with 24 hours and 16 groups, and 24 mode entries; marshal it as the agent does. Expected: under 768 KiB (75% of `usageDayCacheMaxBody`, 1 MiB). If the real object is already over that before the change, or the fixture is, stop and report on the branch with both sizes instead of continuing. Record before and after sizes in the branch description. |
| +- [ ] **Step 4b: Cache keeps it.** Add `TestUsageDayCacheKeepsGuardDay` to `internal/console/usagedays_test.go`: a settled edge day carrying guard tallies, read twice through `usageDayReader`; the second read does not reach the underlying store. |
| - [ ] **Step 5: Commit any census files, push, and request the whole-branch review** (Astra, at most three rounds, AGENTS.md stopping rules). |
| |
| ```bash |