Plan 1 rev 2 after Astra R1; spec amendments; R2 brief
Astra R1 NOT READY (14 P1, 6 P2), findings committed unedited. Every finding accepted; #7 resolved by refusing the engine on HostClaim consoles, #12 by cutting console-editable box thresholds. Spec amended: no proxy, URL-free errors, at-least-once delivery, 5-minute first message, no-growth clears the forecast.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+699
−280
docs/superpowers/plans/2026-10-30-fleet-alerts-1-engine-connectors.md+423 −273docs/superpowers/reviews/CODEX-FINDINGS-fleet-alerts-1-plan-R1.md+129 −0docs/superpowers/reviews/CODEX-REVIEW-BRIEF-fleet-alerts-1-plan-R2.md+111 −0docs/superpowers/specs/2026-10-30-fleet-alerts-and-traffic-design.md+36 −7
CI passed — run details
Intent
Human
<task-notification> <task-id>buqck8ii1</task-id> <tool-use-id>toolu_01XrwNiJzBUJXL8TvQdA67qA</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/buqck8ii1.output</output-file> <status>completed</status> <summary>Background command "Run the Astra plan review on gpt-6-astra" completed (exit code 0)</summary> </task-notification>
diff --git a/docs/superpowers/plans/2026-10-30-fleet-alerts-1-engine-connectors.md b/docs/superpowers/plans/2026-10-30-fleet-alerts-1-engine-connectors.md| index ea9d1604e..1e24d530e 100644 |
| --- a/docs/superpowers/plans/2026-10-30-fleet-alerts-1-engine-connectors.md |
| +++ b/docs/superpowers/plans/2026-10-30-fleet-alerts-1-engine-connectors.md |
| @@ -1,48 +1,71 @@ |
| -# Fleet alerts Plan 1: engine, connectors, fleet rules — Implementation Plan |
| +# Fleet alerts Plan 1: engine, connectors, fleet rules — Implementation Plan (rev 2) |
| > **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:** Operators get a grouped, low-noise Slack (or email, or signed webhook) message days before a disk fills, and manage connectors and fleet rules at `/fleet/alerts`. |
| -**Architecture:** Each box adds a disk-full forecast rule to its existing `metrics.Evaluate` and keeps only incident-level rules on its own sinks. A new console claim worker, the alert engine, replaces `alertPass`. It reads box alert state, heartbeats, the fleet summary and console-side pages, and folds them into incidents in console.db under the spec's noise rules. A notifier delivers each incident message through the subscribed connectors (Slack, webhook, email), with retries. |
| +**Architecture:** |
| +- Each box adds a disk-full forecast rule to its existing `metrics.Evaluate`, and keeps only incident-level rules on its own sinks. |
| +- A new console worker, the alert engine, replaces `alertPass`. It reads box alert state, heartbeats, the fleet summary, and typed one-off events from console code, then folds them into incidents. |
| +- Incidents and their outbound messages are committed together in console.db under the spec's noise rules. |
| +- A notifier drains that outbox through the subscribed connectors (Slack, webhook, email). |
| -**Tech Stack:** Go, SQLite (console.db), `html/template`, `release.Store` / `GetIfChanged`, Ed25519, AES-256-GCM. |
| +**Tech Stack:** Go, SQLite (console.db), `html/template`, `release.Store` and `GetIfChanged`, Ed25519, AES-256-GCM, `internal/rootstate`. |
| -**Spec:** `docs/superpowers/specs/2026-10-30-fleet-alerts-and-traffic-design.md` (APPROVED 2026-10-30). Read §2, §5, §6, §7.1, §7.2, §8, §9, §11.1 and §13 before any task. |
| +**Spec:** `docs/superpowers/specs/2026-10-30-fleet-alerts-and-traffic-design.md` (APPROVED 2026-10-30, amended after plan review R1). Read §2, §5, §6, §7.1, §7.2, §8, §9, §11.1 and §13 before any task. |
| + |
| +**Review history:** Astra R1 on 84997183 was NOT READY, with 14 P1s and 6 P2s: `docs/superpowers/reviews/CODEX-FINDINGS-fleet-alerts-1-plan-R1.md`. Each finding's disposition is at the end of this plan. This is rev 2, for round 2 of 3. |
| ## Global Constraints |
| - Levels are exactly `alerting.LevelIncident` and `alerting.LevelWarning` (`internal/alerting/alerting.go:35-36`). |
| -- Disk forecast: fire at ETA ≤ 72 h, held 2 h. Clear at ETA > 108 h (1.5x). 6 h window, one point a minute, at least 2 h of points before any ETA. |
| -- Noise rules §6 1-8 are binding. Group window 5 min. Group updates silent until the group is 30 min old, then at most one "now also" an hour. Daily reminder after 24 h open. Flapping is 3 fire/clear cycles in 1 h, held until 1 h clear. One-off events self-close after 2 h (region has no room) or 24 h (others). |
| -- Snooze lengths: 1 h, 1 day, 1 week, scoped to (rule, subject). |
| -- Webhook and Slack URLs: |
| - - https on port 443 only |
| - - the dialled IP is checked at connect time |
| +- **Disk forecast:** |
| + - 6 h window, one point a minute |
| + - at least 2 h of span and 30 points before any verdict |
| + - fires at ETA ≤ 72 h, held 2 h |
| + - clears at ETA > 108 h, or on a no-growth verdict |
| +- **Noise rules** (spec §6, 1-8): |
| + - the first message waits until the incident is 5 min old and lists all members; fire and clear inside those 5 min sends nothing |
| + - updates are silent until the group is 30 min old, then at most one an hour |
| + - daily reminder after 24 h open |
| + - flapping is 3 fires in 1 h for one (scope, rule, subject), held until 1 h with no firing signal |
| + - one-offs close after 2 h quiet (`no_room`) or 24 h quiet (the others) |
| +- **Delivery is at least once:** each incident transition and its outbox rows commit in one SQLite transaction. Webhook bodies carry `delivery_id`. |
| +- **Outbound HTTP** (Slack and webhook): |
| + - `Transport.Proxy = nil` |
| + - https on port 443 only, revalidated on every send |
| + - the dialled IP is checked in `Dialer.Control` after `Unmap()` |
| - no redirects |
| - read at most 1 KiB of the response |
| - 5 s timeout |
| - - Slack connectors accept only `https://hooks.slack.com/` URLs |
| -- Webhook signature: header `Carlos-Signature: t=<unix>,ed25519=<std b64>` over `"carlos-alert\n" + t + "\n" + body`. Key row `keys.name = 'alert-sign'`. Body has `"v":1`. |
| -- Connector retries back off from 1 min to 12 h (as mailpush). A connector failing for 24 h is suspended, and the scope's owners are told once. |
| -- Email confirmation sends: 5 per scope per hour, 20 per day. |
| -- Request budget (spec §9): |
| - - the engine's every-minute read of `alerts/boxes/` uses `GetIfChanged` |
| - - heartbeats are read every 5 min, conditionally |
| - - an idle pass makes no unconditional GET |
| - - no new bucket objects in this plan |
| -- No AWS SDK import in any new package. SMS is not in this plan (spec §11.1). |
| -- Copy voice: no em dashes in user-facing text. All user-facing strings go through copy review (Task 9) before templates and messages are final. |
| + - errors are reduced to URL-free categories before anything stores or logs them |
| + - Slack connectors accept only host `hooks.slack.com` |
| +- **Webhook signature:** header `Carlos-Signature: t=<unix>,ed25519=<std b64>` over `"carlos-alert\n" + t + "\n" + body`. The key is the `keys` row `name = 'alert-sign'`. The body carries `"v":1`. |
| +- **Connector health:** |
| + - retries back off from 1 min, doubling, to a 12 h cap |
| + - a connector failing for 24 h is suspended, and the scope's owners are told once |
| +- **Consent:** |
| + - unconfirmed email connectors receive only their confirmation message |
| + - confirmation sends are limited to 5 per scope per hour and 20 per day |
| + - test sends are limited to 10 per connector per hour |
| +- **Tokens:** 32 random bytes, base64url, stored as SHA-256 hashes, each bound to one action and its target (Task 10). |
| +- **Request budget** (spec §9): no new bucket objects. Every engine read is a conditional GET from the engine's own etag cache, including heartbeats and `status/fleet.json`. LIST calls are limited to `alerts/boxes/` every pass and `status/boxes/` every 5th pass. |
| +- The engine runs only on a console with `cfg.HostClaim == false` (spec §5.2, one console per deployment). |
| +- No AWS SDK import in any new package. There is no SMS in this plan. |
| +- Copy voice: no em dashes in user-facing text. Every user-facing string goes through Task 9 before it is final. |
| - Run only touched packages' tests locally (`go test ./internal/<pkg> -run X -count=1`). CI runs the full gate. |
| -- `internal/host`, `internal/metrics` and `internal/alerting` are inside the root-read census. After Tasks 1-3, run `make census-card`. The reviewer approves the card (AGENTS.md "The census"). |
| +- **Census:** |
| + - `internal/host`, `internal/metrics`, `internal/alerting` and `internal/status` are inside the root-read census: run `make census-card` after Task 3. |
| + - The final proposal is in Task 11. |
| + - `NewServer`'s record-write census is re-pinned in Task 10. |
| ## Review Focus |
| -1. **A Slack URL that resolves to a private address after it was saved** (DNS rebinding). The dial must refuse it, because the check runs on the dialled IP, not at save time. Test in Task 5. |
| -2. **The console restarts mid-incident.** No duplicate "fired" message and no lost "cleared" message. Incident and delivery state live in console.db. Test in Task 7. |
| -3. **A box whose `alerts/boxes/<box>.json` disappears** (box retired). Its open incidents close with "no further reports", not "resolved", and it is never flagged as silent forever. Test in Task 8. |
| -4. **An operator with no confirmed connector and no grant.** They are reported once on the engine's own health line, not silently dropped. Test in Task 8. |
| -5. **The connector seal key file is missing or unreadable.** Sealed connectors read as "needs re-entering" and are skipped, with one operator incident. No panic and no unsealed fallback. Test in Task 4. |
| +1. **DNS rebinding and environment proxies.** A Slack or webhook URL that resolves to a private address at send time, or a process started with `HTTPS_PROXY` set, must never reach a refused address. Covered in Task 5. |
| +2. **Crash between steps.** A console that dies between committing an incident and sending, or between sending and recording, loses no clear and repeats at most one message. Covered in Tasks 4 and 8. |
| +3. **A box that never fired anything and then goes silent.** It is still flagged. Covered in Task 8. |
| +4. **A revoked operator.** They get nothing more, including retries already queued. Covered in Tasks 6 and 8. |
| +5. **A missing or unreadable seal key.** Sealed connectors read as "needs re-entering" and one operator incident fires. Email connectors keep working because addresses aren't sealed. Covered in Tasks 4 and 8. |
| --- |
| @@ -50,23 +73,23 @@ |
| | File | Responsibility | |
| |---|---| |
| -| `internal/metrics/forecast.go` (new) | Pure disk ETA fit | |
| -| `internal/metrics/alert.go` | `disk_eta` rule in `Rules`, `Observation`, `Evaluate` | |
| -| `internal/host/disktrend.go` (new) | 6 h ring of (time, used bytes), fed each tick | |
| -| `internal/host/metrics_loop.go` | Feed the ETA to `alertTick`. Box sinks get incident rules only | |
| -| `internal/host/alertsink.go` | Slack-shaped body when the webhook is on hooks.slack.com, plus the engine-silent rule | |
| -| `internal/alerting/alerting.go` | Slack-shaped body for `Sinks.Page` | |
| -| `internal/status/snapshot.go` | `BoxMetrics.DiskFullETAHours`, and `AlertDelivery.NotDelivered()` shared with the CLI | |
| -| `internal/console/alertstore.go` (new) | Tables and accessors: connectors, subscriptions, rule settings, incidents, deliveries, snoozes | |
| -| `internal/console/alertseal.go` (new) | AES-GCM key file, seal and open | |
| -| `internal/console/alertdial.go` (new) | Guarded HTTP client for outside URLs | |
| -| `internal/console/alertsign.go` (new) | `alert-sign` key, signing, public key | |
| -| `internal/console/alertengine.go` (new) | Pure incident step (the noise rules) | |
| -| `internal/console/alertsignals.go` (new) | Gathers signals from the bucket, heartbeats, fleet summary and console pages | |
| -| `internal/console/alertnotify.go` (new) | Senders and the delivery queue | |
| -| `internal/console/alertpages.go` (new) | `/fleet/alerts` handlers and public token doors | |
| -| `internal/console/templates/ops_alerts*.html` (new) | Pages | |
| -| `internal/console/alertwatch.go` | `alertPass` and its worker removed. Shared helpers kept | |
| +| `internal/metrics/forecast.go` (new) | Pure disk trend verdict | |
| +| `internal/metrics/alert.go` | `disk_eta` rule | |
| +| `internal/host/disktrend.go` (new) | 6 h ring, fed each tick | |
| +| `internal/host/probes.go` | New `readDiskBytes()`. `readDiskFrac` unchanged | |
| +| `internal/host/metrics_loop.go` | Trend feed. Box sinks get incident rules only | |
| +| `internal/host/enginebeat.go` (new) | Anchored, no-follow read of the engine beat | |
| +| `internal/host/alertsink.go`, `internal/alerting/alerting.go` | Slack-shaped body, no redirects | |
| +| `internal/status/snapshot.go` | `DiskFullETAHours`, `AlertDelivery.NotDelivered()` | |
| +| `internal/console/alertstore.go` (new) | Tables, the transactional step commit, outbox, tokens, flap history | |
| +| `internal/console/alertseal.go` (new) | Key file, seal and open | |
| +| `internal/console/alertdial.go` (new) | Guarded client, error categories | |
| +| `internal/console/alertsign.go` (new) | Signing key, signing | |
| +| `internal/console/alertengine.go` (new) | Pure `stepIncidents` | |
| +| `internal/console/alertsignals.go` (new) | Conditional loaders, signal collection, typed one-offs | |
| +| `internal/console/alertnotify.go` (new) | Senders, outbox drain | |
| +| `internal/console/alertpages.go` (new) | `/fleet/alerts` and token doors | |
| +| `internal/console/alertwatch.go` | `alertPass` and `StartAlertWatcher` removed. Shared helpers kept | |
| --- |
| @@ -80,140 +103,173 @@ |
| **Interfaces:** |
| - Produces: |
| - `type DiskPoint struct { At time.Time; UsedBytes, TotalBytes uint64 }` |
| - - `func DiskETA(points []DiskPoint, now time.Time) (hours float64, ok bool)`. `ok` is false with under 2 h of span, fewer than 30 points, or a slope ≤ 0. |
| - - `Rules.DiskETAHours float64` (default 72), `Rules.DiskETAHold time.Duration` (default 2 h) |
| - - `RulesFromEnv` reads `CARLOS_ALERT_DISK_ETA_HOURS` |
| - - `Observation.DiskETAHours *float64` |
| - - rule name `"disk_eta"` |
| + - `type TrendVerdict int`, with the constants `TrendUnknown`, `TrendNoGrowth` and `TrendGrowing` |
| + - `func DiskTrend(points []DiskPoint, now time.Time) (v TrendVerdict, etaHours float64)` |
| + - `TrendUnknown`: under 2 h of span or fewer than 30 points |
| + - `TrendNoGrowth`: the fitted slope is ≤ 0 |
| + - otherwise `TrendGrowing` with the ETA |
| + - `Rules.DiskETAHours float64`, default 72, from `CARLOS_ALERT_DISK_ETA_HOURS` |
| + - `Rules.DiskETAHold time.Duration`, default 2 h |
| + - `Observation.DiskTrend *TrendVerdict` and `Observation.DiskETAHours float64` |
| + - Rule name `"disk_eta"`. Its `RuleState.Value` is the ETA in hours, or 0 on a no-growth clear. It never serializes infinity. |
| - [ ] **Step 1: Write failing tests.** In `forecast_test.go`: |
| - - `TestDiskETASteadyFill`: 360 points over 6 h, used rising 1 GiB/h on a 100 GiB disk with 50 GiB used at `now`. Assert ETA is 50 h ±0.5. |
| - - `TestDiskETABurstThenFlat`: 5 GiB jump in the first 10 min, then flat for 3 h. Assert `ok == false` or ETA > 108. |
| - - `TestDiskETATooShort`: 90 min of points. Assert `ok == false`. |
| - - `TestDiskETAShrinking`: Assert `ok == false`. |
| + - `TestDiskTrendSteadyFill`: 360 points, +1 GiB/h on a 100 GiB disk, 50 GiB used now. Assert `TrendGrowing` and ETA 50 ±0.5. |
| + - `TestDiskTrendBurstThenFlat`: assert `TrendNoGrowth`, or an ETA over 108. |
| + - `TestDiskTrendTooShort`: assert `TrendUnknown`. |
| + - `TestDiskTrendShrinking`: assert `TrendNoGrowth`. |
| In `alert_test.go`: |
| - - `TestEvaluateDiskETAHoldsThenFires`: ETA 40 h each minute. No event before 2 h. Exactly one `Event{Rule:"disk_eta", Firing:true}` at 2 h. |
| - - `TestEvaluateDiskETAClears`: firing, then ETA 120 h gives one clear event. |
| - - `TestEvaluateDiskETANilKeepsState`: `nil` ETA while firing gives no event and the state is unchanged. |
| -- [ ] **Step 2: Run them, expect FAIL.** Run `go test ./internal/metrics -run 'DiskETA' -count=1`. |
| -- [ ] **Step 3: Implement.** `DiskETA` is an ordinary least-squares fit of used bytes against minutes over points no older than 6 h. ETA is `(Total - Used_now_fitted) / slope`, in hours. In `Evaluate`, add `evalETA("disk_eta", obs.DiskETAHours, r.DiskETAHours, r.DiskETAHold)`. It fires when ETA ≤ threshold, held. It clears when ETA > 1.5x threshold. `nil` leaves the state unchanged. |
| + - `TestEvaluateDiskETAHoldsThenFires`: one fire event at exactly 2 h. |
| + - `TestEvaluateDiskETAClearsOnHighETA` |
| + - `TestEvaluateDiskETAClearsOnNoGrowth` |
| + - `TestEvaluateDiskETAUnknownKeepsState` |
| +- [ ] **Step 2: Run them, expect FAIL.** Run `go test ./internal/metrics -run 'DiskTrend|DiskETA' -count=1`. |
| +- [ ] **Step 3: Implement.** `DiskTrend` is an ordinary least-squares fit of used bytes against minutes, over points at most 6 h old. ETA = (Total − fitted Used at now) / slope, in hours. `evalETA` fires when the ETA is ≤ threshold and has held for the hold. It clears on ETA > 1.5x threshold or on `TrendNoGrowth`. `TrendUnknown` and `nil` leave the state unchanged. |
| - [ ] **Step 4: Run them, expect PASS.** |
| - [ ] **Step 5: Commit.** `git commit -m "metrics: disk_eta forecast rule"` |
| -### Task 2: Box feeds the forecast; box sinks keep incidents only; heartbeat ETA |
| +### Task 2: Box feeds the forecast; sinks incident-only; heartbeat ETA |
| **Files:** |
| - Create: `internal/host/disktrend.go`, `internal/host/disktrend_test.go` |
| - Modify: |
| - - `internal/host/metrics_loop.go` (`alertTick` :513, `metricsLoop` :805) |
| - - `internal/host/probes.go:209` (`readDiskFrac`: also return used and total bytes) |
| - - `internal/status/snapshot.go` (`BoxMetrics`: `DiskFullETAHours *float64 \`json:"disk_full_eta_hours,omitempty"\``) |
| + - `internal/host/probes.go`: add `func readDiskBytes() (used, total uint64, ok bool)` beside `readDiskFrac` (:209), using `diskBytes(dataDir())` (`statfs_unix.go:15`). `readDiskFrac` and `sampleProbes.diskFrac` (`metrics_loop.go:34`) are unchanged. |
| + - `internal/host/metrics_loop.go` (`sampleProbes`: add `diskBytes func() (uint64, uint64, bool)`; `alertTick` :513; `metricsLoop` :805) |
| + - `internal/status/snapshot.go`: `BoxMetrics.DiskFullETAHours *float64 \`json:"disk_full_eta_hours,omitempty"\`` |
| - Test: `internal/host/metrics_loop_test.go` |
| **Interfaces:** |
| -- Consumes: `metrics.DiskPoint`, `metrics.DiskETA`, `Observation.DiskETAHours` (Task 1) |
| +- Consumes: Task 1 |
| - Produces: |
| - - `type diskTrend struct` with `add(p metrics.DiskPoint)` and `eta(now time.Time) (float64, bool)`. The ring holds 360 points. |
| - - `alertTick` gains a `trend *diskTrend` parameter. |
| - - `func boxSinkRule(rule string) bool`, true only for `"disk"` and `"engine_silent"` (Task 3). |
| + - `type diskTrend struct`, with `add(p metrics.DiskPoint)` and `verdict(now time.Time) (metrics.TrendVerdict, float64)`. The ring holds 360 points and is safe for one writer and one reader. |
| + - `alertTick` gains a final parameter, `trend *diskTrend`. Every caller and test is updated. |
| + - `func boxSinkRule(rule string) bool` is true only for `"disk"` and `"engine_silent"`. |
| - [ ] **Step 1: Write failing tests.** |
| - - `TestDiskTrendRingKeeps360`: 400 adds, `len == 360`, oldest dropped. |
| - - `TestAlertTickSinksIncidentOnly`: with a fake sink, a `disk_eta` fire event is written to state but not sent. A `disk` fire event is sent. |
| - - `TestAlertTickETAInHeartbeat`: the ETA is exposed for the snapshot writer, through the same shared value the heartbeat reads. |
| -- [ ] **Step 2: Run them, expect FAIL.** Run `go test ./internal/host -run 'DiskTrend|AlertTick' -count=1`. |
| -- [ ] **Step 3: Implement.** |
| - - `metricsLoop` builds one `diskTrend`. Each tick it adds `(now, total-avail, total)` from `diskBytes(dataDir())`, which is already called inside `readDiskFrac`, so there's no extra statfs. |
| - - `alertTick` sets `obs.DiskETAHours` from `trend.eta`. |
| - - The sink loop (:531-535) skips events where `!boxSinkRule(ev.Rule)`. |
| - - The status snapshot writer copies the latest ETA into `BoxMetrics.DiskFullETAHours`. |
| + - `TestDiskTrendRingKeeps360` |
| + - `TestAlertTickSinksIncidentOnly`: a `disk_eta` fire reaches the state file but not the sink. A `disk` fire reaches both. |
| + - `TestAlertTickDeletionClearsForecast`: drive the ring through `alertTick` with growth until it fires, then flat for 2 h. Expect one clear. |
| + - `TestSnapshotCarriesDiskETA` |
| +- [ ] **Step 2: Run them, expect FAIL.** Run `go test ./internal/host -run 'DiskTrend|AlertTick|SnapshotCarriesDiskETA' -count=1`. |
| +- [ ] **Step 3: Implement.** `metricsLoop` owns one `diskTrend` and adds a point each tick from `probes.diskBytes`. `alertTick` sets the observation from `trend.verdict`. The sink loop (:531-535) skips any event where `!boxSinkRule(ev.Rule)`. The snapshot writer reads the trend's last ETA, and only when the verdict is `TrendGrowing`. |
| - [ ] **Step 4: Run them, expect PASS.** |
| -- [ ] **Step 5: Commit.** `git commit -m "host: disk trend ring, disk_eta observation, box sinks incident-only"` |
| +- [ ] **Step 5: Commit.** `git commit -m "host: disk trend ring, disk_eta, box sinks incident-only"` |
| -### Task 3: Slack-shaped sink body; engine-silent backstop |
| +### Task 3: Slack sink body, no redirects, engine-silent backstop |
| **Files:** |
| +- Create: `internal/host/enginebeat.go`, `internal/host/enginebeat_linux_test.go` |
| - Modify: |
| - `internal/alerting/alerting.go` (`Sinks.Page` :115, `PostJSON` :224) |
| - `internal/host/alertsink.go` (`deliver` :93) |
| - `internal/host/metrics_loop.go` |
| - `internal/status/snapshot.go` (`AlertDelivery`) |
| - - `cli.go:4163` (`alertsWord` uses the shared method) |
| + - `cli.go:4163` (`alertsWord` uses the new method) |
| - Test: `internal/alerting/alerting_test.go`, `internal/host/alertsink_test.go`, `internal/status/snapshot_test.go` |
| **Interfaces:** |
| - Produces: |
| - - `func alerting.IsSlackWebhook(url string) bool`: true for host `hooks.slack.com` over https. |
| - - `func alerting.SlackBody(subject, body string) []byte`, which gives `{"text":"*<subject>*\n<body>"}`. |
| - - `func (d *status.AlertDelivery) NotDelivered() bool`: `!Webhook && !SNS && !SNSUnavailable`, the same as `alertsWord` today. |
| - - Box rule `"engine_silent"`, level incident. It's armed only when `CARLOS_ALERT_ENGINE_BEAT` names a file. It fires when that file's mtime is over 10 min old, and clears when it's fresh. |
| + - `func alerting.IsSlackWebhook(u string) bool` |
| + - `func alerting.SlackBody(subject, body string) []byte`, giving `{"text":"*<subject>*\n<body>"}` |
| + - `func (d *status.AlertDelivery) NotDelivered() bool`, which equals `alertsWord`'s test |
| + - `func engineBeatAge(path string, now time.Time) (age time.Duration, ok bool)` |
| + - opens with `rootstate.OpenTrustedFileFrom(filepath.Dir(path), path)` (regular file, one link, owned by the directory's owner, no group or other write) and reads the mtime with `Fstat` on that descriptor |
| + - `ok = false` when the file is missing, untrusted, not regular, or has an mtime in the future |
| + - on non-linux it always returns `ok = false` |
| + - Box rule `"engine_silent"`, level incident: |
| + - armed only when `CARLOS_ALERT_ENGINE_BEAT` is set |
| + - fires when `ok` and age > 10 min |
| + - also fires when the file is missing for 10 consecutive minutes after it was once seen |
| + - an untrusted file logs once and holds the rule's state |
| + - clears when fresh |
| - [ ] **Step 1: Write failing tests.** |
| - - `TestPageSlackBody`: `Sinks{WebhookURL:"https://hooks.slack.com/services/T/B/X"}`. The posted body unmarshals to a `text` field containing the subject. No `kind` field. |
| - - `TestPageNonSlackUnchanged`: another URL still gets `pagePayload`. |
| - - `TestBoxDeliverSlackBody`: the same check for `alertSinks.deliver` with a `metrics.Event`. The text is `formatAlert(...)`. |
| - - `TestPostJSONRefusesRedirect`: a redirect to another host is not followed. |
| - - `TestAlertDeliveryNotDelivered`: table over the three booleans, matching `alertsWord`. |
| - - `TestEngineSilentRule`: beat mtime 11 min old fires `engine_silent` and it reaches the sink. Fresh clears it. Env unset means the rule never appears. |
| + - `TestPageSlackBody` |
| + - `TestPageNonSlackUnchanged` |
| + - `TestBoxDeliverSlackBody` |
| + - `TestPostJSONRefusesRedirect` |
| + - `TestAlertDeliveryNotDelivered` |
| + - `TestEngineBeatAgeSymlinkRefused` (linux): the beat is a symlink to a fresh root file, so `ok` is false. |
| + - `TestEngineBeatAgeFutureMtime` |
| + - `TestEngineSilentFiresThroughAlertTick`: an 11-min-old beat fires and reaches the sink. A fresh beat clears. With the env unset the rule is absent. |
| - [ ] **Step 2: Run them, expect FAIL.** |
| -- [ ] **Step 3: Implement.** |
| - - The Slack branch goes in `Sinks.Page` and `alertSinks.deliver`. |
| - - `PostJSON` gets `CheckRedirect` returning `http.ErrUseLastResponse`. |
| - - `engine_silent` is read in `alertTick` with one `os.Stat` per tick. It's a root read of an env-named path, so the census card must list it. |
| +- [ ] **Step 3: Implement** to the interfaces above. `PostJSON` sets `CheckRedirect` to return `http.ErrUseLastResponse`. |
| - [ ] **Step 4: Run them, expect PASS.** |
| -- [ ] **Step 5: Census and commit.** Run `make census-card` and save the output to `docs/superpowers/notes/census-card-fleet-alerts-1.txt`. Then `git commit -m "alerting: Slack body, no redirects; host: engine_silent backstop"`. |
| +- [ ] **Step 5: Census and commit.** Run `make census-card` and save the output to `docs/superpowers/notes/census-card-fleet-alerts-1.txt`. The `engine_silent` read goes through `rootstate.OpenTrustedFileFrom`. Then `git commit -m "alerting: Slack body, no redirects; host: anchored engine_silent backstop"`. |
| -### Task 4: Alert tables, connector seal |
| +### Task 4: Alert store: tables, transactional step, seal |
| **Files:** |
| -- Create: `internal/console/alertstore.go`, `internal/console/alertseal.go`, plus `_test.go` for each |
| +- Create: `internal/console/alertstore.go`, `internal/console/alertseal.go`, plus tests |
| - Modify: |
| - - `internal/console/store.go` (call `s.migrateAlerts()` after the list, as `migrateOperatorPages`, :605-655) |
| - - `internal/console/store_gate.go:190` (`claimSQLTables`) |
| + - `internal/console/store.go` (call `s.migrateAlerts()` after the list, as `migrateOperatorPages` does, :605-655) |
| + - `internal/console/store_gate.go:190` (`claimSQLTables`: one `NonApp` entry per new table) |
| **Interfaces:** |
| -- Tables (all `CREATE TABLE IF NOT EXISTS`): |
| - - `alert_connectors`: `id INTEGER PK, scope TEXT, kind TEXT, name TEXT, target_sealed BLOB, target_hint TEXT, confirm_token TEXT, confirmed_at INTEGER, failing_since INTEGER, suspended_at INTEGER, needs_reentry INTEGER, created_by TEXT, created_at INTEGER`. Kind is `slack`, `webhook` or `email`. `target_hint` is the host plus the last 4 characters. |
| - - `alert_rules`: `scope, rule, enabled INTEGER, threshold REAL NULL, PRIMARY KEY(scope, rule)` |
| - - `alert_subscriptions`: `scope, rule, connector_id, PRIMARY KEY(scope, rule, connector_id)` |
| - - `alert_incidents`: `id INTEGER PK, scope, rule, level, opened_at, last_seen_at, closed_at NULL, close_reason TEXT, members TEXT /*JSON []string*/, cycles TEXT /*JSON []int64 fire times*/, flapping INTEGER, last_notified_at, last_reminder_at, last_update_at` |
| - - `alert_deliveries`: `id INTEGER PK, incident_id, connector_id, kind TEXT, attempts, next_at, sent_at NULL, last_error TEXT`. Kind is `fire`, `clear`, `update`, `reminder` or `test`. |
| - - `alert_snoozes`: `scope, rule, subject, until INTEGER, PRIMARY KEY(scope, rule, subject)` |
| - - Every table goes in `claimSQLTables` as `NonApp` with a one-line reason. |
| +- Tables: |
| + - `alert_connectors`: |
| + - `id PK, scope, kind, name, target_sealed BLOB NULL, target_plain TEXT NULL, target_hint, owner_address TEXT NULL, confirmed_at, failing_since, suspended_at, needs_reentry, created_by, created_at` |
| + - email keeps its address in `target_plain`. Slack and webhook use `target_sealed`. |
| + - `owner_address` is set for an operator's seeded personal connector. |
| + - `alert_rules`: `scope, rule, enabled, threshold REAL NULL, PK(scope, rule)` |
| + - `alert_subscriptions`: `scope, rule, connector_id, PK(...)` |
| + - `alert_incidents`: `id PK, scope, rule, level, opened_at, notify_at, last_seen_at, closed_at NULL, close_reason, members JSON, flapping, one_off, quiet_secs, notified INTEGER, last_reminder_at, last_update_at`. `notify_at` is `opened_at + 5 min`. `notified` is 0 until the first message is queued. |
| + - `alert_fires`: `scope, rule, subject, fired_at`, pruned past 1 h. This is the flap history, independent of incidents. |
| + - `alert_outbox`: `id PK, delivery_id TEXT UNIQUE, incident_id, connector_id, kind, body_json, attempts, next_at, sent_at NULL, err_category TEXT` |
| + - `alert_tokens`: `hash PK, action, scope, connector_id NULL, rule NULL, subject NULL, expires_at NULL, used_at NULL`. The action is `confirm`, `unsubscribe` or `snooze`. |
| + - `alert_snoozes`: `scope, rule, subject, until, PK(...)` |
| + - `alert_oneoffs`: `id PK, scope, rule, subject, level, title, body, quiet_secs, at`. Rows are durable from `raise` until a step consumes them. |
| - Produces: |
| - - `type alertConnector struct{ ID int64; Scope, Kind, Name, TargetHint string; Confirmed, Suspended, NeedsReentry bool; FailingSince time.Time }` |
| + - `type alertConnector struct{ ID int64; Scope, Kind, Name, TargetHint, OwnerAddress string; Confirmed, Suspended, NeedsReentry bool; FailingSince time.Time }` |
| - `type alertRuleSetting struct{ Enabled bool; Threshold *float64; ConnectorIDs []int64 }` |
| - - `type alertIncident struct{ ID int64; Scope, Rule, Level string; OpenedAt, LastSeenAt, ClosedAt time.Time; CloseReason string; Members []string; Cycles []time.Time; Flapping bool; LastNotifiedAt, LastReminderAt, LastUpdateAt time.Time; QuietWindow time.Duration; OneOff bool }`. `QuietWindow` and `OneOff` are copied from the first signal and persisted as two extra columns `quiet_secs INTEGER, one_off INTEGER`. |
| - - `type alertDelivery struct{ ID, IncidentID, ConnectorID int64; Kind string; Attempts int; NextAt time.Time }` |
| - - Store methods: `AlertConnectors(scope string) ([]alertConnector, error)`, `AddAlertConnector(c alertConnector, sealed []byte, confirmToken string) (int64, error)`, `ConfirmAlertConnector(token string) (alertConnector, bool, error)`, `DeleteAlertConnector(scope string, id int64) error`, `AlertConnectorTarget(id int64) ([]byte, error)`, `SetConnectorHealth(id int64, ok bool, now time.Time) (suspendedNow bool, err error)`, `MarkConnectorsNeedReentry(scope string) error` |
| - - Rule settings: `AlertRuleSettings(scope string) (map[string]alertRuleSetting, error)`, `SetAlertRule(scope, rule string, enabled bool, threshold *float64, connectorIDs []int64) error` |
| - - Incidents and deliveries: `OpenIncidents(scope string) ([]alertIncident, error)`, `SaveIncident(inc *alertIncident) error`, `RecentIncidents(scope string, limit int) ([]alertIncident, error)`, `QueueDeliveries(incidentID int64, kind string, connectorIDs []int64, now time.Time) error`, `DueDeliveries(now time.Time, limit int) ([]alertDelivery, error)`, `FinishDelivery(id int64, err error, now time.Time) error` |
| - - Snoozes: `Snooze(scope, rule, subject string, until time.Time) error`, `Snoozed(scope, rule, subject string, now time.Time) (bool, error)` |
| + - `type alertIncident struct{ ID int64; Scope, Rule, Level string; OpenedAt, NotifyAt, LastSeenAt, ClosedAt time.Time; CloseReason string; Members []string; Flapping, OneOff, Notified bool; Quiet time.Duration; LastReminderAt, LastUpdateAt time.Time }` |
| + - `type alertOutboxRow struct{ ID int64; DeliveryID string; IncidentID, ConnectorID int64; Kind string; Body []byte; Attempts int; NextAt time.Time }` |
| + - `func (s *Store) CommitAlertStep(changed []alertIncident, fires []alertFire, outbox []alertOutboxRow, consumedOneOffs []int64) error`, one transaction |
| + - `func (s *Store) AlertStepInputs(now time.Time) (open []alertIncident, recentFires map[alertKey][]time.Time, oneOffs []alertOneOff, err error)` |
| + - `DueOutbox(now time.Time, limit int) ([]alertOutboxRow, error)` |
| + - `FinishOutbox(id int64, cat string, ok bool, now time.Time) error`, with backoff 1m·2^attempts capped at 12 h |
| + - Connector accessors: |
| + - `AlertConnectors(scope string) ([]alertConnector, error)` |
| + - `AddAlertConnector(c alertConnector, sealed []byte, plain string) (int64, error)` |
| + - `ConfirmAlertConnector(id int64) error` |
| + - `DeleteAlertConnector(scope string, id int64) error` |
| + - `AlertConnectorTarget(id int64) (sealed []byte, plain string, err error)` |
| + - `SetConnectorHealth(id int64, ok bool, now time.Time) (suspendedNow bool, err error)` |
| + - `MarkSealedConnectorsNeedReentry() (n int, err error)` |
| + - Rule accessors: `AlertRuleSettings(scope string) (map[string]alertRuleSetting, error)`, `SetAlertRule(scope, rule string, s alertRuleSetting) error` |
| + - Snooze accessors: `Snooze(scope, rule, subject string, until time.Time) error`, `Snoozed(scope, rule, subject string, now time.Time) (bool, error)` |
| + - Token accessors: `NewAlertToken(t alertToken) (raw string, err error)`, `UseAlertToken(raw, action string, now time.Time) (alertToken, error)`. `UseAlertToken` checks the action, the expiry and, for confirm, single use. |
| + - `RaiseOneOff(o alertOneOff) error` |
| - Seal: |
| - `type connectorSeal struct` |
| - - `func openConnectorSeal(path string) (*connectorSeal, error)` creates a 32-byte key with 0600 when absent. |
| - - `Seal(plain []byte) ([]byte, error)` returns nonce‖ciphertext. |
| - - `Open(sealed []byte) ([]byte, error)` |
| - - The key path is `filepath.Join(filepath.Dir(CONSOLE_DB), "alert-connectors.key")`, carried as `Config.AlertSealKeyPath`. |
| - - The `FinishDelivery` backoff is `1m * 2^attempts`, capped at 12 h. |
| + - `func openConnectorSeal(path string) (seal *connectorSeal, created bool, err error)`: creates a 32-byte key at 0600 only when the path is absent. An unreadable key is an error, never a fresh key. |
| + - `Seal(p []byte) ([]byte, error)` and `Open(c []byte) ([]byte, error)`, with output nonce‖ciphertext |
| + - The key path is `Config.AlertSealKeyPath`, defaulting to `filepath.Join(filepath.Dir(CONSOLE_DB), "alert-connectors.key")` |
| - [ ] **Step 1: Write failing tests.** |
| - - `TestAlertTablesMigrateTwice`: running migrate twice is a no-op. |
| + - `TestAlertTablesMigrateTwice` |
| + - `TestCommitAlertStepAtomic`: a forced failure on the outbox insert (via a trigger in the test DB) leaves no incident change behind. |
| + - `TestCommitAlertStepSurvivesReopen` |
| + - `TestOutboxDeliveryIDUnique` |
| + - `TestFinishOutboxBackoff` |
| - `TestConnectorSealRoundTrip` |
| - - `TestConnectorSealKeyFileMode0600` |
| - - `TestConnectorSealMissingKeyAfterSeal`: seal, delete the key file, reopen (a new key), then `Open` errors. The caller's `MarkConnectorsNeedReentry` sets the flag. This is Review Focus 5. |
| - - `TestConfirmTokenOneUse` |
| - - `TestSetConnectorHealthSuspendsAfter24h`: true exactly once. |
| - - `TestFinishDeliveryBackoff`: next_at steps 1m, 2m, 4m … capped at 12 h. |
| + - `TestConnectorSealKeyMode0600` |
| + - `TestConnectorSealUnreadableKeyErrors`: an existing key file at 0000 returns an error and creates no key. |
| + - `TestMarkSealedNeedReentryLeavesEmail` |
| + - `TestAlertTokenActionBound`: a confirm token used as unsubscribe is refused. |
| + - `TestAlertTokenConfirmOneUse` |
| + - `TestAlertTokenExpired` |
| + - `TestSetConnectorHealthSuspendsOnce` |
| - `TestSnoozeExpires` |
| - - `TestClaimSQLTablesCoverAlertTables`: the existing classification test passes with the new tables. |
| -- [ ] **Step 2: Run them, expect FAIL.** Run `go test ./internal/console -run 'AlertTables|ConnectorSeal|ConfirmToken|ConnectorHealth|FinishDelivery|Snooze|ClaimSQL' -count=1`. |
| -- [ ] **Step 3: Implement.** Follow `move_pages` (store.go:376, :2584-2610) for accessor style. AES-GCM uses `crypto/cipher.NewGCM` with a random 12-byte nonce. |
| + - `TestFlapHistoryPrunedAfterHour` |
| + - `TestClaimSQLTablesClassified` |
| +- [ ] **Step 2: Run them, expect FAIL.** |
| +- [ ] **Step 3: Implement.** Follow `move_pages` (store.go:376, :2584-2610) for accessor style. Every write in `CommitAlertStep` uses one `tx`. |
| - [ ] **Step 4: Run them, expect PASS.** |
| -- [ ] **Step 5: Commit.** `git commit -m "console: alert tables and connector seal"` |
| +- [ ] **Step 5: Commit.** `git commit -m "console: alert store, transactional step, connector seal"` |
| -### Task 5: Guarded outside-URL client and alert signing |
| +### Task 5: Guarded outbound client and alert signing |
| **Files:** |
| - Create: `internal/console/alertdial.go`, `internal/console/alertsign.go`, plus tests |
| @@ -221,147 +277,212 @@ |
| **Interfaces:** |
| - Produces: |
| - - `func validConnectorURL(kind, raw string) (*url.URL, error)` |
| - - https, no userinfo, port empty or 443 |
| - - for `slack`: host must be `hooks.slack.com` |
| - - for `webhook`: any public host name; an IP literal is checked as below |
| - - `func refusedAddr(ip netip.Addr) bool` refuses: |
| - - loopback, private (RFC1918, ULA), link-local (v4 and v6) |
| - - CGNAT 100.64.0.0/10 |
| - - unspecified and multicast |
| - - 169.254.169.254 and fd00:ec2::254 |
| - - IPv4-mapped forms of all of these |
| - - any address in a caller-supplied box list |
| - - `func newAlertHTTPClient(boxAddrs func() []netip.Addr) *http.Client` |
| - - `net.Dialer.Control` parses the dialled address and refuses `refusedAddr`, so it checks the IP being connected to |
| - - `CheckRedirect` gives `http.ErrUseLastResponse` |
| + - `func validConnectorURL(kind, raw string) (*url.URL, error)`: https, no userinfo, port empty or 443, no IP-literal host. A `slack` URL needs host `hooks.slack.com`. |
| + - `func refusedAddr(ip netip.Addr) bool` |
| + - `Unmap()` first |
| + - refuses loopback, private (RFC 1918 and ULA), link-local, CGNAT 100.64/10, unspecified, multicast, 169.254.169.254, fd00:ec2::254, 0.0.0.0/8 and 192.0.0.0/24 |
| + - `func newAlertHTTPClient(refused func(netip.Addr) bool) *http.Client` |
| + - `Transport: &http.Transport{Proxy: nil, DialContext: (&net.Dialer{Timeout: 5s, Control: <parse addr, refuse>}).DialContext, TLSHandshakeTimeout: 5s, ForceAttemptHTTP2: true}` |
| + - `CheckRedirect` returns `http.ErrUseLastResponse` |
| - `Timeout: 5 * time.Second` |
| - - `func postAlert(ctx context.Context, c *http.Client, u string, body []byte, headers map[string]string) (status int, err error)` reads at most 1 KiB and treats only 2xx as ok. |
| + - Production passes `refusedAddr`. Tests may pass a wrapper that also allows loopback. |
| + - `type sendErr string`, with categories `"refused"`, `"timeout"`, `"connect"`, `"tls"`, `"status <N>"`, `"invalid"` |
| + - `func postAlert(ctx context.Context, c *http.Client, kind, raw string, body []byte, hdr map[string]string) sendErr` |
| + - calls `validConnectorURL` again on every send |
| + - reads at most 1 KiB of the response |
| + - returns `""` on 2xx |
| + - never returns or logs the `*url.Error` or the URL |
| - `const alertSignatureLabel = "carlos-alert"` |
| - `func signAlert(priv ed25519.PrivateKey, t time.Time, body []byte) string` |
| - `func alertPublicKey(priv ed25519.PrivateKey) string` |
| - [ ] **Step 1: Write failing tests.** |
| - - `TestRefusedAddrTable`: one row per refused class, including `::ffff:10.0.0.1`, `100.100.1.1` and `169.254.169.254`. Public `1.1.1.1` and `2606:4700::1111` are allowed. |
| - - `TestValidConnectorURL`: refuses http, `:8443`, userinfo, and a non-Slack host for kind slack. |
| - - `TestAlertClientRefusesRebind`: a resolver stub returns a public IP at validation and 127.0.0.1 at dial. The POST errors and the local server is never hit. This is Review Focus 1. Inject the resolver through `net.Dialer.Resolver` or a dial hook on the client. |
| + - `TestRefusedAddrTable`: every class, including `::ffff:10.0.0.1`, `::ffff:127.0.0.1`, `100.100.1.1` and `169.254.169.254`. Allowed: `1.1.1.1` and `2606:4700::1111`. |
| + - `TestValidConnectorURL` |
| + - `TestAlertClientRefusesRebind`: a dial hook resolves the public name to 127.0.0.1. Expect `"refused"`, and the local server sees no request. |
| + - `TestAlertClientIgnoresProxyEnv`: set `HTTPS_PROXY` to a recording proxy. The proxy sees nothing. |
| - `TestAlertClientNoRedirect` |
| - `TestPostAlertReadsAtMost1KiB` |
| - - `TestSignAlertVerifies`: the signature verifies over the label, timestamp and body. A mail-event label doesn't verify. |
| + - `TestPostAlertErrorHasNoURL`: a timeout against a URL with the secret `sekrit-XYZ` returns a category without it. |
| + - `TestSignAlertVerifies`: a mail-event label fails. |
| - [ ] **Step 2: Run them, expect FAIL.** |
| - [ ] **Step 3: Implement** to the interfaces above. |
| - [ ] **Step 4: Run them, expect PASS.** |
| -- [ ] **Step 5: Commit.** `git commit -m "console: guarded alert HTTP client and alert signing key"` |
| +- [ ] **Step 5: Commit.** `git commit -m "console: guarded alert client, URL-free errors, alert signing"` |
| -### Task 6: Senders and the delivery queue |
| +### Task 6: Senders and outbox drain |
| **Files:** |
| - Create: `internal/console/alertnotify.go`, `internal/console/alertnotify_test.go` |
| **Interfaces:** |
| -- Consumes: Task 4 store and seal, Task 5 client and signing, `s.deliver` (`delivery.go:41`) |
| +- Consumes: Tasks 4 and 5, and `s.deliver` (`delivery.go:41`) |
| - Produces: |
| - - `type alertMessage struct{ Scope, Rule, Level, Kind, Subject, What, HowLong, WhatToDo, IncidentURL, SnoozeURL string; Members []string; At time.Time }` |
| - - `type alertSender interface { send(ctx context.Context, c alertConnector, target []byte, m alertMessage) error }` |
| - - The `slackSender` body is `{"text": <fallback>, "blocks": [...]}`. The `webhookSender` body is `{"v":1,"scope","rule","level","kind","subject","members","at","incident_url"}`, signed. The `emailSender` goes through `s.deliver(ctx, address, subject, body, 12*time.Second)`. |
| - - `func (s *Server) alertDeliverPass(ctx context.Context) error` handles at most 50 due deliveries a pass. It opens the target, sends, and calls `FinishDelivery`. It calls `SetConnectorHealth`, and when that suspends, it queues one "connector suspended" message to the scope's other connectors, or to owner email when there are none. |
| + - `type alertNote struct{ Scope, Rule, Level, Kind, Subject, What, HowLong, WhatToDo, IncidentURL, SnoozeURL, UnsubscribeURL string; Members []string; At time.Time; DeliveryID string }`. It is named to avoid the existing `func alertMessage`. |
| + - `func renderSlack(n alertNote) []byte` gives `{"text", "blocks"}` |
| + - `func renderWebhook(n alertNote) []byte` gives `{"v":1,"delivery_id","scope","rule","level","kind","subject","members","at","incident_url"}` |
| + - `func renderEmail(n alertNote) (subject, body string)`, whose body always ends with the unsubscribe link |
| + - `func (s *Server) alertDrainOutbox(ctx context.Context) error`, at most 50 rows a pass. Before each send it checks: |
| + - the connector is not deleted, suspended or `needs_reentry` |
| + - email is confirmed (confirmation rows are exempt) |
| + - a connector with `OwnerAddress` is still an operator (`s.store.IsOperator`). If not, the row and the connector are deleted (Review Focus 4). |
| + - Delivery: |
| + - email goes through `s.deliver(ctx, addr, subject, body, 12*time.Second)` |
| + - Slack and webhook go through `postAlert` |
| + - each row ends with `FinishOutbox` |
| + - on suspension, one "connector suspended" outbox row goes to the scope's other connectors, or to owner email when there are none |
| - `func (s *Server) sendTestAlert(ctx context.Context, scope string, id int64) error` |
| + - refused for unconfirmed email |
| + - otherwise limited to 10 per connector per hour |
| + - for Slack, the test text carries a fresh one-use confirm link (a `confirm` token bound to the connector) |
| + - for a webhook, a 2xx test confirms it directly |
| - [ ] **Step 1: Write failing tests.** |
| - - `TestSlackSenderBody`: has `text` and `blocks`. `text` holds the subject, what, how long, what to do, and the snooze link. |
| - - `TestWebhookSenderSignedV1` |
| - - `TestEmailSenderUsesDeliver`: capture `deliver` through the fixture. |
| - - `TestDeliverPassRetriesThenSucceeds` |
| - - `TestDeliverPassSuspendsAfter24hAndTellsOnce` |
| - - `TestDeliverPassSkipsNeedsReentry` |
| + - `TestRenderSlack` |
| + - `TestRenderWebhookSignedV1` |
| + - `TestRenderEmailHasUnsubscribe` |
| + - `TestDrainRetriesThenSucceeds` |
| + - `TestDrainSuspendsAfter24hTellsOnce` |
| + - `TestDrainSkipsNeedsReentry` |
| + - `TestDrainSkipsRevokedOperatorQueued`: queue a row, revoke the operator, drain. There is no send, and the row and connector are gone. |
| + - `TestDrainUnconfirmedEmailGetsNothing` |
| + - `TestTestSendRefusedForUnconfirmedEmail` |
| + - `TestTestSendRateLimited`: the 11th in an hour is refused. |
| + - `TestDrainErrorStoredHasNoSecret`: the `err_category` column and the captured log hold no `sekrit-XYZ`. |
| - [ ] **Step 2: Run them, expect FAIL.** |
| -- [ ] **Step 3: Implement.** Message text comes from the Task 9 copy deck. Until it's approved, use the deck's draft strings in one `alertCopy` map so the swap is a single file. |
| +- [ ] **Step 3: Implement.** Text comes from the `alertCopy` map, the draft strings until Task 9 replaces them. |
| - [ ] **Step 4: Run them, expect PASS.** |
| -- [ ] **Step 5: Commit.** `git commit -m "console: alert senders and delivery queue"` |
| +- [ ] **Step 5: Commit.** `git commit -m "console: alert senders and outbox drain"` |
| -### Task 7: Incident engine (pure noise rules) |
| +### Task 7: Incident step (pure noise rules) |
| **Files:** |
| - Create: `internal/console/alertengine.go`, `internal/console/alertengine_test.go` |
| **Interfaces:** |
| - Produces: |
| - - `type alertSignal struct{ Scope, Rule, Level, Subject string; Firing bool; OneOff bool; QuietWindow time.Duration; Value float64; At time.Time }`. Subject is a box name or the site of a one-off. |
| - - `type alertOut struct{ Incident *alertIncident; Kind string }`. Kind is `fire`, `clear`, `update` or `reminder`. |
| - - `func stepIncidents(open []alertIncident, signals []alertSignal, snoozed func(scope, rule, subject string) bool, now time.Time) (next []alertIncident, out []alertOut)` |
| - - **Grouping:** signals with the same (scope, rule) firing within 5 min of the incident opening join `Members`. |
| - - **Clear:** an incident clears when every member has a non-firing signal. For a one-off it clears when `now - last_seen_at ≥ QuietWindow`, with `close_reason` set to `"quiet"`. |
| - - **Flapping:** 3 fire times within 1 h set `flapping`. The incident then stays open until 1 h with no firing signal. |
| - - **Reminder:** at most one every 24 h while open. |
| - - **Late members:** a new member after 30 min gives at most one `update` an hour. |
| - - **Snooze:** a snoozed (rule, subject) is dropped from `out` but still tracked in `next`. |
| - |
| -- [ ] **Step 1: Write the simulation tests.** Each is a scripted timeline of signals, asserting the exact `out` kinds and times: |
| + - `type alertKey struct{ Scope, Rule, Subject string }` |
| + - `type alertSignal struct{ Key alertKey; Level string; Firing, OneOff bool; Quiet time.Duration; Value float64; At time.Time; Gone bool }`. `Gone` means the source vanished, which closes the incident with `close_reason "box gone"`. |
| + - `type alertFire struct{ Key alertKey; At time.Time }` |
| + - `type alertEmit struct{ Incident alertIncident; Kind string }`. `Kind` is `fire`, `clear`, `update` or `reminder`. |
| + - `func stepIncidents(open []alertIncident, recentFires map[alertKey][]time.Time, signals []alertSignal, snoozed func(alertKey) bool, now time.Time) (changed []alertIncident, fires []alertFire, emits []alertEmit)`, implementing spec §6: |
| + - **Grouping:** signals with the same (scope, rule) that fire before an open incident's `NotifyAt` join its members. |
| + - **First message:** `fire` is emitted when `now ≥ NotifyAt` and the incident is still open. An incident closed before `NotifyAt` emits nothing. |
| + - **Clear:** every member not firing, a one-off quiet for `Quiet`, or `Gone`. A clear is emitted only when the incident was `Notified`. One-off and gone clears carry the reason "no further reports". |
| + - **Flapping:** 3 entries in `recentFires` for a key within 1 h set `Flapping`. The incident then stays open until 1 h with no firing signal. |
| + - **Reminder:** at most one per 24 h. |
| + - **Updates:** a member joining after `NotifyAt` and after 30 min gives at most one `update` an hour. |
| + - **Snooze:** a snoozed key emits nothing but is still tracked. |
| + |
| +- [ ] **Step 1: Write the simulation tests**, each a scripted timeline: |
| + - `TestStepGroupsStaggeredFiveBoxes`: boxes join at minutes 0-4 across separate steps. One `fire` at minute 5 with 5 members. |
| + - `TestStepFireClearInsideWindowSilent` |
| - `TestStepOneFireOneClear` |
| - - `TestStepGroupsFiveBoxes`: one fire, members = 5 |
| - `TestStepLateMemberUpdateHourly` |
| - - `TestStepFlapping` |
| + - `TestStepFlappingAcrossIncidents`: fire, clear, fire, clear, fire, with incidents closing in between. Flapping is set from `recentFires`. |
| - `TestStepDailyReminder` |
| - - `TestStepOneOffQuietCloses2h` and `24h` |
| - - `TestStepSnoozeSuppressesOut` |
| - - `TestStepRestartNoDuplicate`: feed `next` back in as `open` with the same signals, and `out` is empty. This is Review Focus 2. |
| + - `TestStepOneOffQuietCloses` at 2 h and at 24 h |
| + - `TestStepGoneCloses` |
| + - `TestStepSnoozeSuppresses` |
| + - `TestStepRestartNoDuplicate`: replay `changed` as `open` with the same signals, and `emits` is empty. |
| - [ ] **Step 2: Run them, expect FAIL.** |
| - [ ] **Step 3: Implement `stepIncidents`.** It is pure: no store and no clock beyond `now`. |
| - [ ] **Step 4: Run them, expect PASS.** |
| -- [ ] **Step 5: Commit.** `git commit -m "console: incident engine with noise rules"` |
| +- [ ] **Step 5: Commit.** `git commit -m "console: incident step with noise rules"` |
| -### Task 8: Engine worker, signals, console pages routed, watcher retired |
| +### Task 8: Engine worker, signals, typed one-offs, watcher retired |
| **Files:** |
| -- Create: `internal/console/alertsignals.go`, plus test |
| +- Create: `internal/console/alertsignals.go`, `internal/console/alertengine_pass_test.go` |
| - Modify: |
| - - `internal/console/alertwatch.go`: delete `StartAlertWatcher` and `alertPass`. Keep `alertRecipients`, `grantRecipients`, `alertDue` and `recordAlertSeen`, used by `claim_runtime.go:328` and `storenotify.go:64`. |
| - - `claim_workers.go:5-43` |
| - - `cmd/console/main.go:678` |
| - - `jobs.go:278` |
| - - `jobs_test.go:35` |
| - - `testdata/claim-routes.txt` |
| - - `claim_invariant_fixtures_test.go:2174` |
| - - `claim_invariant_probes_worker_test.go:104` |
| - - `nocapacity.go:59`, `egressfleet.go:161`, `lifetimes_floor.go:42`: point their package vars at `s.raiseOneOff` |
| - - `hostsused.go:394`, `lifetimes_cutover.go:474`, `movesrecovery.go:620`, `claim_loss_pages.go:138`: call `s.raiseOneOff` |
| + - `internal/console/alertwatch.go`: delete `StartAlertWatcher` and `alertPass`. Keep `alertRecipients`, `grantRecipients`, `alertDue`, `recordAlertSeen`, `alertMessage` and `alertValueText`, which are used by `claim_runtime.go:328`, `storenotify.go:64` and the engine's message text. |
| + - `alertwatch_test.go`: delete the `alertPass` tests. Their behaviours (recipient set, unmailable operator, fire and clear text) move to `alertengine_pass_test.go`. |
| + - `alertnow_test.go`: drive `alertEnginePass` instead of `alertPass` (:64 and others). |
| + - Registries: |
| + - `claim_workers.go:5-43` |
| + - `cmd/console/main.go:678`: start `StartAlertEngine` only when `!cfg.HostClaim` |
| + - `jobs.go:278` (`"StartAlertEngine": "Alert engine"`) |
| + - `jobs_test.go:35` |
| + - `testdata/claim-routes.txt` |
| + - `claim_invariant_fixtures_test.go:2174` |
| + - `claim_invariant_probes_worker_test.go:104-125`: the effect is now one `alert_incidents` row in place of the `alert_seen` assertion at :121 |
| + - One-off callers: |
| + - `nocapacity.go:59,133`: rule `no_room`, subject the region, quiet 2 h |
| + - `egressfleet.go:161,451`: `egress_conflict`, subject the box |
| + - `hostsused.go:394`: `hosts_used`, subject the reason code |
| + - `lifetimes_floor.go:42,164`: `lifetimes`, subject the box |
| + - `lifetimes_cutover.go:474`: `lifetimes`, subject `"marker"` |
| + - `movesrecovery.go:620`: `moves_recovery`, subject the move rule |
| + - `claim_loss_pages.go:138`: `claim_loss`, subject the loss ID |
| + |
| + The package vars `pageNoCapacity`, `pageEgressConflict` and `lifetimesPage` are kept as test seams but given the typed signature below. Each call site passes `s` explicitly; nothing is bound to a single global server. Existing tests that swap these vars (e.g. `nocapacity_test.go:45`) are updated to the new signature. |
| **Interfaces:** |
| -- Consumes: Tasks 4, 6 and 7, `release.ConditionalGetter.GetIfChanged` (`internal/release/store.go:221`), `status.LoadBoxes` (`fleet.go:151`), `FleetView` (`view.go:923`), `aliasReadings` (`apidomains.go:1645`), `AlertDelivery.NotDelivered` (Task 3) |
| +- Consumes: Tasks 3, 4, 6, 7; `release.ConditionalGetter.GetIfChanged` (`internal/release/store.go:221`), with the `condGet` pattern from `internal/provision/recordview.go:387` |
| - Produces: |
| - - Worker `"StartAlertEngine"`: `func (s *Server) StartAlertEngine(ctx context.Context)`, a one-minute ticker running `s.jobs.Run(ctx, "StartAlertEngine", s.alertEnginePass)`. The job label is `"Alert engine"`. |
| - - `func (s *Server) alertEnginePass(ctx context.Context) error` does the following in order: |
| - 1. `collectBoxSignals`: `List("alerts/boxes/")`, then `GetIfChanged` per key, with the etag cache in memory. A key gone from the list sends a non-firing one-off close with `close_reason "box gone"` (Review Focus 3). |
| - 2. Every 5th pass, `collectHeartbeatSignals`: |
| - - `box_silent`: incident, no heartbeat for 15 min, but only for boxes still in `alerts/boxes/` |
| - - `alert_delivery_broken`: warning |
| - - `cert_expiring`: warning, within 14 days |
| - - `service_down`: incident, from `FleetView().Services` |
| - 3. Drain one-offs raised since the last pass. |
| - 4. `stepIncidents`. |
| - 5. Save, and queue deliveries to the subscribed connectors per rule. A rule with no settings row uses every confirmed fleet connector. |
| - 6. `alertDeliverPass`. |
| - 7. Feed `s.alertsNow` so the dashboard keeps working (`opdashboard.go:419`). |
| - 8. Touch `Config.AlertEngineBeatPath`, which defaults to `filepath.Join(filepath.Dir(CONSOLE_DB), "alert-engine.beat")`. |
| - - `func (s *Server) raiseOneOff(ctx context.Context, level, subject, body string) error` has the `alerting.Page` shape. It records the one-off for the next pass and still calls `alerting.Page` for the HostClaim backstop. |
| - - The first run of the worker seeds operators, once and idempotently: an `email` connector per operator address, `confirmed_at = now`, scope `fleet`. |
| - - An operator who has neither a confirmed connector nor a grant is reported once a day in the engine's job status (`s.jobs`) line. This is Review Focus 4. |
| - - Rule IDs and levels in scope `fleet`: `disk_eta` W, `disk` I, `mem` W, `cpu` W, `geoip` W, `box_silent` I, `service_down` I, `no_room` I (one-off, 2 h), `cert_expiring` W, `alert_delivery_broken` W, plus one-offs `egress_conflict`, `hosts_used`, `lifetimes`, `moves_recovery`, `claim_loss` at their current levels with a 24 h window. |
| + - `type alertOneOff struct{ Key alertKey; Level, Title, Body string; Quiet time.Duration }` |
| + - `func (s *Server) raise(ctx context.Context, o alertOneOff) error` |
| + - persists with `RaiseOneOff` before returning |
| + - also calls `alerting.Page(ctx, o.Level, o.Title, o.Body)` for the HostClaim backstop, unchanged |
| + - `type engineReads struct`: the engine's own etag cache, holding `map[key]{etag string; body []byte}` |
| + - `func (r *engineReads) get(ctx, store, key) (body []byte, changed bool, err error)`, always conditional after the first read |
| + - `func (r *engineReads) boxes(ctx, store) ([]status.Box, error)`: LIST `status/boxes/` plus a conditional GET per key, decoding as `status.LoadBoxes` does |
| + - `func (r *engineReads) fleet(ctx, store) (*status.Fleet, error)`: conditional GET of `status/fleet.json` |
| + - `aliasReadings` gains a sibling, `func aliasReadingsFrom(boxes []status.Box, now time.Time) map[string]status.AliasReading`, so the engine reuses the boxes it already decoded. `aliasReadings` calls it. |
| + - `func (s *Server) StartAlertEngine(ctx context.Context)`: a one-minute ticker running `s.jobs.Run(ctx, "StartAlertEngine", s.alertEnginePass)` |
| + - `func (s *Server) alertEnginePass(ctx context.Context) error`: |
| + 1. **First run only:** |
| + - Open the seal. On error, report it in job status, raise `seal_key` (incident) and treat sealed connectors as unusable. On a created key while sealed rows exist, call `MarkSealedConnectorsNeedReentry` and raise `seal_key`. |
| + - Seed each operator a personal email connector (`owner_address` = their address, confirmed), idempotently. |
| + - **Cutover:** for each currently firing box rule where `alert_seen` shows `firing = 1` for every operator, open the incident with `Notified = true`, so no repeat fire is sent and the clear still is. |
| + 2. **Box signals:** LIST `alerts/boxes/`, then `reads.get` for each key. A key that disappears gives `Gone` signals for that box's open incidents. |
| + 3. **Every 5th pass, heartbeat signals** from `reads.boxes`: |
| + - `box_silent` (incident) for any box whose heartbeat is older than 15 min. Membership is every box with a `status/boxes/` object, so a box that never fired is included (Review Focus 3). |
| + - A box whose heartbeat object is gone gets `Gone`. |
| + - `alert_delivery_broken` (warning) from `Metrics.Alerts.NotDelivered()`. |
| + - `cert_expiring` (warning) at ≤ 14 days, from `aliasReadingsFrom`. |
| + - `service_down` (incident) from `reads.fleet().Services`. |
| + 4. **Commit:** `AlertStepInputs`, then `stepIncidents`, then build outbox rows for each emit. The connectors come from the rule's subscriptions, or every confirmed fleet connector when the rule has none, and skip disabled rules. Then `CommitAlertStep`, all in one call. |
| + 5. `alertDrainOutbox`. |
| + 6. Feed `s.alertsNow` from open box-rule incidents, so `opdashboard.go:419` keeps working. |
| + 7. Write `Config.AlertEngineBeatPath` (default `filepath.Join(filepath.Dir(CONSOLE_DB), "alert-engine.beat")`) by creating a temp file and renaming it over the beat, mode 0644. |
| + - **Unreachable operators:** once a day, an operator with no usable connector is named in the job status line (Review Focus 4). |
| + - **Rule IDs and levels** in scope `fleet`: |
| + |
| + | Rule | Level | Notes | |
| + |---|---|---| |
| + | `disk_eta` | warning | | |
| + | `disk` | incident | | |
| + | `mem` | warning | | |
| + | `cpu` | warning | | |
| + | `geoip` | warning | | |
| + | `box_silent` | incident | threshold minutes, editable | |
| + | `service_down` | incident | | |
| + | `no_room` | incident | | |
| + | `cert_expiring` | warning | threshold days, editable | |
| + | `alert_delivery_broken` | warning | | |
| + | `seal_key` | incident | | |
| + | `egress_conflict`, `hosts_used`, `lifetimes`, `moves_recovery`, `claim_loss` | at their callers' current levels | | |
| - [ ] **Step 1: Write failing tests.** |
| - - `TestEnginePassFiresSlackForDiskETA`: s3fake has `alerts/boxes/a.json` with `disk_eta` firing, and a Slack connector at an `httptest` TLS server. The client's box list is empty, so loopback is allowed in this test through an injected `refused` func. Exactly one POST is made. |
| - - `TestEnginePassIdleStoreCalls`: second pass, nothing changed. Assert `s3fake.Requests()` delta = 1 LIST + N conditional GETs, and zero unconditional GETs. |
| - - `TestEnginePassBoxGone` (Review Focus 3) |
| - - `TestEnginePassSeedsOperatorEmail`: two operators give two confirmed email connectors. A second pass adds none. |
| - - `TestEnginePassOperatorUnreachableReported` (Review Focus 4) |
| - - `TestRaiseOneOffBecomesIncidentAndQuietCloses` |
| - - `TestEnginePassFeedsAlertsNow`: the dashboard attention items still list the firing box rule. |
| - - `TestEnginePassTouchesBeat` |
| - - Rename the worker in each registry (claim-routes.txt `worker StartAlertEngine`, the fixture, the probe, `jobPassFuncs`, `jobLabels`). The existing registry tests will fail until each is updated. |
| -- [ ] **Step 2: Run them, expect FAIL.** Run `go test ./internal/console -run 'EnginePass|RaiseOneOff|ClaimConsoleRouteCensus|Jobs' -count=1`. |
| -- [ ] **Step 3: Implement.** Copy the `condGet` pattern from `internal/provision/recordview.go:387`. |
| -- [ ] **Step 4: Run them, expect PASS.** Also run `go test ./internal/console -run 'Alert|Dashboard|Claim' -count=1`. |
| -- [ ] **Step 5: Commit.** `git commit -m "console: alert engine worker replaces the alert watcher"` |
| + - `TestEnginePassFiresSlackForDiskETA`: s3fake plus a TLS `httptest` server, with a client built with a loopback-permitting `refused`. The first pass sends nothing. The pass at minute 5 sends one POST. |
| + - `TestEnginePassFiveCycleRequests`: a recording `release.Store` wrapper logs method, key and whether the GET was conditional. Over 5 idle passes after a warm-up, every GET is conditional. The LISTs are 5× `alerts/boxes/` and 1× `status/boxes/`. There is one GET of `status/fleet.json`, conditional. |
| + - `TestEnginePassNeverAlertedBoxGoesSilent` (Review Focus 3) |
| + - `TestEnginePassBoxGoneCloses` |
| + - `TestEnginePassSeedsOperatorEmailOnce` |
| + - `TestEnginePassCutoverNoRefire`: `alert_seen` already records a fire, so no fire is sent and the later clear is. |
| + - `TestEnginePassCrashBetweenCommitAndSend`: commit, close the store, reopen, drain. One send. |
| + - `TestEnginePassSealKeyUnreadable` (Review Focus 5): connectors are skipped, a `seal_key` incident is emailed, and email connectors still deliver. |
| + - `TestRaiseOneOffDurable` |
| + - `TestRaiseNoRoomQuietCloses2h` |
| + - `TestEngineNotStartedInHostClaim` |
| + - `TestEnginePassFeedsAlertsNow` |
| + - `TestEnginePassWritesBeat` |
| + - Registry tests (`TestClaimConsoleRouteCensus`, the jobs and probe tests) fail until they are renamed. |
| +- [ ] **Step 2: Run them, expect FAIL.** Run `go test ./internal/console -run 'EnginePass|RaiseOneOff|RaiseNoRoom|EngineNotStarted|ClaimConsoleRouteCensus|Jobs|NoCapacity|Egress|Lifetimes|MovesRecovery|ClaimLoss|HostsUsed' -count=1`. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run them, expect PASS.** Also run `go test ./internal/console -run 'Alert|Dashboard|Claim|StoreNotify' -count=1`. |
| +- [ ] **Step 5: Commit.** `git commit -m "console: alert engine replaces the alert watcher"` |
| ### Task 9: Copy deck |
| @@ -369,87 +490,116 @@ |
| - Create: `docs/superpowers/notes/copy-fleet-alerts-1.md` |
| - [ ] **Step 1: Extract every user-facing string into the deck.** |
| - - Slack, email and webhook message text for each rule ID in Task 8, covering fire, clear, update, reminder and "no further reports". Each follows the "what is wrong, how long you have, what to do" shape from spec §6.5. |
| - - The confirm email, the test message, and the "connector suspended" message. |
| - - Every label, heading, button, empty state and error on `/fleet/alerts`. |
| -- [ ] **Step 2: Run the `copy-review` skill on the deck.** For a large deck, use a Luna pass on Paul's house rules (memory: large copy decks delegated). Apply the result verbatim. |
| -- [ ] **Step 3: Replace the `alertCopy` draft map (Task 6) with the approved strings.** Run `go test ./internal/console -run 'Alert' -count=1` and expect PASS. |
| + - Message text per rule ID in Task 8, for each of fire, clear, "no further reports", update and reminder. Each follows "what is wrong, how long you have, what to do". |
| + - The confirm email, the Slack test text with its confirm link, the "connector suspended" message, and the unsubscribe footer. |
| + - Every label, heading, button, empty state, read-only threshold note and error on `/fleet/alerts`, and the token door pages. |
| +- [ ] **Step 2: Run the `copy-review` skill on the deck.** For a large deck use a Luna pass (memory: large copy decks delegated). Apply the result verbatim. |
| +- [ ] **Step 3: Replace the `alertCopy` draft strings.** Run `go test ./internal/console -run 'Alert|Render' -count=1` and expect PASS. |
| - [ ] **Step 4: Commit.** `git commit -m "console: approved alert copy"` |
| -### Task 10: `/fleet/alerts` pages and public token doors |
| +### Task 10: `/fleet/alerts` pages and token doors |
| **Files:** |
| -- Create: `internal/console/alertpages.go`, `internal/console/templates/ops_alerts.html`, `ops_alerts_history.html`, plus `alertpages_test.go` |
| +- Create: `internal/console/alertpages.go`, `templates/ops_alerts.html`, `templates/ops_alerts_history.html`, `templates/alert_door.html`, plus `alertpages_test.go` |
| - Modify: |
| - - `server.go` (register routes near :1753) |
| + - `server.go` (routes near :1753) |
| - `opshell.go:30`: `{Key: "alerts", Href: "/fleet/alerts", Label: "Alerts"}` after Metrics |
| - `opshots_test.go:30` |
| - `testdata/claim-routes.txt` |
| - `claim_invariant_fixtures_test.go` |
| - `claim_invariant_probes_read_test.go` |
| - `testdata/perf-budgets.txt` |
| - - Record-write census: a new `internal/provision/fleet_alerts_census_test.go` re-pinning `NewServer`, layered on `fleetPublicRoutesWriteCensusInventory()`, copying `operator_people_detail_census_test.go` |
| +- Record-write census: |
| + - create `internal/provision/fleet_alerts_census_test.go` with `fleetAlertsWriteCensusInventory()`, layered on `fleetPublicRoutesWriteCensusInventory()` and re-pinning `NewServer` (copy `operator_people_detail_census_test.go`) |
| + - modify `internal/provision/plan9_b8_census_test.go:369` to select `fleetAlertsWriteCensusInventory()` |
| **Interfaces:** |
| -- Operator routes (guarded with `operatorOnly`, `server.go:3742`; POSTs carry the console's existing CSRF form token): |
| - - `GET /fleet/alerts`: Connectors and Rules on one page |
| - - `POST /fleet/alerts/connectors`: add slack, webhook or email. Slack and webhook send a test at once. Email sends the confirm link. |
| - - `POST /fleet/alerts/connectors/{id}/test` |
| +- **Operator routes** (`operatorOnly`, `server.go:3742`; POSTs carry the console's existing CSRF form token): |
| + - `GET /fleet/alerts`: connectors, plus rules with editable thresholds for `box_silent` and `cert_expiring` and read-only `host.env` names for box rules |
| + - `POST /fleet/alerts/connectors`: add slack, webhook or email |
| + - Slack sends a test with a confirm link. |
| + - Webhook sends a signed test, and 2xx confirms it. |
| + - Email sends a confirm link, rate limited (copy `signinSend`, `emailsignin_limits.go:192`, onto new `keyedWindow`s in `s.limits`). |
| + - `POST /fleet/alerts/connectors/{id}/test`, rules as in `sendTestAlert` |
| - `POST /fleet/alerts/connectors/{id}/delete` |
| - - `POST /fleet/alerts/rules/{rule}`: enabled, threshold, connector IDs |
| + - `POST /fleet/alerts/rules/{rule}` |
| - `GET /fleet/alerts/history`: last 200 incidents |
| -- Public, token-gated routes. Tokens are 32 random bytes in base64url, stored hashed: |
| - - `GET /alerts/confirm/{token}` |
| - - `GET /alerts/snooze/{token}?for=1h|1d|1w` |
| - - `GET /alerts/unsubscribe/{token}` |
| -- `GET /alerts/signing-key`: the public key as text/plain. |
| -- Confirmation sends are limited to 5 per scope per hour and 20 per day, with a new `keyedWindow` pair on `s.limits` (copy `signinSend`, `emailsignin_limits.go:192`). |
| +- **Public doors.** Each GET shows a confirm page, and each POST acts, so link scanners don't act: |
| + - `GET|POST /alerts/confirm/{token}`: action `confirm`, bound to the connector, 7-day expiry, one use |
| + - `GET|POST /alerts/unsubscribe/{token}`: action `unsubscribe`, bound to the connector, no expiry, idempotent. It disables the connector. |
| + - `GET|POST /alerts/snooze/{token}?for=1h|1d|1w`: action `snooze`, bound to (scope, rule, subject), 30-day expiry, reusable. Each use sets the snooze to now + duration and never adds to it. Any other `for` is refused. |
| +- `GET /alerts/signing-key`: text/plain. |
| - [ ] **Step 1: Write failing tests.** |
| - `TestFleetAlertsNotOperator404` |
| - - `TestFleetAlertsAddSlackSendsTest` |
| + - `TestFleetAlertsAddSlackSendsTestWithConfirm` |
| - `TestFleetAlertsAddSlackRefusesNonSlackHost` |
| - - `TestFleetAlertsSecretNeverRendered`: the page body holds `target_hint` only, never the full URL. |
| - - `TestFleetAlertsAddEmailUnconfirmedGetsNothing`: an engine pass with a firing rule makes zero sends to it. |
| - - `TestAlertsConfirmTokenOneUse` |
| - - `TestAlertsSnoozeSuppresses` |
| - - `TestAlertsConfirmRateLimit`: the sixth in an hour is refused. |
| + - `TestFleetAlertsSecretNeverRendered` |
| + - `TestFleetAlertsRepeatedTestOnUnconfirmedEmailRefused` |
| + - `TestFleetAlertsBoxRuleThresholdReadOnly` |
| + - `TestAlertDoorGetDoesNotAct` |
| + - `TestAlertDoorWrongActionRefused` |
| + - `TestAlertDoorSnoozeInvalidDuration` |
| + - `TestAlertDoorSnoozeNotCumulative` |
| + - `TestAlertsConfirmRateLimit` |
| - `TestAlertsSigningKeyServed` |
| - - Add a probe and fixture for each route. The registry tests fail until they're added. |
| + - Registry and census tests fail until each entry is added. |
| - [ ] **Step 2: Run them, expect FAIL.** |
| -- [ ] **Step 3: Implement.** Templates copy `ops_boxes.html` (`{{template "op_top" .}}`). The strings come from Task 9. Avoid a literal `NN%` in the page, because `TestAppPageOwnerMetricsBoundary` flags it. |
| -- [ ] **Step 4: Run them, expect PASS.** Run `go test ./internal/console -run 'FleetAlerts|AlertsConfirm|AlertsSnooze|AlertsSigning|ClaimConsoleRouteCensus|Perf|OpShots' -count=1` and `go test ./internal/provision -run TestPlan9B8RecordWriteCensus -count=1`. |
| -- [ ] **Step 5: Commit.** `git commit -m "console: /fleet/alerts pages, confirm/snooze/unsubscribe doors"` |
| +- [ ] **Step 3: Implement.** Templates copy `ops_boxes.html`. Strings come from Task 9. Avoid a literal `NN%` (`TestAppPageOwnerMetricsBoundary`). |
| +- [ ] **Step 4: Run them, expect PASS.** Run `go test ./internal/console -run 'FleetAlerts|AlertDoor|AlertsConfirm|AlertsSigning|ClaimConsoleRouteCensus|Perf|OpShots' -count=1` and `go test ./internal/provision -run TestPlan9B8RecordWriteCensus -count=1`. |
| +- [ ] **Step 5: Commit.** `git commit -m "console: /fleet/alerts pages and token doors"` |
| -### Task 11: Docs, roll notes, branch gate |
| +### Task 11: Docs, roll notes, census, gate |
| **Files:** |
| -- Modify: `README.md` (alerting section near :923-942) |
| +- Modify: `README.md` (alerting, near :923-942) |
| - Create: `docs/superpowers/notes/roll-fleet-alerts-1.md` |
| - [ ] **Step 1: README.** Document: |
| - `/fleet/alerts` |
| - - the connector kinds |
| + - the connector kinds and how each is confirmed |
| - `CARLOS_ALERT_DISK_ETA_HOURS` |
| - `CARLOS_ALERT_ENGINE_BEAT` |
| - that box sinks now carry incident rules only |
| - Slack URLs in `CARLOS_ALERT_WEBHOOK` |
| - - the seal key file, and that it must not be restored from the replica alone |
| -- [ ] **Step 2: Roll notes.** Cover: |
| - - roll order dev first (memory `roll-order-dev-first`) |
| - - set `CARLOS_ALERT_ENGINE_BEAT=/data/console/alert-engine.beat` in `host.env` on each console box |
| - - optionally point the console box's `CARLOS_ALERT_WEBHOOK` at the operators' Slack URL |
| - - live check: add the Slack connector on dev and send a test, then confirm a `disk_eta` fires on a dev box. Lowering `CARLOS_ALERT_DISK_ETA_HOURS` to 100000 on one dev box for 2 h is enough. Then put it back. |
| -- [ ] **Step 3: Census proposal.** Run `make census-card` again on the final diff, then `make census-propose NAME=fleet-alerts-1 CLAIMS=<file>`. The reviewer approves it on #280. |
| -- [ ] **Step 4: Push and gate.** Push the branch, then check `amadan ci status carlos/platform -branch design-fleet-alerts` until it is green. |
| -- [ ] **Step 5: Commit.** `git commit -m "docs: fleet alerts README and roll notes"` |
| + - the seal key file and replica-only restores |
| + - at-least-once delivery |
| +- [ ] **Step 2: Roll notes.** |
| + - **Order:** dev first (memory `roll-order-dev-first`). |
| + - **host.env:** set `CARLOS_ALERT_ENGINE_BEAT=/data/console/alert-engine.beat` on each console box. |
| + - **Live witness, needs Paul's go** (production-infrastructure rule): |
| + 1. On one named dev box, run a scratch file under `/data/tmp/fleet-alerts-witness` that grows 50 MiB every 10 min (a `systemd-run --on-unit-active=10min` timer), with `CARLOS_ALERT_DISK_ETA_HOURS=100000` on that box. |
| + 2. Expect one Slack message about 4 h 5 min after the file starts growing: 2 h of warm-up, the 2 h hold, then the 5 min group window. |
| + 3. Delete the file and the timer, then restore the env. |
| + 4. Expect a clear about 2 h later. |
| + - **A quicker check:** the Slack test message and its confirm link. |
| +- [ ] **Step 3: Commit.** Commit everything, including the notes. `git commit -m "docs: fleet alerts README and roll notes"` |
| +- [ ] **Step 4: Census.** Run `make census-card` on the final tree, then `make census-propose NAME=fleet-alerts-1 CLAIMS=<file>`, then commit the overlay. The reviewer approves it on #280. |
| +- [ ] **Step 5: Gate.** Push. Then run `amadan ci status carlos/platform -branch design-fleet-alerts` against the exact pushed tip until it is green. |
| --- |
| -## Self-review notes |
| - |
| -- **Spec coverage:** |
| - - §5.1 Slack, webhook and email: Tasks 5, 6, 10. SMS moved to Plan 3 (spec §11.1). |
| - - §5.2 seeded operators: Task 8. Quiet hours and "also send to" are in the spec's options; Plan 1 builds neither because both are off by default. They come with Plan 3's account UI. |
| - - §5.3: Tasks 5, 6, 10. §6: Task 7. §7.1: Task 8 (minus the two Plan 2 rules). §7.2 sinks: Task 2. §8: Task 3. §9: Task 8. §13: Tasks 1, 5, 7, 8. |
| -- **Deliberate gap:** quiet hours and "also send to" are not in Plan 1. They're a stated deferral, listed here so the reviewer doesn't count them as missed. |
| +## R1 dispositions (Astra, `CODEX-FINDINGS-fleet-alerts-1-plan-R1.md`) |
| + |
| +| # | Sev | Disposition | |
| +|---|---|---| |
| +| 1 | P1 | Accepted. `Proxy: nil`, revalidation on every send, `Unmap()`, a proxy-env test (Task 5). The box-address list is dropped from the spec (public box addresses only reach the public edge). | |
| +| 2 | P1 | Accepted. URL-free `sendErr` categories, and `err_category` is the only stored error. Tests on the DB and on logs (Tasks 5, 6). | |
| +| 3 | P1 | Accepted. `rootstate.OpenTrustedFileFrom` plus `Fstat`. Refuses non-regular files, symlinks and future mtimes. Missing-file behaviour is defined (Task 3). | |
| +| 4 | P1 | Accepted. `owner_address` on seeded connectors, and operator status is rechecked before each send, including queued rows (Task 6). | |
| +| 5 | P1 | Accepted. Test sends are refused for unconfirmed email and limited to 10/h (Tasks 6, 10, with an HTTP-route test). | |
| +| 6 | P1 | Accepted. `CommitAlertStep` writes the incident and outbox in one transaction. At-least-once with a `delivery_id` is now stated in spec §6.1 (Tasks 4, 8). | |
| +| 7 | P1 | Accepted by refusing up front. The engine never runs on a HostClaim console. One console per deployment is the existing invariant every console worker relies on (spec §5.2). | |
| +| 8 | P1 | Accepted. `TrendNoGrowth` is a clearing verdict (Tasks 1, 2), and spec §7.1 is amended. | |
| +| 9 | P1 | Accepted. The `alert_fires` history is independent of incidents (Tasks 4, 7). | |
| +| 10 | P1 | Accepted. `notify_at` is open + 5 min, and fire and clear inside it is silent (Task 7; spec §6.2). | |
| +| 11 | P1 | Accepted. Membership comes from `status/boxes/`, and `Gone` comes from object removal (Task 8). | |
| +| 12 | P1 | Accepted by cutting. Box-rule thresholds stay in `host.env` and are shown read-only. Only console-evaluated thresholds are editable (spec §5.2). | |
| +| 13 | P1 | Accepted. New `readDiskBytes` and probe, `alertNote` renamed, and the watcher tests and worker probe migrated (Tasks 2, 6, 8). | |
| +| 14 | P1 | Accepted. `plan9_b8_census_test.go:369` now selects the new inventory (Task 10). | |
| +| 15 | P2 | Accepted. `engineReads` conditional loaders, `aliasReadingsFrom`, and a five-pass recording test (Task 8). | |
| +| 16 | P2 | Accepted. Action-bound token records with expiry and replay rules, GET shows and POST acts, unsubscribe in every email (Tasks 4, 6, 10). | |
| +| 17 | P2 | Accepted. Slack confirms through the link in its test message. Webhook confirms on a 2xx signed test (Tasks 6, 10). | |
| +| 18 | P2 | Accepted. Typed `alertOneOff` with rule and subject at every call site, persisted before return, with no global server binding (Task 8). | |
| +| 19 | P2 | Accepted. Unreadable or new key paths raise `seal_key`, email still works, and `alert_seen` is imported at cutover (Task 8). | |
| +| 20 | P2 | Accepted. The live witness has controlled growth, real timings and Paul's go. Commit before push (Task 11). | |
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-fleet-alerts-1-plan-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-fleet-alerts-1-plan-R1.md| new file mode 100644 |
| index 000000000..6691518fc |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-FINDINGS-fleet-alerts-1-plan-R1.md |
| @@ -0,0 +1,129 @@ |
| +Reviewed commit `84997183390cc068c97dd7e47607bcbc8d0ae392` against base `c24e7a04`. No files changed; no test suites run. |
| + |
| +References to **Plan** below mean [2026-10-30-fleet-alerts-1-engine-connectors.md](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/docs/superpowers/plans/2026-10-30-fleet-alerts-1-engine-connectors.md). **Spec** means [2026-10-30-fleet-alerts-and-traffic-design.md](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/docs/superpowers/specs/2026-10-30-fleet-alerts-and-traffic-design.md). |
| + |
| +1. **P1 — Task 5: `Dialer.Control` alone does not enforce the outbound boundary.** |
| + **Evidence:** Plan:235–249 specifies the dial check but never disables proxies. Go’s transport connects to the proxy address when one is configured ([transport.go:2079](/usr/local/go/src/net/http/transport.go:2079)). |
| + **Failure:** With `ProxyFromEnvironment`, an allowed public proxy resolves and connects to the destination; `Control` checks only the proxy. A connector can therefore reach a forbidden destination through it. |
| + **Fix:** Require `Transport.Proxy = nil`, validate scheme and port on every send, normalize mapped addresses before checking, and specify the production source of fleet addresses. Test proxy environment variables through the production client. |
| + **Fault family:** Outbound destination enforcement. |
| + |
| +2. **P1 — Tasks 4–6: transport errors can defeat connector sealing.** |
| + **Evidence:** Plan:181 stores `last_error`; Plan:239 returns a POST error; Plan:267 passes delivery errors to `FinishDelivery`. HTTP client errors contain the request URL ([client.go:622](/usr/local/go/src/net/http/client.go:622)), and `url.Error.Error()` prints it ([url.go:39](/usr/local/go/src/net/url/url.go:39)). |
| + **Failure:** A timeout or TLS failure exposes the Slack secret in plaintext error storage, replicas, logs or job status. |
| + **Fix:** Sanitize errors at the HTTP boundary into URL-free error categories. Test a failed request with a distinctive secret against database contents, rendered errors and captured logs. |
| + **Fault family:** Connector-secret confidentiality. |
| + |
| +3. **P1 — Task 3: the heartbeat read follows console-controlled symlinks.** |
| + **Evidence:** Plan:163 prescribes `os.Stat` on the env-named path; Plan:345 puts it beside console.db. Root-run agents remain supported ([agent.go:2519](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/host/agent.go:2519)). AGENTS.md:359–364 explicitly rejects new root follows through agent-writable inputs. |
| + **Failure:** Replacing the heartbeat with a symlink makes a root-run agent inspect another inode. Merely recording this on the census card does not make it acceptable. |
| + **Fix:** Define an anchored, no-symlink metadata read, including parent-directory handling. Reject invalid file types and future timestamps; define missing/unreadable heartbeat behavior. Test these through `alertTick`. |
| + **Fault family:** Root filesystem traversal. |
| + |
| +4. **P1 — Task 8: seeded connectors outlive operator authorization.** |
| + **Evidence:** Plan:347 seeds confirmed connectors once; Plan:342 subsequently selects confirmed fleet connectors. Today recipients are rederived from `Operators()` on each pass ([alertwatch.go:167](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/console/alertwatch.go:167)); revocation changes only the user’s operator bit ([store.go:2499](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/console/store.go:2499)). |
| + **Failure:** A revoked operator continues receiving private fleet alerts through their seeded connector. |
| + **Fix:** Identify automatically seeded personal connectors explicitly and recheck recipient authorization before delivery, including queued retries. Test revocation after queuing. |
| + **Fault family:** Fleet-information authorization. |
| + |
| +5. **P1 — Tasks 6 and 10: the test-send door bypasses the stated opt-in boundary.** |
| + **Evidence:** Plan:268 exposes `sendTestAlert(scope, id)` for connectors; Plan:397 exposes its POST route. The only unconfirmed-delivery witness, Plan:413, exercises an engine pass. |
| + **Failure:** An operator adds an arbitrary unconfirmed email address and repeatedly invokes `/test`, sending messages beyond the confirmation allowance without recipient consent. |
| + **Fix:** Enforce confirmation eligibility inside the shared sender/test-send boundary. Unconfirmed email may receive only a rate-limited confirmation. Add an HTTP-route test covering repeated test sends. |
| + **Fault family:** Recipient consent and confirmation limits. |
| + |
| +6. **P1 — Tasks 4, 7 and 8: incident persistence and delivery queuing are not atomic.** |
| + **Evidence:** Plan:191 defines separate `SaveIncident` and `QueueDeliveries` operations; Plan:342 runs them sequentially. Plan:307 tests only feeding an in-memory result back into the pure function. |
| + **Failure:** A crash after saving a clear but before queuing it loses the clear permanently. A successful external send followed by a crash before `FinishDelivery` can repeat the message. |
| + **Fix:** Commit incident transitions and uniquely identified outbox entries in one transaction. Test failures between persistence operations and across database reopen. State the unavoidable ambiguous-send behavior for destinations without idempotency support; the present no-duplicate guarantee is stronger than the mechanism. |
| + **Fault family:** Durable notification transitions. |
| + |
| +7. **P1 — Task 8: a claim worker is not a fleet-wide single runner.** |
| + **Evidence:** Plan:332 relies on `RunClaimWorker` and `s.jobs.Run`. Registration only attaches context ([claim_workers.go:35](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/console/claim_workers.go:35)); execution simply calls the handler ([claim_workers.go:57](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/console/claim_workers.go:57)). The serve lock protects one database path ([main.go:310](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/cmd/console/main.go:310)). |
| + **Failure:** Two claim-mode consoles with separate databases both observe the same fleet transition and send it. |
| + **Fix:** Specify and enforce one fleet-wide engine owner, including ownership transfer and preservation of incident state and seal-key availability. Add a two-console witness. |
| + **Fault family:** Fleet-wide notification ownership. |
| + |
| +8. **P1 — Task 1: a disk forecast cannot clear after growth stops.** |
| + **Evidence:** Plan:83 returns `ok=false` for a nonpositive slope; Plan:98–100 says a nil ETA preserves firing state. Spec:581 requires deletion to clear the forecast. |
| + **Failure:** A firing forecast followed by deletion or sustained flat usage eventually produces no ETA and remains firing indefinitely. |
| + **Fix:** Distinguish insufficient data from valid evidence of no growth. Define the latter as a clearing observation without serializing infinity, and test deletion/flat usage through the ring and evaluator together. |
| + **Fault family:** Forecast clearing semantics. |
| + |
| +9. **P1 — Tasks 4 and 7: flapping history disappears between incidents.** |
| + **Evidence:** Plan:191 loads `OpenIncidents`; Plan:291 accepts open incidents; Plan:293 closes ordinary incidents immediately when every member clears. Plan:294 requires three fire times within an hour. |
| + **Failure:** Fire → clear → fire → clear creates separate incidents. Once each closed incident drops out of the input, the next episode cannot count earlier cycles. |
| + **Fix:** Persist and load recent transition history independently of open incidents, or retain explicit rule/subject cycle state. Test three cycles through the production store, including a restart between cycles. |
| + **Fault family:** Flapping suppression across incident lifetimes. |
| + |
| +10. **P1 — Tasks 7 and 8: immediate delivery contradicts five-minute grouping.** |
| + **Evidence:** Plan:352 expects a POST on the first engine pass. Plan:292 joins subsequent members, while Plan:296 permits updates only after 30 minutes. Spec:259–263 requires one message listing members that fire within five minutes. |
| + **Failure:** Box A fires at minute zero and is sent immediately. Boxes B–E join over the next four minutes, but the recipient never receives the promised grouped list. |
| + **Fix:** Persist a pending initial notification until the grouping deadline, then send the accumulated members. Test staggered arrivals across separate passes and a restart inside the window. |
| + **Fault family:** Notification grouping. |
| + |
| +11. **P1 — Task 8: `alerts/boxes/` is not a box-membership registry.** |
| + **Evidence:** Plan:336 limits `box_silent` to boxes listed there. The producer writes an alert object only when an event occurs ([metrics_loop.go:525](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/host/metrics_loop.go:525)); the existing watcher explicitly recognizes an empty prefix as “no box has ever published an alert” ([alertwatch.go:115](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/console/alertwatch.go:115)). |
| + **Failure:** A previously healthy box dies without ever having fired a rule. It has heartbeat history but no alert object, so `box_silent` never fires. |
| + **Fix:** Derive monitored membership from the fleet inventory and define retirement separately from alert-object disappearance. Test a never-alerted box going silent. |
| + **Fault family:** Fleet liveness membership. |
| + |
| +12. **P1 — Tasks 2, 4, 8 and 10: editable box thresholds have no path to evaluation.** |
| + **Evidence:** Plan:178–190 stores console thresholds; Plan:399 exposes editing. Box rules are loaded from environment once ([metrics_loop.go:847](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/host/metrics_loop.go:847)). The engine consumes already-evaluated rule state. |
| + **Failure:** An operator changes the disk forecast threshold, but the box continues using its environment/default threshold. The control appears to work while alerts remain unchanged. |
| + **Fix:** Specify how settings reach the box evaluator through an existing control path within the request budget. Add a production-path test demonstrating that a saved threshold changes firing behavior. |
| + **Fault family:** Configuration-to-evaluation consistency. |
| + |
| +13. **P1 — Tasks 2, 6 and 8: the prescribed changes leave compilation failures.** |
| + **Evidence:** Three verified conflicts: |
| + - Changing `readDiskFrac` to return additional values, Plan:110, breaks `sampleProbes.diskFrac func() *float64` ([metrics_loop.go:34](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/host/metrics_loop.go:34)) and the status caller ([agent.go:4330](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/host/agent.go:4330)). |
| + - The new `type alertMessage`, Plan:264, collides with the existing package-level function ([alertwatch.go:340](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/console/alertwatch.go:340)). |
| + - Deleting `alertPass`, Plan:318, leaves calls in [alertwatch_test.go:83](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/console/alertwatch_test.go:83), [alertnow_test.go:64](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/console/alertnow_test.go:64) and other tests. |
| + |
| + **Failure:** The named package test commands cannot compile the intermediate/final implementation as written. |
| + **Fix:** Preserve a fraction-only wrapper or update every caller, choose a noncolliding message type, and explicitly migrate watcher tests. Also replace the worker probe’s `alert_seen` assertion ([claim_invariant_probes_worker_test.go:121](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/console/claim_invariant_probes_worker_test.go:121)); renaming its registry key is insufficient. |
| + **Fault family:** Buildable task integration. |
| + |
| +14. **P1 — Task 10: the new record-write census layer is never selected.** |
| + **Evidence:** Plan:391 creates a new inventory layered on `fleetPublicRoutesWriteCensusInventory`, but does not modify the test selecting the inventory. That test still calls the old function ([plan9_b8_census_test.go:369](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/provision/plan9_b8_census_test.go:369)). |
| + **Failure:** Changing `NewServer` still fails the required census test; the new fingerprint is unused. |
| + **Fix:** Include the census entry-point change in Task 10 and select the new inventory. |
| + **Fault family:** Census enforcement wiring. |
| + |
| +15. **P2 — Task 8: the budget test misses the expensive pass.** |
| + **Evidence:** Plan:353 tests only the second pass. The fifth-pass dependencies include unconditional reads in [view.go:924](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/console/view.go:924), [fleet.go:292](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/status/fleet.go:292), and another box load through [apidomains.go:1649](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/console/apidomains.go:1649). `s3fake.Requests()` is only an aggregate counter ([s3fake.go:85](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/s3fake/s3fake.go:85)). |
| + **Failure:** The test passes while every fifth pass violates the stated conditional-read budget. |
| + **Fix:** Define conditional cached loaders and shared decoded heartbeat inputs. Assert methods, keys and conditional headers over a complete five-pass cycle, including fleet-summary reads. |
| + **Fault family:** Store-request accounting. |
| + |
| +16. **P2 — Task 10: public token authorization is underspecified.** |
| + **Evidence:** Plan:401–404 specifies random hashed tokens, but Task 4 provides only `confirm_token`; it defines no snooze/unsubscribe token records, action binding, expiry or consumption rules. |
| + **Failure:** Implementers must invent whether tokens are interchangeable, reusable, or able to renew a snooze indefinitely. The proposed tests do not establish cross-action or cross-scope isolation. |
| + **Fix:** Specify token records bound to action, scope and exact connector or rule/subject; define expiry and replay behavior. Test wrong action, wrong scope, reuse and invalid duration. Ensure every alert email includes its unsubscribe link. |
| + **Fault family:** Public-token capability scope. |
| + |
| +17. **P2 — Tasks 6 and 10: Slack verification has no completion step.** |
| + **Evidence:** Spec:151 requires the person to confirm seeing the test. Plan:396–404 provides creation, testing, deletion and email confirmation, but no Slack acknowledgement operation. |
| + **Failure:** Slack either remains unconfirmed forever or is marked confirmed merely because Slack accepted a POST. |
| + **Fix:** Add an operator-protected acknowledgement tied to a successful test; specify webhook confirmation on successful signed-test delivery separately. |
| + **Fault family:** Connector verification lifecycle. |
| + |
| +18. **P2 — Task 8: one-off routing loses structured identity.** |
| + **Evidence:** Plan:346 preserves only `(level, subject, body)`, while Plan:349 needs distinct rule IDs and quiet windows. Existing callers carry useful identity outside their formatted text, such as region in [nocapacity.go:125](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/console/nocapacity.go:125) and condition/loss ID in [claim_loss_pages.go:130](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/console/claim_loss_pages.go:130). |
| + **Failure:** Rule selection, grouping and quiet-window assignment depend on parsing prose. Binding package-global callbacks to one `Server` also risks routing another server’s events into it. |
| + **Fix:** Use per-server typed adapters carrying rule ID, stable subject key, level and quiet window. Persist one-offs before acknowledging acceptance or draining them. |
| + **Fault family:** Durable signal identity. |
| + |
| +19. **P2 — Tasks 4 and 8: key-loss and watcher-cutover witnesses are incomplete.** |
| + **Evidence:** Plan:205 tests decryption failure and setting a flag, but not the promised operator incident or unreadable-key startup. Plan:342–347 starts new incident state without importing the watcher’s per-recipient `alert_seen` state ([alertwatch.go:279](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/internal/console/alertwatch.go:279)). |
| + **Failure:** Restore handling may fail silently, and an already-notified standing alert is resent as a new fire during rollout. |
| + **Fix:** Specify recovery notification and re-entry behavior end to end, including email-target availability after key loss. Add an explicit cutover migration and tests for already-sent fires, pending recipients and subsequent clears. |
| + **Fault family:** Restore and rollout continuity. |
| + |
| +20. **P2 — Task 11: the live witness and final gate order are incorrect.** |
| + **Evidence:** Plan:442 calls setting the threshold to `100000` “lowering” it and promises a fire after two hours. Plan:83 requires two hours of samples before forecasting, followed by the two-hour hold at Plan:96. Flat usage never qualifies. Plan:444 pushes and gates before the final commit at Plan:445. |
| + **Failure:** The live check need not fire, and the checked tip excludes the final changes. |
| + **Fix:** Define controlled growth and sufficient warm-up/hold time, with scoped authorization for any required deployment changes. Commit all changes before pushing and checking the exact final tip. Keep the first merge as the complete observable Slack slice. |
| + **Fault family:** Valid release evidence. |
| + |
| +NOT READY |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-fleet-alerts-1-plan-R2.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-fleet-alerts-1-plan-R2.md| new file mode 100644 |
| index 000000000..d58d06cf3 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-fleet-alerts-1-plan-R2.md |
| @@ -0,0 +1,111 @@ |
| +# Review brief: fleet alerts Plan 1 (engine, connectors, fleet rules) and its spec, round 2 of 3 |
| + |
| +Repo carlos/platform, branch `design-fleet-alerts`, commit: this brief's parent (plan rev 2). |
| + |
| +Under review: |
| +- `docs/superpowers/plans/2026-10-30-fleet-alerts-1-engine-connectors.md`, the plan |
| +- `docs/superpowers/specs/2026-10-30-fleet-alerts-and-traffic-design.md`, the spec, insofar as Plan 1 builds it |
| + |
| +Authorities: the spec above (APPROVED by Paul 2026-10-30; it lives on this branch), main's code at the branch base c24e7a04, and AGENTS.md (census, request budget, stopping rules, production-wired witnesses). |
| + |
| +You are an independent reviewer. Read the spec, then the plan, then the code each task names, and check every claim against that code (file:line). |
| + |
| +## Fixed: do not re-argue |
| + |
| +These are recorded in spec §2. Report only mechanisms that fail to honour them. |
| + |
| +- Paul's rulings: |
| + - warn before it breaks, with the disk forecast as the reference case |
| + - Slack first |
| + - the same alert at 3am by default |
| + - one engine at three levels |
| + - ready-made alerts for end users |
| + - traffic page layout A |
| + - noise is the anti-goal |
| + - plan order: engine, then traffic, then account and app alerts |
| +- Plan-time calls already folded into the spec. Argue one only if it is unsafe or does not work: |
| + - the connector seal key lives in its own file beside console.db |
| + - the disk forecast keeps its own ring and is silent for 2 h after a restart |
| + - SMS, quiet hours and "also send to" move to Plan 3 |
| + - operators are seeded with confirmed email connectors |
| + - box sinks carry incident rules only |
| + - app thresholds are fleet-wide (Plan 3) |
| + |
| +## What to check |
| + |
| +1. **Interfaces and names.** Does every signature, file:line and registry the plan names exist as described on main? Would a task as written compile against the code? Pay special attention to: |
| + - `alertTick`'s parameters and `readDiskFrac` |
| + - `GetIfChanged` and the `condGet` pattern |
| + - the `claimSQLTables` classification |
| + - the claim worker and route registries, and the record-write census re-pin |
| + - `s.limits` |
| + - `operatorOnly` |
| +2. **Outbound URL guard (Task 5).** Can a Slack or webhook connector reach loopback, private, link-local, CGNAT, metadata or a fleet box address by any path? Consider: |
| + - DNS rebinding |
| + - IPv4-mapped IPv6 addresses |
| + - an HTTP proxy taken from the environment (`http.ProxyFromEnvironment` in the transport) |
| + - redirects |
| + - a non-443 port reached through a URL that passes validation |
| + |
| + Is checking in `Dialer.Control` sufficient? |
| +3. **Secrets.** Can a sealed target leak through: |
| + - a page, the job status line or a log |
| + - an error string from `postAlert` (the URL inside `*url.Error`) |
| + - the console.db replica |
| + |
| + Is the "key file lost" path safe? |
| +4. **Public token doors (Task 10).** Can confirm, snooze or unsubscribe be guessed, replayed or used across scopes? Can confirm-link sends be used to mail arbitrary addresses beyond the rate limit? Does a rate limit held in memory reset on restart in a way that matters? |
| +5. **Engine correctness (Task 7).** Do the noise rules as specified hold across: |
| + - a restart (state persisted before messages are sent? an at-least-once versus at-most-once gap?) |
| + - a pass that fails halfway |
| + - two consoles in claim mode (is the worker single-runner?) |
| +6. **Retiring the watcher (Task 8).** |
| + - Does anything still depend on `alertPass` or `StartAlertWatcher`? |
| + - Do `claim_runtime.go:328` and `storenotify.go:64` keep working? |
| + - Does the dashboard's `alertsNow` keep working? |
| + - Is there a window during the roll where operators get nothing, or get everything twice? |
| +7. **Request budget (spec §9).** Does any task add an unconditional GET, a new object or a timer? Is the test in Task 8 strong enough? |
| +8. **Root census.** Tasks 1-3 touch `internal/host`, `internal/metrics` and `internal/alerting`. Is the `engine_silent` root read of an env-named path safe? Does `os.Stat` follow a symlink placed by the console's user? Is the census step in the right place? |
| +9. **Order (AGENTS.md stopping rule 6).** Is there a visible first merge, and are any tasks mis-ordered against their dependencies? |
| + |
| +## Round 2 |
| + |
| +Earlier rounds: |
| +- R1 on 84997183: `docs/superpowers/reviews/CODEX-FINDINGS-fleet-alerts-1-plan-R1.md`, NOT READY, 14 P1s and 6 P2s. |
| +- The plan's dispositions are in its "R1 dispositions" table. |
| +- Spec amendments after R1, all in the spec: |
| + - §5.2: editable thresholds cut to console-evaluated rules; one console runs the engine; HostClaim refused |
| + - §5.3: no proxy; URL-free errors; box addresses dropped |
| + - §6.1: at-least-once delivery |
| + - §6.2: the first message waits 5 min |
| + - §7.1: a no-growth trend clears the forecast |
| + |
| +First give one line per R1 P1 and P2: resolved, partly, or not. Carry every unresolved or partly resolved finding forward at its current severity, then add new findings. The verdict covers everything outstanding. |
| + |
| +Two R1 findings were resolved by cutting or refusing rather than adding mechanism: #7 (single runner, refused on HostClaim) and #12 (box thresholds, cut to read-only). Judge those as cuts. Raise them again only if the cut itself is unsafe or leaves a control that appears to work but doesn't. |
| + |
| +## 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; 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 |
| + |
| +Findings ranked P1, P2, P3. Each 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 (that is 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. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites. |
diff --git a/docs/superpowers/specs/2026-10-30-fleet-alerts-and-traffic-design.md b/docs/superpowers/specs/2026-10-30-fleet-alerts-and-traffic-design.md| index 6160a8f09..f3a59ef58 100644 |
| --- a/docs/superpowers/specs/2026-10-30-fleet-alerts-and-traffic-design.md |
| +++ b/docs/superpowers/specs/2026-10-30-fleet-alerts-and-traffic-design.md |
| @@ -86,7 +86,7 @@ where it matters. |
| ### Non-goals (v1) |
| - A general rule builder with custom metrics and expressions. Operators |
| - can tune thresholds on built-in rules. End users can't. |
| + can tune thresholds on console-evaluated built-in rules (§5.2). End users can't. |
| - On-call rotations, acknowledgement and escalation chains (PagerDuty |
| territory). A generic webhook can feed PagerDuty or Opsgenie. |
| - Managed-fleet owners alerting on their own boxes. The data model must |
| @@ -148,7 +148,7 @@ multiply setup. |
| | Kind | Setup | Verification before first use | |
| |---|---|---| |
| -| Slack | paste an incoming-webhook URL | a test message is sent, and the person confirms they saw it | |
| +| Slack | paste an incoming-webhook URL | a test message is sent carrying a one-use confirm link; clicking it proves someone saw it | |
| | Email | an address | a confirm link is sent to the address, and nothing else goes there until it's clicked | |
| | SMS | a phone number | a six-digit code is sent, and the person types it back | |
| | Webhook | an https URL | a signed test POST that must answer 2xx | |
| @@ -195,7 +195,19 @@ So, my call (plan time): |
| A subscription is (scope, alert, connectors, options): |
| - **Fleet:** each built-in fleet rule (§7.1) has a list of connectors |
| - and a threshold the operator can change. |
| + and a threshold. |
| + - Console-evaluated rules (box silent, certificate expiring) have a |
| + threshold the operator can change on the page. |
| + - Box-evaluated rules (disk, memory, CPU, disk forecast) keep their |
| + per-box `host.env` settings, and the page shows them read-only with |
| + the variable's name. Sending console settings to boxes would need a |
| + new control path. (Cut after plan review R1.) |
| + |
| +**One console runs the engine.** Like every console worker today (plan |
| +notices, the alert watcher), the engine assumes one console per |
| +deployment. A console started in host-claim mode (shelved, and able to |
| +run several consoles) refuses to start the engine and says so in its job |
| +status. |
| - **Account:** "plan caps" and the account-wide defaults for app alerts. |
| - **App:** each ready-made app alert (§7.3) is on or off, and uses the |
| account's connectors unless it lists its own subset. |
| @@ -238,8 +250,14 @@ and the rest are warnings. |
| - **Webhook and Slack URLs:** |
| - must be https on port 443 |
| - the resolved address is checked at send time against loopback, |
| - private, link-local, CGNAT (Tailscale's 100.64/10), metadata and |
| - the fleet's own box addresses |
| + private, link-local, CGNAT (Tailscale's 100.64/10) and metadata |
| + - box public addresses are not refused. They only reach the public |
| + edge, which anyone can reach. (Changed after plan review R1.) |
| + - no proxy: the HTTP transport has `Proxy = nil`, so the dial check |
| + is never applied to a proxy instead of the destination |
| + - errors are reduced to URL-free categories (timeout, refused, |
| + connect, TLS, status N) before they are stored or logged, so a |
| + failed send can't leak the URL |
| - redirects are not followed |
| - the response body is never read beyond 1 KiB |
| - a 5-second timeout |
| @@ -256,8 +274,18 @@ and the rest are warnings. |
| 1. **One message on fire, one on clear.** Nothing repeats while the |
| condition holds. An incident still open after 24 hours gets one |
| daily reminder, at most. |
| + |
| + Delivery is at least once. An incident change and its queued |
| + messages are committed in one transaction, so nothing is lost. A |
| + console that dies after a send but before recording it may repeat |
| + that one message. Webhook bodies carry a delivery ID so receivers |
| + can drop the repeat. Slack can't, and accepts the rare duplicate. |
| 2. **Group.** One rule firing on several boxes, or several apps of one |
| - account, within 5 minutes is one message listing them. A new member |
| + account, within 5 minutes is one message listing them. The first |
| + message waits until 5 minutes after the incident opens, then lists |
| + every member so far. An incident that fires and clears inside those |
| + 5 minutes sends nothing. Box sinks still send "disk full now" at |
| + once, as the backstop. A new member |
| joining an open incident updates the group, with no new message, |
| until the group is 30 minutes old. After that it sends at most one |
| "now also" message per hour. |
| @@ -312,7 +340,8 @@ The **disk forecast** is computed on the box from its own samples: |
| box converts it to bytes using the filesystem size from `statfs`. |
| - it fires when the projected time to 100% is under the threshold |
| and has stayed under it for the hold window |
| -- it clears when the projection passes 1.5x the threshold |
| +- it clears when the projection passes 1.5x the threshold, or when the |
| + fitted trend shows no growth (flat or shrinking), so a deletion clears it |
| - the box reports `disk_full_eta` in its heartbeat as well |
| - the box keeps today's samples only until they're flushed (at most 120, |
| `metrics_loop.go:50`), so the forecast keeps its own in-memory ring of |