| index 1e24d530e..2b8f85569 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,4 +1,4 @@ |
| -# Fleet alerts Plan 1: engine, connectors, fleet rules — Implementation Plan (rev 2) |
| +# Fleet alerts Plan 1: engine, connectors, fleet rules — Implementation Plan (rev 3) |
| |
| > **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. |
| |
| @@ -14,7 +14,7 @@ |
| |
| **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. |
| +**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`. Astra R2 on 5e17b11a was NOT READY, with 3 P1s and 5 P2s: `docs/superpowers/reviews/CODEX-FINDINGS-fleet-alerts-1-plan-R2.md`. Stopping rule 2 fired on two fault families (root traversal, buildable integration), and Paul chose the approach for both on 2026-10-31. Each finding's disposition is at the end of this plan. This is rev 3, for round 3 of 3, the last. |
| |
| ## Global Constraints |
| |
| @@ -173,16 +173,21 @@ |
| - `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` |
| + - **Root mode is refused up front** (Paul's ruling 2026-10-31, after R2 #1): |
| + - `func engineBeatArmed(getenv func(string) string, euid int) (path string, armed bool, why string)` |
| + - when `euid == 0` it returns `armed = false` with why `"agent runs as root"` before any path lookup |
| + - the status line and `carlos status --live` show `engine-beat=off (agent runs as root)` |
| + - a root-run agent never opens, stats or resolves the path |
| + - `type beatState int`, with the values `beatFresh`, `beatStale`, `beatMissing`, `beatNotRegular` and `beatFuture` |
| + - `func readEngineBeat(path string, now time.Time) (beatState, time.Duration)` |
| + - non-root only: `os.Lstat`, so a symlink reads as `beatNotRegular` |
| + - stale means over 10 min old |
| - 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 |
| + - armed when `engineBeatArmed` says so; the arming time is the agent's start |
| + - fires on `beatStale` |
| + - fires on `beatMissing`, `beatNotRegular` or `beatFuture` once the armed agent has run 10 minutes without a fresh read, whether or not a beat was ever seen (R2 #3) |
| + - an agent restart restarts that 10-minute grace |
| + - clears on `beatFresh` |
| |
| - [ ] **Step 1: Write failing tests.** |
| - `TestPageSlackBody` |
| @@ -190,13 +195,16 @@ |
| - `TestBoxDeliverSlackBody` |
| - `TestPostJSONRefusesRedirect` |
| - `TestAlertDeliveryNotDelivered` |
| - - `TestEngineBeatAgeSymlinkRefused` (linux): the beat is a symlink to a fresh root file, so `ok` is false. |
| - - `TestEngineBeatAgeFutureMtime` |
| + - `TestEngineBeatRootRefusedBeforeLookup`: with `euid = 0`, a stat hook counts zero calls and the rule is absent. |
| + - `TestReadEngineBeatSymlinkNotRegular` |
| + - `TestReadEngineBeatFutureMtime` |
| + - `TestEngineSilentNeverCreatedBeatFires`: armed, the file never exists, and the rule fires at 10 min. |
| + - `TestEngineSilentRestartWhileMissing`: fires again 10 min after the restart. |
| - `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** 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`. The `engine_silent` read goes through `rootstate.OpenTrustedFileFrom`. Then `git commit -m "alerting: Slack body, no redirects; host: anchored 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 card should show no new root read, because root mode is refused before any lookup. Then `git commit -m "alerting: Slack body, no redirects; host: engine_silent backstop, refused for root agents"`. |
| |
| ### Task 4: Alert store: tables, transactional step, seal |
| |
| @@ -220,13 +228,22 @@ |
| - `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. |
| + - `alert_incidents` also carries `details TEXT` (JSON `[]{subject, title, body, at}`, at most 20 entries). A one-off's title and body move here in the same transaction that consumes the row, so the delayed first message still has them (R2 #5). |
| + - `alert_meta`: `k TEXT PK, v TEXT`. Holds `cutover_done`. |
| - Produces: |
| - `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, 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)` |
| + - These value types are defined here in `alertstore.go`, and Tasks 7 and 8 use them: |
| + - `type alertKey struct{ Scope, Rule, Subject string }` |
| + - `type alertFire struct{ Key alertKey; At time.Time }` |
| + - `type alertOneOff struct{ Key alertKey; Level, Title, Body string; Quiet time.Duration }` |
| + - `type alertOneOffRow struct{ ID int64; At time.Time; alertOneOff }` |
| + - `func (s *Store) AlertStepInputs(now time.Time) (open []alertIncident, recentFires map[alertKey][]time.Time, oneOffs []alertOneOffRow, err error)` |
| + - `alertIncident` gains `Details []alertDetail`, where `type alertDetail struct{ Subject, Title, Body string; At time.Time }` |
| + - `func (s *Store) AlertCutover(f func(tx *sql.Tx) error) (ran bool, err error)` runs `f` and sets `cutover_done` in one transaction, only when the marker is absent |
| - `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: |
| @@ -320,11 +337,11 @@ |
| - Produces: |
| - `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 renderWebhook(n alertNote) []byte` gives `{"v":1,"delivery_id","scope","rule","level","kind","subject","members","what","how_long","what_to_do","at","incident_url","snooze_url"}` (R2 #8) |
| - `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) |
| + - the connector is confirmed, whatever its kind (R2 #7). Only outbox rows of kind `verify` (the email confirm link, the Slack test with its link, the signed webhook test) go to an unconfirmed connector. Rule subscriptions may name unconfirmed connectors, but nothing ordinary reaches them until they are confirmed. |
| - 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)` |
| @@ -346,6 +363,8 @@ |
| - `TestDrainSkipsNeedsReentry` |
| - `TestDrainSkipsRevokedOperatorQueued`: queue a row, revoke the operator, drain. There is no send, and the row and connector are gone. |
| - `TestDrainUnconfirmedEmailGetsNothing` |
| + - `TestDrainUnconfirmedSlackSubscribedGetsNothing`: an explicit subscription and a queued retry both stay unsent until confirmed. A `verify` row is sent. |
| + - `TestRenderWebhookCarriesContent`: a signed delivery carries `what`, `how_long`, `what_to_do` and a `snooze_url` whose token is bound to the incident's key. |
| - `TestTestSendRefusedForUnconfirmedEmail` |
| - `TestTestSendRateLimited`: the 11th in an hour is refused. |
| - `TestDrainErrorStoredHasNoSecret`: the `err_category` column and the captured log hold no `sekrit-XYZ`. |
| @@ -361,9 +380,9 @@ |
| |
| **Interfaces:** |
| - Produces: |
| - - `type alertKey struct{ Scope, Rule, Subject string }` |
| + - Uses `alertKey`, `alertFire` and `alertOneOffRow` from Task 4. |
| - `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 }` |
| + - One-off rows enter the step as signals. Their title and body are appended to the incident's `Details`. |
| - `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. |
| @@ -398,14 +417,16 @@ |
| - `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). |
| + - `opdashboard_test.go:147` and `jobs_test.go:188`: drive `alertEnginePass`. |
| + - **Guard** (Paul's ruling 2026-10-31, after R2 #2): the step 4 check below must return nothing. The list above is the starting point, not the definition of done. |
| - Registries: |
| - `claim_workers.go:5-43` |
| - - `cmd/console/main.go:678`: start `StartAlertEngine` only when `!cfg.HostClaim` |
| + - `cmd/console/main.go:678`: start `StartAlertEngine` as the watcher was. The refusal lives in the worker itself: on `s.cfg.HostClaim` it records job status `"refused: host-claim console"` and returns before any read or write. |
| - `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 |
| + - `claim_invariant_probes_worker_test.go:104-125`: its world is HostClaim (`claim_invariant_world_test.go:521`), so the probe asserts the refusal: the job status says so, and the worker made no store calls and wrote no `alert_*` rows. This replaces the `alert_seen` assertion at :121. Successful incident creation is tested in a non-HostClaim fixture in `alertengine_pass_test.go`. |
| - 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 |
| @@ -420,7 +441,6 @@ |
| **Interfaces:** |
| - 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: |
| - - `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 |
| @@ -434,7 +454,10 @@ |
| 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. |
| + - **Cutover** (R2 #6) is a one-time migration inside `AlertCutover`, so it runs once in one transaction and never again after a restart. It reads the box alert state from step 2 and `alert_seen` per (box, rule, operator): |
| + - **Firing now:** open the incident with `Notified = true`. For each operator whose `alert_seen` is not `firing = 1`, queue a `fire` outbox row to that operator's seeded connector only. |
| + - **Not firing now, but some operator has `alert_seen` `firing = 1`:** a clear is owed. Queue a `clear` row to each such operator's seeded connector, and open no incident. |
| + - Seeding happens in the same transaction, before these rows. |
| 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). |
| @@ -466,7 +489,15 @@ |
| |
| - [ ] **Step 1: Write failing tests.** |
| - `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. |
| + - `TestEnginePassFiveCycleRequests` (R2 #4): fixture with A = 3 alert objects and B = 4 heartbeat objects. A recording `release.Store` wrapper logs method, key and whether each GET was conditional. Over 5 idle passes after a warm-up, the exact request multiset is: |
| + - LISTs: 5× `alerts/boxes/`, 1× `status/boxes/` |
| + - GETs: 5A = 15 alert GETs, B = 4 heartbeat GETs, 1 `status/fleet.json` GET |
| + - every GET is conditional |
| + - no other request |
| + - `TestEnginePassCutoverMixedRecipients`: operator 1 was told the fire and operator 2 wasn't. Only operator 2 gets a fire. |
| + - `TestEnginePassCutoverPendingClear`: the rule has stopped firing and one operator was told the fire. That operator gets one clear. |
| + - `TestEnginePassCutoverSecondStartNoop` |
| + - `TestEnginePassOneOffDetailsSurviveRestart`: raise an egress one-off, step (consumed), restart before `notify_at`. The first message carries the account, app and address from the details. |
| - `TestEnginePassNeverAlertedBoxGoesSilent` (Review Focus 3) |
| - `TestEnginePassBoxGoneCloses` |
| - `TestEnginePassSeedsOperatorEmailOnce` |
| @@ -475,14 +506,15 @@ |
| - `TestEnginePassSealKeyUnreadable` (Review Focus 5): connectors are skipped, a `seal_key` incident is emailed, and email connectors still deliver. |
| - `TestRaiseOneOffDurable` |
| - `TestRaiseNoRoomQuietCloses2h` |
| - - `TestEngineNotStartedInHostClaim` |
| + - `TestEngineRefusesInHostClaim`: the job status says it refused, with zero store calls and no `alert_*` writes. |
| - `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"` |
| +- [ ] **Step 4: Run them, expect PASS.** Also run `go test ./internal/console -run 'Alert|Dashboard|Claim|StoreNotify|Jobs' -count=1` and `go vet ./internal/console ./cmd/console`, which compiles every test file in the package. |
| +- [ ] **Step 5: Guard.** Run `git grep -n -E '\balertPass\b|StartAlertWatcher' -- internal cmd`. Expected: no output. Any hit is a caller to migrate before commit. |
| +- [ ] **Step 6: Commit.** `git commit -m "console: alert engine replaces the alert watcher"` |
| |
| ### Task 9: Copy deck |
| |
| @@ -603,3 +635,16 @@ |
| | 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). | |
| + |
| +## R2 dispositions (Astra, `CODEX-FINDINGS-fleet-alerts-1-plan-R2.md`) |
| + |
| +| # | Sev | Disposition | |
| +|---|---|---| |
| +| 1 | P1 | Paul's ruling (2026-10-31): refuse in root mode. `engineBeatArmed` returns unarmed when `euid == 0`, before any path lookup, and the status line says why. Non-root agents use `os.Lstat`. There is no root read and no rootstate dependency (Task 3). | |
| +| 2 | P1 | Paul's ruling (2026-10-31): a guard check. Task 8 Step 5's `git grep` must be empty, `go vet` compiles every test file, `opdashboard_test.go:147` and `jobs_test.go:188` are named, and the HostClaim probe asserts the refusal. Incident creation is tested without HostClaim. | |
| +| 3 | P1 | Accepted. A grace period starts at arming, whether or not a beat was ever seen. `beatState` distinguishes the five states. Tests cover a never-created beat and a restart while missing (Task 3). | |
| +| 4 | P2 | Accepted. The test asserts the exact request multiset over 5 passes (Task 8). | |
| +| 5 | P2 | Accepted. `alertOneOffRow` carries the ID and time. Details move to `alert_incidents.details` in the consuming transaction. There's a restart test (Tasks 4, 8). | |
| +| 6 | P2 | Accepted. A one-time transactional cutover (`AlertCutover`, marker `cutover_done`) with per-recipient fire and clear rows. Tests cover mixed recipients, a pending clear and a second start (Tasks 4, 8). | |
| +| 7 | P2 | Accepted. The drain requires confirmation for every kind, and only `verify` rows are exempt (Task 6). | |
| +| 8 | P2 | Accepted. The webhook body carries what, how long, what to do and a snooze URL, with a signed-delivery test (Task 6). | |