carlos / platform Public

Fleet alerts Plan 2 (traffic): plan rev 1 and Astra review brief

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 95377f5269b056a140e69760967809f8e9e5defc parent 11c8c86
2 files changed, +567 −0
  • docs/superpowers/plans/2026-11-01-fleet-alerts-2-traffic.md +487 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-fleet-alerts-2-plan.md +80 −0

CI passed — run details

Intent

Human

<task-notification> <task-id>a521bc539f3ec0e17</task-id> <tool-use-id>toolu_01448PuUjrXtXtjCDeQAbAJT</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/1f8653ea-6b78-4712-b1ac-1eb863a870a6/tasks/a521bc539f3ec0e17.output</output-file> <status>completed</status> <summary>Agent "Recon edge counters and heartbeat" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>All paths below are under `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/fleet-alerts-2-traffic`. Line numbers are as read at 11c8c864. I changed nothing. Bash sandbox note: parallel Bash calls sometimes fail with a bwrap "commondir" error from other worktrees. Sequential calls work. **1. Request counting per class today** There are two independent counters, plus the choke point they share. - **Choke point.** The observer `defer` in `Edge.ServeHTTP` is `internal/edge/edge.go:2185-2199`, installed under `if up.route.Kind != "status"` (~2142). `ob := &amp;countingWriter{...}` (edge.go:2139, type at `usagemeter.go:149`) latches the final status in `ob.status`; 0 means 200, as `reqrecords.go:62` treats it. - **What is known at the choke point.** Status, `up.route` (Host, App, `release.RouteAccount(rt)`, Environment), `r` (path, client IP, geo answer from context), `out` (the guard verdict) and `hopped`. - **What the defer calls.** - `m.Record(up.route, 1, bytes, hopped)` at edge.go:2187. It is skipped when `out.unbilled`, which is an acknowledged home asset fill. - `observeAnalytics`. - `observeRecords` (edge.go:2193). - `observeGuardCount` (edge.go:2198). - **Second call site.** `serveAssetFar`'s own defer at `assetcatch.go:1074-1093` calls `Record`, `observeRecords` and `observeGuardCount` for far-asset answers, with a synthetic route. - **Not covered by the choke point.** - Everything before the route lookup. - Kind "status". - Early returns at `importGateAdmit` and `planDisabledAdmit` (edge.go:~2122-2129). - The :80 handler. - A tunnelled request on the fleet box. `observeRecords` returns early for `fromTunnel` (reqrecords.go:~58), but `Record` does not skip it. - **Counter A, UsageMeter (`internal/edge/usagemeter.go`).** - `m map[string]usage.EdgeRow`, keyed by host. - `usage.EdgeRow` (`internal/usage/edge.go:14-41`) has Account, App, Requests, BytesOut, HopRequests, HopBytesOut, RateShed, RateCeiling and PlanThrottled. - It has no status class and no 5xx count. - Flush: `usageLoop` (`internal/host/usage_loop.go:~60`) sleeps 5 minutes, then `m.Drain` into `usage.UpsertEdgeDay`, which CAS-merges into the hour-bucketed day object. - **Counter B, reqrec.Recorder (`internal/reqrec/recorder.go`).** - `minuteCounts` (123-131) has s2xx, s3xx, s4xx, s404, s5xx, wakes, block, watch and methods. - It is keyed by `minuteKey{acct, app, minute}` (118) and filled by `count()` (222-240), where 404 is its own bucket and not also in 4xx. - `Response()` is at 263 and `Match()` at 293. `Match` counts the status class too, so there is no double count. - `Flush(now)` (377) is called by `reqrecLoop` every minute (`internal/host/reqrec_loop.go:~44`, wired at `agent.go:1093-1095`). It writes one `kind=minute` summary per app and minute into the applog edge stream through `EdgeSummary`. - It is nil when there is no log sink or `CARLOS_EDGE_RECORDS=off` (reqrec_loop.go:~28). **2. Protection counts** - **Increment.** `Edge.observeGuardCount` (`internal/edge/guard.go:106-117`) calls `UsageMeter.RecordGuard(rt, rule, blocked)` (`usagemeter.go:100-120`). - It is called from edge.go:2198 and assetcatch.go:1092. - It runs once per request that has a `guardState`, which is every request except doors, hop-door calls, tunnelled requests and `CARLOS_EDGE_PROTECT=off`. - **Fields.** - `usage.GuardDelta` (`usage/edge.go:~64-70`) has Host, Account, App, Checked, Watch, Block and Groups. - Delta keys are `guardOwner{host, account, app}`. - The day side is `GuardTally`/`GuardHour` with `Guard map[string]GuardTally` (`usage/edge.go:~46-60`, 117). - `Groups` is capped at `GuardGroupCap=32` with an "other" overflow (`AddGroup`). - **Blocked versus watched.** - Rule modes are watch, block and burst (`internal/edgeguard/catalogue.go:~28-33, 98`). Burst rules are excluded from both counts (usagemeter.go:106). - `blocked` means `guardState.verdict.block`, i.e. `guardMode.blocks(rule)` (guard.go:~57-64). The mode comes from `CARLOS_EDGE_PROTECT` (off, watch, block, or the catalogue default). - The default blocks nothing (guard.go:~25), so everything is "watch". - Watch is a matched, non-burst, non-blocked rule. Block is a matched, non-burst, blocked rule. - **Client hash and country.** - Country: `geoAnswerFrom(r.Context()).Country` (`geoipheaders.go:18`), read in `requestResponse` (`reqrecords.go:~38-47`). `Response` also carries `ClientIP: clientIP(r)` (`analytics.go:76`, which handles the verified hop's X-Forwarded-For). - Hash: `reqrec.ClientKey(ip)` gives the /32 or /64, and `reqrec.ClientHash(salt, key)` gives a 12-hex HMAC (`reqrec/classify.go:82-96`). - `ClientHash` is computed only inside the unexported `Recorder.fields` (recorder.go:~344), using `saltFor`, which reads `analytics.DaySalt(dataDir, day)`. It runs only for emitted (capped) records. - The edge-side `RecordGuard` has no client or country today. - `Recorder.Match` sees every matched request, since `c.block++` and `c.watch++` happen before the record cap (recorder.go:~300-312). It already has `ClientIP`, `Country`, `Path` and `Kind`. **3. Rate limit and plan throttle** - **Rate limit.** `rateAdmit` (`internal/edge/ratelimit.go:126`) calls `noteRateLimited` (ratelimit.go:159), which calls `UsageMeter.RecordRateLimited(rt, d)` (`usagemeter.go:66-80`). - `ratelimit.Shed` increments `EdgeRow.RateShed` (fair share). Any other non-Allow decision increments `RateCeiling` (per-client backstop). - Observe mode counts refusals that would have happened. - `rateAdmit` is called from edge.go:2288 (upgrade) and 2408, and from `assetcatch.go:316, 413, 452`. - **Plan throttle.** It exists as `EdgeRow.PlanThrottled` (`usage/edge.go:40`). - It is incremented by `UsageMeter.RecordPlanThrottled` (`usagemeter.go:84`), called from `notePlanThrottled` (`planthrottle.go:44-47`). - Its callers are `planthrottle.go:78` ("a request") and `:87` ("an upgrade"). - `SetOwner` zeroes these three counters when a row's owner changes (`usage/edge.go:~128`). **4. Reqrec masking and bad paths** - **Masking.** `reqrec.MaskPath(p)` (`reqrec/redact.go:459`) escapes controls, masks segments of unclassified shape, and caps length at `MaxPath`. `QueryNames` is at 584 and `Fragment` at 667. - **Bad-path identification.** There is no explicit "bad path" concept. - Not-found records are `Status == 404` (`Recorder.Response`, recorder.go:263-290), capped at `NotFoundPerMin=60` per app per minute. - Block and watch records come from `Match`, capped at `BlockPerMin` and `WatchPerMin` of 300. - Rule matches are classified by `edgeguard.Check` (edge.go:~2163). - **Top-N.** None exists. The closest bounded-cardinality precedents are `usage.AddGroup` with its 32-entry cap and "other" (`usage/edge.go:~95`), and the analytics pace map (`internal/analytics/pace.go`). **5. unknownHost** - `func (e *Edge) unknownHost(w http.ResponseWriter, r *http.Request)` is at `edge.go:2884-2901`. It returns nothing. - It strips the port from `r.Host`, so the hostname is available. Callers could pass it, or read `r.Host` themselves. - It writes one of three answers: - `pendingHost` when `underPlatformDomain(host)` (pending.go). - A 302 to `fallbackURL`. - A 404 "unknown host". - Call sites: - 1835: a door caller asking for a reserved host. - 1970: a door caller whose app does not own the host. - 1986: the main case, where nothing here and no backhaul serves the host. - 2120: a door caller out of scope (the route is known). - 2965: the :80 handler. - The hostname is attacker-controlled, so it needs a bounded structure. - The door cases (1835, 1970, 2120) are the platform's own calls, not outsiders. A count should probably skip them or keep them separate. **6. Heartbeat** - **Writer.** `statusLoop` (`internal/host/agent.go:4239`) calls `groupStatusTick` and `statusTick` (4523), which calls `status.CollectBox` (4546) and `status.WriteBox` (`internal/status/snapshot.go:1230`). - `WriteBox` does an indented `MarshalIndent` and a CAS put to `status/boxes/&lt;label&gt;.json`. - **Cadence.** `status.SnapshotPeriod = 5m` plus up to 1 minute of jitter (`status/fleet.go:112`; `agent.go:~4338`). A nudge channel can trigger a tick early. - **Struct.** `BoxMetrics` is at `snapshot.go:532-720`, reached as `Box.Metrics *BoxMetrics` (879). - Fields are fed from `Probes` (`snapshot.go:48-213`). - Each probe is copied in the `box.Metrics = &amp;BoxMetrics{...}` literal (1175-1210). - That literal sits behind an any-field-known `if` at 1155-1161. - **Adding a field.** The convention is a nil or empty value that omits the key, with `json:"x,omitempty"` on the BoxMetrics field. - Add the field to `Probes`. - Add it to the "any known" condition (1155-1161), or an alone-populated field will not attach the block. - Add it to the literal. - Fill it in `statusLoop`'s `Probes{...}` (~4380-4415). - Newer fields carry "Private Metrics only: names hosts" comments. Older and newer readers ignore unknown keys. - **Size.** The block is dominated by host-keyed maps: `RouteVersions`, `RouteServing`, `Aliases`, `RouteDBBytes`, `Upstreams`, `Updates`, `Egress` and `BuildStates`. It scales with route count, roughly tens to a few hundred KB on a big box. - The caps are `maxFleetBoxBodyBytes = 1&lt;&lt;20` (`fleet.go:~134`, `LoadBoxes`) and `engineBoxBodyBytes = 1&lt;&lt;20` (`internal/console/alertsignals.go:39-40`). Oversize is logged and skipped. The caps are 200 keys, and objects older than 24 hours are dropped. - 3 windows of top-10 lists is about 8-12 KB indented, which is small against 1 MiB. - **Edge-to-host handoff.** The edge is in the same process as the heartbeat writer. `statusLoop` is spawned before the edge exists, so the pattern is an `atomic.Value` holding a func, stored in the edge-ready callback (`agent.go:1037-1047`). - `upstreamSource` (set by `setUpstreamSource(e.UpstreamStates)`). - `geoIPSource` and `geoIPAlertSource`, with `geoIPState()` at agent.go:4177 returning nil before the edge is ready. - Usage follows a related shape: `m := edge.NewUsageMeter(); e.EnableUsage(m); go usageLoop(m.Drain, am)` (agent.go:1051-1053, 1082). - A traffic accessor would follow `geoIPState()`: publish a func in that callback and read it into a new `Probes` field inside `statusLoop`'s Probes literal. **7. Windowing models to follow** - **Usage meter.** The mutex and map pattern with `Drain`, which swaps the map out and resets (`usagemeter.go:123-137`). It is drained on a timer, so it cannot give three retained windows. - **Recorder.** `Recorder.minutes` keyed by minute, with `Flush(cutoff)` emitting finished buckets (`recorder.go:377`). The closest model for "completed windows". - **GeoIP alert.** `Edge.GeoIPAlertCode(now)` is a pull accessor reading edge state (`geoipmirror.go:677`). - **Rate limit.** `internal/ratelimit/limiter.go` is token buckets with idle eviction, not windows. - **Cardinality bound.** `usage.AddGroup` (see 4). **8. Which boxes run edges and write heartbeats** - The edge is only started in two places: - The standalone `carlos edge` verb (`main.go:69-70`, `edge.Run`). It writes no heartbeat and never calls `EnableUsage`, so it meters nothing ("pure-proxy edges meter nothing", edge.go:~599-604). - The box agent via `edge.RunWithActivatorReady` (`agent.go:1037`). Every agent box runs both an edge and `statusLoop`. - **Fleet boxes** (`CARLOS_FLEET` set) run the same agent. - `shouldSkipPublisherElection` skips the publisher lease, so they never run `BuildFleet` or `PublishFleet`. - They heartbeat under `fleets/&lt;fleet&gt;/status/boxes/&lt;label&gt;.json` through `CARLOS_STATUS_PREFIX` or the store door (`agent.go:~40-72, 4262-4290`). They run an edge that receives hub traffic (`fromTunnel`). - `systemBoxes` in the console unions platform and fleet boxes for `carlos system status` (`apistatuslayout.go:135`). - The alert engine's `engineReads.boxes` reads only `status/boxes/` at the platform prefix (`alertsignals.go:36, 133`). Fleet boxes' heartbeats are not seen by the engine as written. - **Console.** It is a separate process on a box whose agent reports it through `ConsoleProcesses` (`status/console_process.go`). I found no edge in the console process. **Design notes** - The recorder-based tops are only complete if `Recorder.Match` is the hook, and that is nil on boxes without a log sink or with `CARLOS_EDGE_RECORDS=off`. - `observeGuardCount` and `Record` do not depend on the recorder. The client hash needs the recorder's salt, or a copy of it.</result> <usage><subagent_tokens>121266</subagent_tokens><tool_uses>39</tool_uses><duration_ms>225102</duration_ms></usage> </task-notification>

Attributed to this commit: 38.8 g CO₂e (3,382,199 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on fleet-alerts-2-traffic, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/docs/superpowers/plans/2026-11-01-fleet-alerts-2-traffic.md b/docs/superpowers/plans/2026-11-01-fleet-alerts-2-traffic.md
new file mode 100644
index 000000000..96feaf700
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-01-fleet-alerts-2-traffic.md
@@ -0,0 +1,487 @@
+# Fleet alerts Plan 2: fleet traffic. Implementation Plan (rev 1)
+
+> **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:** An operator opens `/fleet/traffic` and sees, across every edge, whether traffic is healthy, whether anyone is abusing the platform, and whether the fleet is loaded or short of capacity. Two new fleet rules, fleet 5xx rate and abuse surge, alert on the same numbers.
+
+**Architecture:**
+- Each box's edge keeps 5-minute fleet counters in memory. The box puts the last 3 completed windows in its existing status heartbeat (`status/boxes/<box>.json`, `BoxMetrics.Traffic`). No new bucket object.
+- The console's alert engine already reads every heartbeat on every 5th pass (`heartbeatSignals`). On those passes it also writes the windows into console.db: 5-minute rows kept 7 days and hourly rollups kept 90 days. Then it evaluates `fleet_5xx` and `abuse_surge` from those rows.
+- `/fleet/traffic` reads console.db only. Its four tiles read the engine's open incidents, so a tile and an alert can never disagree.
+
+**Tech Stack:** Go, SQLite (console.db), `html/template`.
+
+**Spec:** `docs/superpowers/specs/2026-10-30-fleet-alerts-and-traffic-design.md` (APPROVED 2026-10-30). Read §6, §7.1, §7.2, §9, §10 and §11 item 2 before any task. Plan 1 (`docs/superpowers/plans/2026-10-30-fleet-alerts-1-engine-connectors.md`, merged 27173ed) built the engine this plan extends. Its build rulings are in amadan discussion 495. R-25 (the 24 h heartbeat horizon), R-41 (no unconditional fallbacks) and R-27 (job label) bind here.
+
+**Review budget:** at most three Astra plan rounds (AGENTS.md stopping rules). This is rev 1, round 1.
+
+## Recon: what main already counts (2026-11-01, at 11c8c864)
+
+| §10.1 needs | What exists | Plan 2 does |
+|---|---|---|
+| requests by class | `reqrec.Recorder` counts 2xx/3xx/4xx/404/5xx per app and minute (`internal/reqrec/recorder.go:123-131`). It is nil without a log sink or with `CARLOS_EDGE_RECORDS=off`. `usage.EdgeRow` has requests but no class. | Count at the same choke point, the observer defer in `Edge.ServeHTTP` (`internal/edge/edge.go:2185-2199`), and in `serveAssetFar`'s defer (`assetcatch.go:1074-1093`). It doesn't depend on the recorder. |
+| blocked, watched | `observeGuardCount` puts them in the usage edge day (`guard.go:106-117`, `usagemeter.go:100-120`). Burst rules are excluded. `/fleet/protection` reads them. | Count from the same verdict in the same call, with the same burst exclusion, so `/fleet/traffic` and `/fleet/protection` agree. |
+| rate-limit shed, ceiling, plan-throttled | In `EdgeRow` (`usage/edge.go:34-40`). Observe mode counts would-be refusals as refusals. | Count enforced refusals and observed (would-be) refusals apart. |
+| unknown host | Not counted (`edge.go:2884` `unknownHost`). | New counter at the two outsider call sites. |
+| top-N lists | None. `usage.AddGroup` (cap 32 plus "other") is the only bounded-cardinality precedent. | New bounded maps per window. |
+| client hash, country | `reqrec.ClientHash(salt, ClientKey(ip))` is computed only inside the recorder (`recorder.go:357`). The country comes from `geoAnswerFrom(ctx)`. | Export `Recorder.ClientID` so the hash matches what Logs shows. |
+| heartbeat carriage | `BoxMetrics` (`internal/status/snapshot.go:532-720`) has an edge-to-host `atomic.Value` source pattern (`geoIPSource`, `internal/host/agent.go:1046, 4156-4177`). | Add a `trafficSource` the same way. |
+
+The usage edge day is a bucket object read by `/fleet/protection`. Reading it for traffic would add store requests, and §9 binds, so the heartbeat carries the counters.
+
+## Global Constraints
+
+- **Request budget (§9):** no new bucket objects and no new store calls. The engine's existing every-5th-pass heartbeat reads carry the windows. The traffic page reads console.db only.
+- **Window:** 5 minutes, aligned to UTC multiples of 300 s. The heartbeat carries the last 3 completed windows. A window that began before the edge's counter started is never reported, so a restart is a gap, not a low count.
+- **Per window:**
+ - Each request the edge answered for a route is counted once, as either refused or one status class.
+ - `Requests == S2xx + S3xx + S4xx + S404 + S5xx + Refused`. 404 is not in `S4xx`, as in reqrec.
+ - Unknown-host requests are counted only in `UnknownHost`.
+- **Top lists:** 10 entries a window on the box, 20 in an hourly rollup.
+- **Edge memory bounds, per window, in distinct keys:**
+ - apps 4096
+ - rate-limited apps 1024
+ - paths 1024
+ - sources 1024
+ - unknown hosts 256
+
+ A request whose key doesn't fit still counts in the totals and enters no list.
+- **Strings from the box are hostile text:**
+ - unknown hostnames are cut to 253 bytes, paths go through `reqrec.MaskPath` (≤ 512)
+ - every string is made valid UTF-8, with control characters replaced by `?`
+ - the console re-applies the same caps on ingest
+ - hostnames are never rendered as links
+- **Retention:** 5-minute rows for 7 days, hourly rows for 90 days. There is no backfill. A missing window is a gap, never zero and never estimated.
+- **Rules (spec §7.1), both warning level, subject `fleet`:**
+ - `fleet_5xx`
+ - fires when 5xx > threshold % (default 1) of at least 500 answered requests over the three windows ending 5 min before the current window
+ - while open, stays open until the rate is ≤ half the threshold or requests fall under 500
+ - `abuse_surge`, where B is blocked + watched over the last 12 windows
+ - fires when B ≥ 1,000 and B > multiple (default 5) × the median of the same UTC hour on each of the previous 7 days
+ - while open, stays open until B < 500 or B ≤ half the multiple × the median
+ - until all 7 baseline hours exist, it fires above 10,000 and clears at ≤ 5,000
+- **Editable thresholds (§5.2), whole numbers:**
+ - `fleet_5xx` percent, bounds 1..50
+ - `abuse_surge` multiple, bounds 2..50
+- **Tiles (§10.3):** a tile is Watch exactly when one of its rules has an open fleet incident.
+ - Healthy: `fleet_5xx`, `service_down`, `box_silent`
+ - Abuse: `abuse_surge`
+ - Load: `cpu`, `mem`
+ - Capacity: `disk_eta`, `disk`, `cert_expiring`
+
+ Region has no room isn't an engine rule yet (Plan 1 cut it), so Capacity leaves it out until it is.
+- **Copy voice:** no em dashes in user-facing text. Every user-facing string goes through Task 6 before it is final.
+- **Verification budget** (memory `verification-budget`):
+ - mutation checks only on refusal, security, termination and lifecycle paths, at most about 10 per task, each with targeted `-run` tests
+ - local tests once with `-count=1`, plus one `-race` run of the touched packages
+ - CI runs the full suite
+- **Sandbox:** leave `GOCACHE` at its default (`~/.cache/go-build`). Keep scratch in `$TMPDIR`.
+- **Census:** `internal/edge`, `internal/reqrec`, `internal/status` and `internal/host` are in the root binary's dependencies. Run `make census-card` in Task 8. A new `NewServer` route may move the record-write census (Task 7).
+
+## Review Focus
+
+1. **A flood of junk:** 100,000 distinct random hostnames or paths in one window. Edge memory stays within the key caps, the heartbeat's traffic block stays under 16 KiB, and a `<script>` hostname renders as escaped text with no link. Tests in Tasks 2, 4 and 7.
+2. **Missed data is not zero:** a box that restarts, or a console down for 30 minutes. The chart shows a gap, `fleet_5xx` and `abuse_surge` neither fire nor clear on the missing windows, and a restarted box reports no partial window. Tests in Tasks 2, 4 and 5.
+3. **Counted once:** a backhauled (hopped) request, a tunnelled request, a refusal (429 or a block page), a far-asset answer. Each counts once fleet-wide, a refusal is not also a 4xx, and blocked plus watched equal what the usage meter counted for `/fleet/protection`. Tests in Task 2.
+4. **A forged or broken heartbeat:** windows with unaligned or future starts, negative or huge counts, more than 3 windows, over-long strings or lists. They are dropped or trimmed on ingest, and nothing panics. Tests in Task 4.
+5. **A quiet fleet:** under 500 requests with some 5xx never fires. Abuse surge with under 7 days of history uses the 10,000 floor. A zero median still needs 1,000. Tests in Task 5.
+
+---
+
+## File structure
+
+| File | Responsibility |
+|---|---|
+| `internal/status/traffic.go` (new) | `TrafficWindow` and its list types, constants |
+| `internal/status/snapshot.go` | `Probes.Traffic`, `BoxMetrics.Traffic` |
+| `internal/reqrec/recorder.go` | `Recorder.ClientID` |
+| `internal/edge/traffic.go` (new) | Window counter, bounded tops, `Edge.TrafficWindows` |
+| `internal/edge/edge.go`, `guard.go`, `ratelimit.go`, `planthrottle.go`, `assetcatch.go`, `answered.go` | Hooks: outcome refusal marks, the two defers, unknown host |
+| `internal/host/agent.go` | `trafficSource`, enable on the agent's edge, `Probes.Traffic` |
+| `internal/console/trafficstore.go` (new) | Tables, ingest with sanitising, hourly rollup, pruning, reads |
+| `internal/console/trafficrules.go` (new) | `fleet_5xx` and `abuse_surge` evaluation, pure |
+| `internal/console/alertsignals.go`, `alertpages.go`, `alertnotify.go`, `alertengine_pass.go` | Ingest on heartbeat passes, rule registration, copy |
+| `internal/console/trafficview.go` (new), `templates/fleet_traffic.html` (new) | The page |
+| `internal/console/opshell.go`, `server.go` | Rail item, route |
+
+---
+
+### Task 1: Traffic window types and heartbeat field
+
+**Files:**
+- Create: `internal/status/traffic.go`, `internal/status/traffic_test.go`
+- Modify: `internal/status/snapshot.go` (`Probes` :41, `BoxMetrics` :532, the any-known condition :1155-1161, the `BoxMetrics` literal :1175-1210)
+
+**Interfaces:**
+- Produces:
+ ```go
+ const (
+ TrafficWindowLen = 5 * time.Minute
+ TrafficWindowsKept = 3
+ TrafficTopN = 10
+ )
+ type TrafficWindow struct {
+ Start int64 `json:"start"` // unix seconds, a multiple of 300
+ Requests int64 `json:"requests"`
+ S2xx, S3xx, S4xx, S404, S5xx int64 // json "s2xx" ... "s5xx"
+ Refused int64 `json:"refused"`
+ Blocked int64 `json:"blocked"`
+ Watched int64 `json:"watched"`
+ RateShed int64 `json:"rate_shed"`
+ RateCeiling int64 `json:"rate_ceiling"`
+ RateObserved int64 `json:"rate_observed"`
+ PlanThrottled int64 `json:"plan_throttled"`
+ UnknownHost int64 `json:"unknown_host"`
+ Apps []TrafficApp `json:"apps,omitempty"` // by Requests
+ RateApps []TrafficApp `json:"rate_apps,omitempty"` // by Refused+Observed (rate and plan)
+ Paths []TrafficCount `json:"paths,omitempty"`
+ Sources []TrafficSource `json:"sources,omitempty"`
+ Hosts []TrafficCount `json:"hosts,omitempty"`
+ }
+ type TrafficApp struct { Account, App string; Requests, S5xx, Refused, Observed int64 } // json account, app, requests, s5xx, refused, observed
+ type TrafficCount struct { Key string; Hits int64 } // json key, hits
+ type TrafficSource struct { Client, Country string; Hits int64 } // json client, country, hits
+ func (w TrafficWindow) Answered() int64 // S2xx+S3xx+S4xx+S404+S5xx
+ ```
+ - `Probes.Traffic []TrafficWindow`
+ - `BoxMetrics.Traffic []TrafficWindow` with `json:"traffic,omitempty"` and a "Private Metrics only: names hosts and paths" comment
+
+- [ ] **Step 1: Write failing tests.**
+ - `TestTrafficWindowJSONNames` pins every JSON name above.
+ - `TestCollectBoxCarriesTraffic`: Probes with only `Traffic` set still attaches `Metrics` and round-trips the windows.
+ - `TestTrafficWindowAnswered`
+- [ ] **Step 2: Run, expect FAIL.** `go test ./internal/status -run 'Traffic' -count=1`
+- [ ] **Step 3: Implement.** `len(p.Traffic) > 0` joins the any-known condition.
+- [ ] **Step 4: Run, expect PASS.**
+- [ ] **Step 5: Commit.** `git commit -m "status: traffic windows in the heartbeat"`
+
+### Task 2: Edge fleet counters
+
+**Files:**
+- Create: `internal/edge/traffic.go`, `internal/edge/traffic_test.go`
+- Modify:
+ - `internal/reqrec/recorder.go`: add `ClientID`
+ - `internal/edge/answered.go`: `outcome` gains `refused bool` and `rate rateNote`
+ - `internal/edge/edge.go`: the observer defer :2185, the unknown-host calls at :1986 and :2965
+ - `internal/edge/guard.go`: `observeGuardCount` :106
+ - `internal/edge/ratelimit.go`: `rateAdmit` :126, `noteRateLimited` :159
+ - `internal/edge/planthrottle.go`: :44-95
+ - `internal/edge/assetcatch.go`: `serveAssetFar`'s defer :1074-1093
+
+**Interfaces:**
+- Consumes: Task 1 types.
+- Produces:
+ - `func (r *Recorder) ClientID(ip string, at time.Time) string`, which returns `ClientHash(r.saltFor(day), ClientKey(ip))`. It is nil-safe ("" for a nil recorder or no salt) and is never called with `r.mu` held.
+ - `type trafficCounter struct` (unexported) with:
+ - `func newTrafficCounter(now time.Time, clientID func(ip string, at time.Time) string) *trafficCounter`
+ - `func (c *trafficCounter) request(ev trafficRequest)`
+ - `func (c *trafficCounter) unknownHost(at time.Time, host string)`
+ - `func (c *trafficCounter) windows(now time.Time) []status.TrafficWindow`
+ - `type trafficRequest struct { At time.Time; Account, App string; Status int; Refused bool; Guard guardCount; Path, ClientIP, Country string; Rate rateNote }`. `guardCount` is none, watch or block, already burst-excluded. `rateNote` holds shed, ceiling and observed flags plus a plan-throttled flag.
+ - `func (e *Edge) EnableTraffic(clientID func(string, time.Time) string)` and `func (e *Edge) TrafficWindows(now time.Time) []status.TrafficWindow`. The latter is nil when not enabled. The standalone `carlos edge` never enables it.
+
+**Decisions:**
+- **Window rotation.** It happens lazily, under the counter's one mutex, on `request`, `unknownHost` and `windows`.
+ - A window whose end is ≤ now closes into a ring of 3.
+ - Each fully skipped 5-minute slot closes as a zero window.
+ - Windows that start before `ceil5(counter start)` are discarded.
+- **`windows(now)`** returns the closed windows whose starts are among the 3 before `floor5(now)`, oldest first. An idle box reports zero windows, not nothing.
+- **Classification in the two defers.** The route path skips status-kind routes as the defer already does, and also skips `fromTunnel` requests, as `observeRecords` does: the hub counted them. A request is refused when `out.refused` is set (a rate or plan refusal) or the guard verdict blocked it.
+ - Refused requests add to `Refused` and to no class.
+ - Otherwise the status (0 means 200) picks the class.
+- **Blocked and watched** are counted in `observeGuardCount`, beside `m.RecordGuard`, under the same condition and with the same burst exclusion. Move the traffic call there, or call it with the same inputs, so the counts equal the usage meter's.
+- **Rate.** `rateAdmit` marks the request's outcome: `rate.shed` or `rate.ceiling` when enforcing, together with `refused = true`, and `rate.observed` in observe mode. `planThrottleAdmit` and `planUpgradeAdmit` mark `rate.plan` and `refused`. They reach the outcome with `outcomeFrom(r)`.
+ - `serveAssetFar` must carry an outcome on its request, the same way, so its rate refusals reach its defer.
+ - A refusal on a request with no outcome is still counted in the usage meter, as today. It doesn't reach the traffic counter, and a comment says so.
+- **Lists:**
+ - Apps by route account and app.
+ - RateApps for any rate or plan note.
+ - Paths for 404s and guard matches (block or watch), keyed `reqrec.MaskPath(r.URL.Path)`.
+ - Sources for guard matches only, keyed on `clientID(ip, at)`, or on `reqrec.ClientPrefix(ip)` when that is "". Country comes from `geoAnswerFrom(ctx).Country`. Call `clientID` before taking the counter's mutex.
+ - Hosts from the unknown-host sites: the port is stripped, the host lower-cased and cut to 253 bytes, `strings.ToValidUTF8(…, "?")` is applied, and control characters become `?`.
+- **Unknown host** is counted only at `edge.go:1986` (after the far-asset and backhaul tries) and in the :80 handler at :2965. The door-caller sites at :1835, :1970 and :2120 are the platform's own calls and are not counted.
+- **Top-N** is taken at close by a stable sort on hits, descending, then key, ascending. Truncate to `TrafficTopN`.
+
+- [ ] **Step 1: Write failing tests** in `traffic_test.go`, driving the counter with an injected clock:
+ - `TestTrafficWindowsRotateAndKeepThree`: traffic in 5 consecutive windows. `windows` returns the last 3 completed windows, oldest first, with exact counts.
+ - `TestTrafficIdleWindowsAreZero`: after 12 idle minutes, `windows` returns zero windows, not nil.
+ - `TestTrafficPartialFirstWindowNotReported`: a counter started at 10:02 reports nothing for 10:00. At 10:15 it reports 10:05 and 10:10 only.
+ - `TestTrafficClassesSumToRequests`: a mix of 200, 0, 301, 404, 403, 503 and refused requests. Assert `Requests == Answered()+Refused`, and that a refused 429 is not in `S4xx`.
+ - `TestTrafficKeyCapsHold`: 100,000 distinct hosts and paths in one window. The internal map sizes stay ≤ 256 and ≤ 1024, `UnknownHost == 100000`, and `json.Marshal(windows)` is under 16 KiB.
+ - `TestTrafficHostSanitised`: a 400-byte host with `\x00` and invalid UTF-8 is cut to 253 bytes, is valid UTF-8, and has no control bytes.
+ - `TestTrafficTopNOrder`: ties are broken by key.
+ - Through `ServeHTTP`, in an existing edge test harness with a usage meter:
+ - `TestEdgeTrafficGuardMatchesUsageMeter`: in block mode, one blocked probe and one watched path. Traffic `Blocked`/`Watched` equal the meter's `GuardDelta` Block/Watch, and the blocked request is `Refused`.
+ - `TestEdgeTrafficRateEnforcedVsObserved`: an enforcing refusal counts `RateShed` or `RateCeiling` and `Refused`. Observe mode counts only `RateObserved`, and the request is served and classed.
+ - `TestEdgeTrafficTunnelNotCounted`
+ - `TestEdgeTrafficUnknownHostOutsiderOnly`: an outsider's unknown host counts. A door caller's out-of-scope request does not.
+ - `TestRecorderClientIDMatchesRecords`: `ClientID` equals the `cid` field the recorder writes for the same IP and day. A nil recorder returns "".
+- [ ] **Step 2: Run, expect FAIL.** `go test ./internal/edge -run 'Traffic' -count=1` and `go test ./internal/reqrec -run ClientID -count=1`
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run, expect PASS,** then run the same packages once with `-race`.
+- [ ] **Step 5: Commit.** `git commit -m "edge: 5-minute fleet traffic counters"`
+
+### Task 3: The box reports its windows
+
+**Files:**
+- Modify: `internal/host/agent.go` (edge-ready callback :1037-1053, beside `geoIPSource` :1046 and `EnableUsage`; the source vars near :4156; the `Probes{...}` literal in `statusLoop` ~:4380-4415)
+- Test: `internal/host/agent_traffic_test.go` (new) or the nearest existing heartbeat test file
+
+**Interfaces:**
+- Consumes: Task 1 and Task 2 `EnableTraffic` and `TrafficWindows`.
+- Produces:
+ - `var trafficSource atomic.Value // func(time.Time) []status.TrafficWindow`
+ - `func trafficWindows(now time.Time) []status.TrafficWindow`, which is nil before the edge is ready
+
+**Decisions:**
+- The callback calls `e.EnableTraffic(rec.ClientID)` when the agent has a recorder, and `e.EnableTraffic(nil)` otherwise.
+- Sources then fall back to the clear /24 prefix, the same value records already store.
+
+- [ ] **Step 1: Write failing tests.**
+ - `TestTrafficWindowsBeforeEdgeReadyIsNil`
+ - `TestStatusProbesCarryTraffic`: a stored source func's windows appear in the `Probes` the status tick builds. Use whatever seam the heartbeat tests already use for `geoIPState`.
+- [ ] **Step 2: Run, expect FAIL.** `go test ./internal/host -run 'Traffic' -count=1`
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run, expect PASS.**
+- [ ] **Step 5: Commit.** `git commit -m "host: heartbeat carries traffic windows"`
+
+### Task 4: The traffic series in console.db
+
+**Files:**
+- Create: `internal/console/trafficstore.go`, `internal/console/trafficstore_test.go`
+- Modify: the store's schema list. Add the tables where `alertstore.go:30-140` adds its own, and follow its migration style.
+
+**Interfaces:**
+- Consumes: Task 1 types.
+- Produces:
+ ```sql
+ CREATE TABLE IF NOT EXISTS traffic_windows (box TEXT NOT NULL, start INTEGER NOT NULL, body TEXT NOT NULL, PRIMARY KEY (box, start));
+ CREATE TABLE IF NOT EXISTS traffic_hours (start INTEGER PRIMARY KEY, windows INTEGER NOT NULL, boxes INTEGER NOT NULL, body TEXT NOT NULL);
+ ```
+ - `traffic_hours.windows` is the number of distinct 5-minute starts with any row in that hour, 0..12. `body` is a `trafficSum` as JSON.
+ - `type trafficSum struct`: the totals of `status.TrafficWindow` (without `Start`), its five lists (each trimmed to 20 when stored), and `Starts int`, the distinct window starts summed.
+ - `func addTraffic(sum *trafficSum, w status.TrafficWindow)` merges lists by key: (account, app) for app lists, `Key` for counts, (client, country) for sources.
+ - `func (s trafficSum) trimmed(n int) trafficSum`
+ - `func sanitizeTrafficWindow(w status.TrafficWindow, now time.Time) (status.TrafficWindow, bool)`
+ - `func (s *Store) IngestTraffic(byBox map[string][]status.TrafficWindow, now time.Time) (inserted int, err error)`
+ - `func (s *Store) PruneTraffic(now time.Time) error`
+ - `func (s *Store) TrafficRange(from, to time.Time) (sum trafficSum, starts map[int64]bool, err error)`, read from 5-minute rows. `starts` is the window starts present.
+ - `func (s *Store) TrafficHours(from, to time.Time) ([]trafficHour, error)`, with `type trafficHour struct { Start time.Time; Windows, Boxes int; Sum trafficSum }`. Hours with no row are absent, and the caller draws them as gaps.
+
+**Decisions:**
+- **Sanitising** drops the whole window when any of these fail:
+ - `Start % 300 == 0`
+ - `now-2h ≤ Start` and `Start+300 ≤ now+60s`
+ - every count in `0..1e12`
+ - `Requests == Answered()+Refused`
+
+ Otherwise it keeps at most `TrafficTopN` entries a list, drops entries with negative hits, and applies these caps:
+ - account and app: 128 bytes
+ - path keys: 512 bytes
+ - host keys: 253 bytes
+ - client: 64 bytes
+ - country: exactly two letters A-Z, else ""
+
+ Each string is made valid UTF-8 with control characters replaced by `?`. Per box, at most the 3 latest windows by `Start` are taken.
+- **Ingest** is one transaction:
+ 1. `INSERT OR IGNORE` each window.
+ 2. Recompute the `traffic_hours` row of every hour that got a new window, from its 5-minute rows.
+
+ `PruneTraffic` deletes 5-minute rows older than 7 days and hourly rows older than 90 days. Task 5 calls it at most once an hour (`alertEngineState.trafficPrunedAt`).
+
+ A box's label is its heartbeat key's (`status.Box.Label`).
+
+- [ ] **Step 1: Write failing tests.**
+ - `TestTrafficIngestDedupesByBoxAndStart`: the same 3 windows ingested twice give 3 rows, `inserted` 3 then 0.
+ - `TestTrafficIngestRejectsForgedWindows`: unaligned, future, too old, a negative count, a sum mismatch, and 5 windows (only the latest 3 kept).
+ - `TestTrafficIngestTrimsHostileStrings`: a 1 KiB host, 20 list entries, a `\x00`, invalid UTF-8 and country `"<s"`.
+ - `TestTrafficHourRollupMergesBoxesAndLists`: two boxes and the same app in both. The hour row sums them, the lists merge by key, and `Windows` counts distinct starts.
+ - `TestTrafficHourRecomputedOnLateWindow`: a window arriving after its hour row exists updates it.
+ - `TestTrafficPruneKeeps7DaysAnd90Days`
+ - `TestTrafficHoursGapIsAbsent`: no rows for an hour means no `trafficHour` for it, not a zero one.
+- [ ] **Step 2: Run, expect FAIL.** `go test ./internal/console -run 'TrafficIngest|TrafficHour|TrafficPrune|TrafficHours' -count=1`
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run, expect PASS.**
+- [ ] **Step 5: Commit.** `git commit -m "console: traffic series in console.db"`
+
+### Task 5: Ingest on heartbeat passes; fleet 5xx and abuse surge
+
+**Files:**
+- Create: `internal/console/trafficrules.go`, `internal/console/trafficrules_test.go`
+- Modify:
+ - `internal/console/alertsignals.go`: `heartbeatSignals` :~400, `alertRuleLevels`, `alertConsoleRules`, `alertThresholdDefaults`
+ - `internal/console/alertpages.go`: `alertRuleOrder` :213, `alertThresholdBounds` :218
+ - `internal/console/alertnotify.go`: `alertCopy` draft keys, following the `rule.box_silent.*` set at :196-200
+ - `internal/console/alertengine_pass.go`: `alertValueText` :731
+ - `internal/console/alertstore.go`: add `AlertFiring`
+- Test: `internal/console/alertengine_pass_test.go` (`TestEnginePassFiveCycleRequests` :171)
+
+**Interfaces:**
+- Consumes: Task 4.
+- Produces:
+ - `func fleet5xxVerdict(sum trafficSum, complete bool, thresholdPct float64, wasFiring bool) (firing bool, value float64, ok bool)`. `ok` is false when not `complete`, and `value` is the 5xx percentage.
+ - `func abuseSurgeVerdict(b int64, complete bool, baseline []int64, multiple float64, wasFiring bool) (firing bool, value float64, ok bool)`. `baseline` holds the 7 same-hour totals; fewer than 7 means "no history yet".
+ - `func (s *Server) trafficSignals(ctx context.Context, settings map[string]alertRuleSetting, now time.Time, sig *alertSignals)`
+ - `func (s *Store) AlertFiring(k alertKey) (bool, error)`: true when an open incident for k's scope and rule lists k's subject as a firing member.
+ - Rule IDs `fleet_5xx` and `abuse_surge`, both `alerting.LevelWarning`, both console rules. Threshold defaults are 1 and 5, with bounds {1, 50} and {2, 50}.
+
+**Decisions:**
+- **Ingest.** In `heartbeatSignals`, after `r.boxes` succeeds, call `IngestTraffic` with each box's `Metrics.Traffic`. Boxes with nil `Metrics` contribute nothing. Then call `trafficSignals`.
+ - If the listing failed, nothing is ingested or evaluated, and neither rule is covered, so their state holds.
+ - If ingest fails, `alertReadFailed` runs and neither rule is covered.
+ - After a successful ingest, call `PruneTraffic` when `now - alertEngineState.trafficPrunedAt ≥ 1h`. A prune error is logged and fails the run, and evaluation still proceeds.
+- **`fleet_5xx` evaluation.** Let `cur = floor5(now)`. The windows are the starts `cur-20m`, `cur-15m` and `cur-10m`. `complete` means all three starts are present.
+- **`abuse_surge` evaluation.**
+ - The windows are the 12 starts `cur-65m` to `cur-10m`, and `complete` means at least 9 of them are present.
+ - The baseline is `traffic_hours` rows at `floorHour(cur-40m) - d*24h` for d = 1..7, each with `Windows ≥ 9`. A missing or thin row makes the baseline short, which selects the 10,000 floor.
+ - The median of 7 is the 4th value in order.
+- **Signals.** Each verdict with `ok` adds one signal, keyed `(fleet, rule, "fleet")`, and covers the rule with no unknowns. A verdict that is not `ok` covers the rule with `unknown = {"fleet": true}`, so the member keeps its state (Review Focus 2). `wasFiring` comes from `AlertFiring`.
+- **Value text.** `fleet_5xx` reads like "1.4% of requests", `abuse_surge` like "12,400 an hour". The drafts are finalised in Task 6.
+
+- [ ] **Step 1: Write failing tests.**
+ - `TestFleet5xxVerdictTable`, rows of (answered, 5xx, threshold, wasFiring) and the expected result:
+ - (499, 100, 1, f): not firing
+ - (500, 6, 1, f): firing
+ - (500, 5, 1, f): not firing
+ - (1000, 6, 1, t): still firing at 0.6%
+ - (1000, 5, 1, t): clears at 0.5%
+ - (400, 50, 1, t): clears under 500
+ - not complete: `ok` false
+ - `TestAbuseSurgeVerdictTable`:
+ - with a 7-day median of 300: B 1,500 fires; B 999 doesn't; open at B 800 stays open; open at B 750 clears (≤ 2.5 × 300); open at B 499 clears
+ - with no history (6 rows): 10,001 fires, 10,000 doesn't; open at 5,001 stays; open at 5,000 clears
+ - a zero median needs B ≥ 1,000
+ - `TestTrafficSignalsGapKeepsState`: an open `fleet_5xx` incident, then a pass whose windows are missing. No Gone signal and the incident stays open.
+ - `TestTrafficSignalsListingFailedNoCover`
+ - `TestEnginePassFiveCycleRequests` (extend): heartbeats now carry 3 traffic windows each, and the pass's store call counts are exactly the existing assertion's.
+ - `TestAlertRuleOrderCoversEveryRule` (existing) passes with both rules added.
+- [ ] **Step 2: Run, expect FAIL.** `go test ./internal/console -run 'Fleet5xx|AbuseSurge|TrafficSignals|EnginePassFiveCycle|AlertRuleOrder' -count=1`
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run, expect PASS.**
+- [ ] **Step 5: Commit.** `git commit -m "console: fleet 5xx and abuse surge rules on the traffic series"`
+
+### Task 6: Copy deck
+
+**Files:**
+- Create: `docs/superpowers/notes/copy-fleet-alerts-2.md`
+
+- [ ] **Step 1: Extract every user-facing string into the deck.**
+ - Both rules' title, what, what.none, how_long, what_to_do and value text. Each says what is wrong, how long you have and what to do (spec §6.5).
+ - The `/fleet/traffic` page:
+ - the rail label "Traffic"
+ - each tile's name, OK line and Watch line
+ - the range links and chart legend (served, 4xx, 5xx, blocked or refused)
+ - the gap label
+ - the "counting started" note
+ - the four bad-traffic headings and the busiest-apps heading
+ - every empty state
+ - The threshold labels on `/fleet/alerts` for the two new rules.
+- [ ] **Step 2: Run a Luna pass** (memory `large-copy-decks-delegated`): `codex exec -m gpt-5.6-luna` with a committed brief carrying Paul's house rules (no em dashes; a full stop and a new sentence; plain words). Apply the result verbatim. Mark the rows approved by delegation, and bring only Luna's flags to Paul.
+- [ ] **Step 3: Replace the drafts** in `alertCopy` and the page copy. Add `approved_traffic_copy_test.go`, pinning each approved string as `approved_protection_copy_test.go` does. Run `go test ./internal/console -run 'Copy|Alert' -count=1`.
+- [ ] **Step 4: Commit.** `git commit -m "console: approved traffic copy"`
+
+Tasks 6 and 7 may swap order. Task 7 renders drafts until Task 6 lands, and Task 6 then replaces them.
+
+### Task 7: `/fleet/traffic`
+
+**Files:**
+- Create: `internal/console/trafficview.go`, `internal/console/trafficview_test.go`, `internal/console/templates/fleet_traffic.html`
+- Modify:
+ - `server.go` (routes near :1808-1843): `GET /fleet/traffic`
+ - `opshell.go:30`: `{Key: "traffic", Href: "/fleet/traffic", Label: "Traffic"}` between Dashboard and People
+ - the registry and budget tests every new operator page moves, as Plan 1 Task 10 did:
+ - `opshell_test.go`
+ - `opshots_test.go`
+ - `testdata/claim-routes.txt`
+ - `claim_invariant_fixtures_test.go`
+ - `claim_invariant_probes_read_test.go`
+ - `testdata/perf-budgets.txt`
+ - `perfwalk_test.go`
+ - Record-write census, only if `TestPlan9B8RecordWriteCensus` fails: create `internal/provision/fleet_traffic_census_test.go` with `fleetTrafficWriteCensusInventory()`, layered on `rootfsApps6WriteCensusInventory()` (the current selection, `plan9_b8_census_test.go:369`). Copy `fleet_alerts_census_test.go`, and select the new layer there.
+
+**Interfaces:**
+- Consumes: Tasks 4 and 5. Open incidents come from the store (the `open` half of `AlertStepInputs`, or a narrower `OpenAlertIncidents(scope string)` if you add one).
+- Produces:
+ - `func (s *Server) handleFleetTraffic(w http.ResponseWriter, r *http.Request)`, behind `operatorOnly`
+ - `type trafficTile struct { Key, Name, State, Line, Href string }`, where State is "ok" or "watch"
+ - `func trafficTiles(open []alertIncident, day trafficSum, dayOK bool) []trafficTile`, which is pure
+ - `func buildTrafficChart(hours []trafficHour, rng string, now time.Time) *trafficChart`, which is pure
+
+**Decisions:**
+- **Range.** `range` is `24h`, `7d` or `30d`; anything else means 24h, and the page never answers 400. 24h and 7d draw hourly bars; 30d draws daily bars, each the sum of that day's hours.
+- **Gaps.**
+ - A bar with no data is a gap, drawn as an empty, labelled column, never zero.
+ - A day with some hours present is drawn from those hours.
+ - The current hour is drawn as it stands.
+- **Stacks:**
+ - served = S2xx+S3xx
+ - 4xx = S4xx+S404
+ - 5xx = S5xx
+ - blocked or refused = Refused+UnknownHost
+- **Tiles.**
+ - **Watch:** one of the tile's rules has an open incident. Its line names the rule's title and member count, and its Href is `/fleet/alerts/history#incident-<id>` of the oldest such incident.
+ - **OK lines:**
+ - Healthy: the 5xx share of answered requests over the last 24 h.
+ - Abuse: blocked plus watched over the last 24 h.
+ - Load and Capacity: fixed lines.
+ - With no traffic counted yet, the Healthy and Abuse lines say so.
+- **Lists:** sums over the range, trimmed to 10.
+ - Busiest apps: account, app, requests, 5xx. Plain text, as `/fleet/protection` shows them; there is no operator app view to link to yet (follow-up).
+ - Probe paths: links to `/fleet/protection`.
+ - Blocked sources (client, country, hits): links to `/fleet/protection`.
+ - Unknown hostnames: plain escaped text, never a link.
+ - Rate-limited apps: refused and observed, as two columns.
+- **"Counting started <date>"** shows when the oldest hour row is younger than the range.
+- **No region filter in v1** (spec "my call"; follow-up).
+
+- [ ] **Step 1: Write failing tests.**
+ - `TestFleetTrafficNotOperator404`
+ - `TestFleetTrafficTilesFollowIncidents`: open `abuse_surge` gives Abuse Watch linked to `#incident-<id>`. Open `cpu` gives Load Watch. With none open, all four are OK. Check for every rule in the tile table.
+ - `TestFleetTrafficChartGapNotZero`: hours 1-3 present, 4 missing, 5 present. Column 4 renders as a gap with no bar height.
+ - `TestFleetTrafficChartThirtyDaysDaily`
+ - `TestFleetTrafficHostileHostEscaped`: an unknown host `<script>x</script>.example` renders escaped, with no `<a` around it.
+ - `TestFleetTrafficRangeDefaults`: `?range=junk` gives 24h and status 200.
+ - `TestFleetTrafficEmpty`: no rows gives the empty states and status 200.
+ - The registry, perf and census tests above, updated for the new route.
+- [ ] **Step 2: Run, expect FAIL.**
+- [ ] **Step 3: Implement.** The template copies `fleet_protection.html` and reuses the analytics chart parts that `protectionview.go` uses. Avoid a literal `NN%` in markup (`TestAppPageOwnerMetricsBoundary`).
+- [ ] **Step 4: Run, expect PASS.**
+ - `go test ./internal/console -run 'FleetTraffic|OpShell|OpShots|ClaimConsoleRouteCensus|Perf' -count=1`
+ - `go test ./internal/provision -run TestPlan9B8RecordWriteCensus -count=1`
+- [ ] **Step 5: Commit.** `git commit -m "console: /fleet/traffic"`
+
+### Task 8: Docs, roll notes, census, gate
+
+**Files:**
+- Modify: `README.md` (the alerting section Plan 1 wrote)
+- Create: `docs/superpowers/notes/roll-fleet-alerts-2.md`
+
+- [ ] **Step 1: README.** Cover:
+ - `/fleet/traffic` and what each tile means
+ - the two rules, their defaults and thresholds
+ - that history starts at the roll and gaps are shown as gaps
+ - that unknown hostnames are counted
+- [ ] **Step 2: Roll notes.**
+ - **Order:** dev first (memory `roll-order-dev-first`). Boxes and console can roll in either order: a console without traffic rows shows empty states, and an old console ignores the new heartbeat key.
+ - **Check:** on one dev box, send a few requests, one with an unknown Host and one probe path. After 15 minutes, `/fleet/traffic` on the dev console shows them. Don't use a box another session holds for a witness.
+ - No `host.env` changes and no infrastructure.
+- [ ] **Step 3: Docs pass.** Run Luna over the README lines and roll notes (Plan 1 R-43), then commit.
+- [ ] **Step 4: Census.** Run `make census-card` on the final tree, then `make census-propose NAME=fleet-alerts-2 CLAIMS=<file>`. Commit the overlay. Astra approves it on #280.
+- [ ] **Step 5: Gate.** Push, then check `amadan ci status carlos/platform -branch fleet-alerts-2-traffic` against the exact pushed tip until it is green.
+
+---
+
+## Per-task review (AGENTS.md stopping rule 3)
+
+- Opus reviews these tasks:
+ - Task 2: the edge hot path and hostile input.
+ - Tasks 4 and 5 together: box-written input into console.db, and alert rules.
+ - Task 7: a new operator route and hostile text rendered.
+- Tasks 1, 3, 6 and 8 are covered by the whole-branch Astra review.
+
+## Follow-ups (not in this plan)
+
+- Busiest-apps rows link to an operator app view once one exists.
+- A region filter on the chart.
+- Capacity tile gains "region has no room" when that rule moves onto the engine.
+- Managed-fleet boxes' heartbeats (`fleets/<f>/status/boxes/`) are not read by the engine. Their traffic arrives through the hub's tunnel and is counted by the hub.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-fleet-alerts-2-plan.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-fleet-alerts-2-plan.md
new file mode 100644
index 000000000..015e53e9b
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-fleet-alerts-2-plan.md
@@ -0,0 +1,80 @@
+# Review brief: fleet alerts Plan 2 (fleet traffic) plan, round 1 of 3
+
+Repo carlos/platform, branch `fleet-alerts-2-traffic`. The commit is named in the reviewer's prompt.
+Under review: `docs/superpowers/plans/2026-11-01-fleet-alerts-2-traffic.md` (rev 1).
+Authorities, all MERGED on main:
+- `docs/superpowers/specs/2026-10-30-fleet-alerts-and-traffic-design.md`, APPROVED. Plan 2 is §11 item 2, with §10, §9, §7.2 and the two Plan 2 rows of §7.1.
+- `docs/superpowers/plans/2026-10-30-fleet-alerts-1-engine-connectors.md` (rev 4, merged 27173ed), and the engine code it built in `internal/console/alert*.go`.
+- `AGENTS.md`.
+
+Do not review against unmerged branches. If this work needs one, say so as a P1 and stop.
+
+You are an independent reviewer. Read the plan, then the code it names, and check every claim against that code. Line numbers were taken at 11c8c864.
+
+## Fixed: do not re-argue
+
+- **Paul's rulings in spec §2:** layout A, four tiles; noise is the anti-goal; order engine, then traffic, then account and app alerts.
+- **Spec §9:** no new bucket objects, and the counters ride the heartbeat. Reading the usage edge day instead is out.
+- **Plan 1 build rulings** (amadan discussion 495), especially:
+ - R-25: the 24 h heartbeat listing horizon.
+ - R-41: no unconditional fallbacks after conditional-read errors.
+ - R-17: incident `Members` are the members firing now.
+- **The author's calls, which are not defects unless they break the spec:**
+ - Daily bars for the 30 d range.
+ - No region filter in v1.
+ - Busiest apps not linked, since no operator app view exists.
+ - Capacity omits "region has no room" until that rule is on the engine.
+ - Rate refusals counted enforced and observed apart.
+ - Unknown hosts counted only at the outsider call sites.
+
+Report only mechanisms that fail to honour these.
+
+## What to check
+
+1. **Counted once and agreeing with `/fleet/protection`.**
+ - The edge choke points named in Task 2 (`internal/edge/edge.go` observer defer, `assetcatch.go` `serveAssetFar` defer, `guard.go` `observeGuardCount`, `ratelimit.go`, `planthrottle.go`, `answered.go`): does every answered request land in exactly one of Refused or a class?
+ - Are hopped, backhauled, tunnelled and far-asset requests each counted once fleet-wide?
+ - Do Blocked and Watched equal the usage meter's guard counts?
+ - Does the `outcome` really reach `rateAdmit` and `planThrottleAdmit` on every path that can refuse?
+2. **Hostile input.** Unknown hostnames, paths and every heartbeat field are box- or attacker-controlled.
+ - Are the edge key caps, the heartbeat size, the console sanitising and the template escaping enough?
+ - Can one box's heartbeat poison fleet sums, for example with huge counts, forged starts, or a label collision?
+3. **Gaps and evaluation timing.** Heartbeats are written every 5-6 min with jitter, and the engine reads them every 5th one-minute pass.
+ - Are the `fleet_5xx` windows (`cur-20m..cur-10m`) and the `abuse_surge` windows reliably present when evaluated?
+ - Does "not complete" hold state without Gone or a false clear, given `withGone` and `keepMissing` in `internal/console/alertsignals.go`?
+ - Is the hysteresis via `AlertFiring` consistent with how `stepIncidents` (`alertengine.go`) treats Firing?
+4. **Request budget.** Does anything in Tasks 3-5 add a store call (`TestEnginePassFiveCycleRequests`)?
+5. **Tiles and alerts never disagree** (spec anti-goal "Contradiction"). Is the tile state read from the same incidents the engine opens? Do the tile rule IDs match `alertRuleLevels`?
+6. **Buildability.**
+ - Would each task's named interfaces compile against the code as it is? Check `Probes`, the `BoxMetrics` attach condition, the `agent.go` edge-ready callback, `outcomeFrom`, `alertThreshold`, `alertRuleOrder` and the record-write census selection at `internal/provision/plan9_b8_census_test.go:369`.
+ - Are the registry and perf tests a new operator route moves listed?
+7. **Census.** Is anything in Tasks 1-3 a new root read, beyond "body" changes?
+8. **Proportion.** Is anything here more than the spec asks for Plan 2? Is anything the spec asks for missing (§10.1 fields, §10.3 page parts, §7.1 Plan 2 rules, §13 tile test)?
+
+## Severity
+
+- **P1:** unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2:** wrong or missing. Fixed without reopening this review. The census, and review of any newly changed security, root, termination or production-storage behaviour, still check the fix; see AGENTS.md, "Stopping rules".
+- **P3:** clarity or polish. Goes on a follow-up list, and is never a reason for another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open.
+
+## Output
+
+Rank findings P1, then P2, then P3. Each finding gives:
+- the section or task
+- the problem
+- the evidence (file:line, verified)
+- the failure scenario
+- a concrete fix
+- the invariant or trust boundary it breaks (its fault family)
+
+End with exactly one verdict:
+
+- **READY:** no P1 and no P2.
+- **READY AFTER FIXES:** no P1. The listed P2s are fixed without another round.
+- **NOT READY:** one or more P1s, listed.
+
+In round 3, a NOT READY also says whether the P1s share one cause, and whether refusing the case up front or cutting the feature would remove them.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.