carlos / platform Public

Plan 1 (engine, connectors, fleet rules); spec approved with plan-time calls

Spec marked APPROVED (Paul, 2026-10-30). Plan-time calls folded into
the spec: connector seal key in its own file beside console.db; disk
forecast keeps its own 6 h ring; SMS, quiet hours and also-send-to move
to Plan 3.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 03d8a26b163edab5e1f1182aac43bc2c3eec7407 parent 9a99f78
2 files changed, +485 −6
  • docs/superpowers/plans/2026-10-30-fleet-alerts-1-engine-connectors.md +455 −0
  • docs/superpowers/specs/2026-10-30-fleet-alerts-and-traffic-design.md +30 −6

CI failed — run details

Intent

Human

<task-notification> <task-id>b9ufxx675</task-id> <tool-use-id>toolu_01MEiTJGdAdhdy2W1eAfmH9R</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/b9ufxx675.output</output-file> <status>failed</status> <summary>Background command "Start mockup server on the Tailscale address, unsandboxed" failed with exit code 143</summary> </task-notification>

Human

<task-notification> <task-id>ab73d97b4c6e07692</task-id> <tool-use-id>toolu_01A7r1zZ39Zbo8H7zhygy2cV</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/ab73d97b4c6e07692.output</output-file> <status>completed</status> <summary>Agent "Map code for alerts Plan 1" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>I've read everything you asked about. Six findings don't match what the spec assumes, and the plan has to settle them before it names functions. Those come first; the reference material for items 1–12 follows. Line numbers are against this worktree. ## Where the code differs from the spec 1. **The console has no seal it can open.** `appconfig.Sealer` seals to a box's ECDH public key. The console only holds `cfg.SecretsPub`, and `server.go:654-660` says "the console cannot decrypt anything". Every secret the console reads back is stored in plain text in console.db: the `keys` table holds PKCS8 base64, and `grants.token` is plain too. §5.1's "use the mechanism the console already uses for app secrets" therefore has nothing to reuse. Sealing a Slack URL needs a new console-held key, for example a new row in the `keys` table plus AES-GCM. The nearest existing code is `sealToBox` (`keymail.go:419`, AES-GCM at :440-444). 2. **The watcher does not use conditional GETs.** `alertPass` does `List` and then a plain `Get` per key. The conditional interface exists: `release.ConditionalGetter` (`internal/release/store.go:221`), `GetIfChanged(ctx context.Context, key, etag string) (body []byte, newETag string, changed bool, err error)`. The pattern to copy is `condGet` in `internal/provision/recordview.go:387`. `hostops.mutationBoundary`, `prefixStore`, `S3Store` and `DirStore` all implement it, and s3fake honours `If-None-Match` (`s3fake.go:240`). 3. **Operator mail today does not go through `deliver()`.** The watcher sends with `s.sendApp`, using each operator's own Keymail grant. `deliver()` sends federated, as the console. Two other callers share the watcher's helpers and must survive its retirement: - `claim_runtime.go:328` `alertSQLDatabaseReplaced` uses `alertRecipients`, `alertDue` and `recordAlertSeen` against `alert_seen` box `"claim-sql"`. - `storenotify.go:64,69` uses `grantRecipients`. Also, on a HostClaim console `consoleMail` is nil (`cmd/console/main.go:1293`), so `deliver()` has no SES fallback there. 4. **The box keeps far less than 6 hours of samples.** `sampler.buf` (`metrics_loop.go:62`) holds only samples not yet flushed (the current hour), capped at `samplerMaxBuf = 120` (:50). The forecast needs its own ring buffer. The disk size is already read but thrown away: `readDiskFrac` (`internal/host/probes.go:209`) calls `diskBytes(dataDir())` (`statfs_unix.go:15`: `func diskBytes(dir string) (total, avail uint64, err error)`) and keeps only the fraction. `HostSample` has no total field. 5. **No Terraform grants `sns:Publish`.** There is no `sns:` action anywhere under `infra/`. `region-host/main.tf:617-643` only creates the memory-alarm topic and its subscription. 6. **Console paging is only armed on a HostClaim console.** `armMovesPaging` returns early when `!cfg.HostClaim`, so everywhere else `alerting.Page` just logs "no sink configured" and returns nil. ## 1. alertwatch.go and alertnow.go **Types (alertwatch.go):** - `type operatorGrant struct { address string; token string }` (:65) - `type alertRun struct { to []operatorGrant; missing []string; noted bool }` (:73) - `const alertWatchInterval = time.Minute` (:38), `const alertPrefix = "alerts/boxes/"` (:42), `const noMailboxAddress = ""` (:95) **Functions:** - `func (s *Server) StartAlertWatcher(ctx context.Context)` (:48): a ticker loop running `s.jobs.Run(ctx, "StartAlertWatcher", s.alertPass)`. - `func (s *Server) alertPass(ctx context.Context) error` (:107): - returns nil if `s.cfg.Releases == nil || s.sendApp == nil`; - `s.cfg.Releases.List(ctx, alertPrefix)`, then `s.alertRecipients()`; - per key: `Get`, unmarshal into `metrics.AlertState`, `s.alertsNow.setBox(...)`, then `s.alertRule(...)` for each rule in sorted order; - finally `keepOnly(listed)` and `markKnown()`. - `func (s *Server) alertRecipients() (*alertRun, error)` (:167) calls `s.store.Operators()` then `grantRecipients`. - `func (s *Server) grantRecipients(addrs []string) (*alertRun, error)` (:178) lower-cases and dedups, calls `s.store.GrantToken(addr)`, and puts addresses with an empty token in `missing`. - `func (s *Server) alertRule(ctx context.Context, run *alertRun, box, rule string, rs metrics.RuleState, updated time.Time)` (:203) - `func (s *Server) alertDueFor(ctx context.Context, box, rule, address string, rs metrics.RuleState) bool` (:248), plus `geoipReasonRule(code float64) string` (:245) - `func (s *Server) recordAlertSeenFor(ctx context.Context, box, rule, address string, rs metrics.RuleState)` (:261) - `func (s *Server) alertDue(ctx context.Context, box, rule, address string, firing bool) bool` (:279) - `func (s *Server) recordAlertSeen(ctx context.Context, box, rule, address string, firing bool)` (:306) - `func alertValueText(rule string, value float64) string` (:323) - `func alertMessage(box, rule string, rs metrics.RuleState, updated time.Time) (subject, body string)` (:340) - `func geoipReasonText(code int) string` (:359) **alertnow.go:** - `type FiringAlert struct { Box, Rule string; Since time.Time }` (:22) - `type alertNow struct` (:31); `newAlertNow()` (:37) - `func (a *alertNow) setBox(box string, rules map[string]metrics.RuleState, now time.Time)` (:42) - `keepOnly(boxes map[string]bool)` (:75), `markKnown()` (:89) - `func (a *alertNow) Firing() (alerts []FiringAlert, known bool)` (:100) - Server field `alertsNow *alertNow` (`server.go:996`), set in NewServer (:1673). The only reader is `opdashboard.go:419`, which feeds `attentionItems` (:108-111). **Registration as a claim worker:** - The registry is the map in `registerClaimWorkers()` (`claim_workers.go:5-43`): `"StartAlertWatcher": s.StartAlertWatcher`. The worker type is `func(context.Context)`. - Each worker is wrapped with `s.jobs.declare(name)` and `claimEntry{Kind: "worker", ...}`. - It is started by `cmd/console/main.go:678`: `go srv.RunClaimWorker(context.Background(), "StartAlertWatcher")`. - `func (s *Server) RunClaimWorker(ctx context.Context, name string)` (`claim_workers.go:57`). **Tests:** - `alertwatch_test.go`: `alertFixture{*consoleFixture; sent []sentMail; err error; failFor string}`, `newCapturedFixture` (which replaces `fx.srv.sendApp` with a capture), `newAlertFixture` (two operators, one grant), `writeAlert` (CAS Put with etag), `pass`. - `alertnow_test.go`: `alertNowFixture` is `newPerfFixture`, i.e. s3fake plus `perfLatency`. Also `publishAlert`, `putAlertBody`, `boxAlert`. - Store-call counting for the request-budget test: `s3fake.Server.Requests() int64` (`s3fake.go:85`), reached through `perfLatency.fake`. ## 2. store.go **How tables are added:** - `func (s *Store) migrate() error` (:142) loops over one `[]string` of `CREATE TABLE IF NOT EXISTS` statements plus `ALTER`s, swallowing "duplicate column" errors. - Newer features add their own `s.migrateX()` call after the list (:605-655). Example: `migrateOperatorPages` in `opstore.go:28`. - `PRAGMA user_version` is only a one-shot backfill marker (:669-690). There are no versioned migrations. - **Every new table must also be classified** in `claimSQLTables` (`store_gate.go:190`). Example: `"alert_seen": {NonApp: "operator alert memory, keyed by box, rule and address"}` (:232). **alert_seen:** - DDL at :237: `box, rule, address TEXT NOT NULL, firing INTEGER NOT NULL, PRIMARY KEY (box, rule, address)`. - `func (s *Store) AlertSeen(box, rule, address string) (firing bool, known bool, err error)` (:2553) - `func (s *Store) SetAlertSeen(box, rule, address string, firing bool) error` (:2570), an upsert with `ON CONFLICT`. - `func (s *Store) Operators() ([]string, error)` (:2526): `SELECT address FROM users WHERE operator != 0 ORDER BY address`. **A small table to copy:** `move_pages` (DDL at :376). Accessors are `func (s *Store) MovePageAttempt(rule string) (time.Time, bool, error)` (:2584) and `func (s *Store) SetMovePageAttempt(rule string, at time.Time) error` (:2597). **Census:** - The record-write census is `TestPlan9B8RecordWriteCensus` (`internal/provision/plan9_b8_census_test.go:360`). Its current head is `fleetPublicRoutesWriteCensusInventory()` (`fleet_public_routes_census_test.go`). - Registering a route changes NewServer's hash. Re-pin it with a new `*_census_test.go` layered on that head, copying `operator_people_detail_census_test.go`: `{"internal/console/server.go", "NewServer", "key-site", "lit:instances", "&lt;sha&gt;"}`. - SQL seam guard: `TestClaimSQLSeamCallers` (`claim_sql_census_test.go:29`). - `internal/console` is outside the root-read census. `internal/host`, `internal/metrics`, `internal/alerting` and `infra/` are inside it, so changes there need `make census-card` and a reviewer. ## 3. deliver() - `type deliveryChannel string` (`delivery.go:11`), with `deliveredKeymail = "keymail"` and `deliveredEmail = "email"`. - `func (s *Server) deliver(ctx context.Context, to, subject, body string, keymailShare time.Duration) (deliveryChannel, error)` (:41). - `keymailShare` is the timeout for the Keymail federated attempt (`context.WithTimeout(ctx, keymailShare)`), so the SES `consoleMail.Send` keeps the rest of ctx. - plangracepass.go:235-237: ```go dctx, cancel := context.WithTimeout(ctx, planNoticeDeliveryTimeout) _, err := s.deliver(dctx, m.Name, subject, body, planNoticeDeliveryTimeout*4/5) cancel() ``` `planNoticeDeliveryTimeout = 15 * time.Second` (:20). Other callers pass `12*time.Second` (`storenotify.go:88`, `authcli.go:1454`). ## 4. Sealing - `type Sealer struct{...}` (`internal/appconfig/sealer.go:18`) - `func NewSealer(pub *ecdh.PublicKey, b Binding, bound bool) Sealer` (:27) - `func (s Sealer) Seal(b Binding, plaintext []byte) (Var, error)` (:48) - The Server builds one per call: `func (s *Server) sealKeyFor(ctx context.Context, acctSqid, app string) (appconfig.Sealer, error)` (`sealkey.go:99`). - It is public-key only, so the console can't open what it seals. There is no type to reuse; see finding 1. ## 5. mailpush signing and address guards **Key:** - Ed25519. `func (s *Store) MailEventsSigningKey() (ed25519.PrivateKey, error)` (:140). - Stored in SQLite: `keys` row `name='mail-events-sign'`, PKCS8 base64, generated on first use with `INSERT OR IGNORE` and then reloaded. - For the alert key, copy this with a new name, e.g. `'alert-sign'`. **Signature:** - `const mailEventSignatureLabel = "carlos-mail-event"` (:81) - `func signMailEvent(priv ed25519.PrivateKey, t time.Time, body []byte) string` (:189) returns `"t=&lt;unix&gt;,ed25519=&lt;std b64 sig&gt;"`, sent as the `Carlos-Signature` header. - `mailEventSignedBytes(ts string, body []byte) []byte` (:195) builds `label + "\n" + ts + "\n" + body`. - `mailEventsPublicKey(priv) string` (:184) returns the raw 32 bytes in std base64. **HTTP client:** - `var mailPushClient = &amp;http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}` (:121). - The timeout comes from the context (`mailPushTimeout`, 10s). - The body is drained with `io.LimitReader(resp.Body, mailPushMaxBody)`, where `mailPushMaxBody = 64&lt;&lt;10`. - Send path: `deliverMailEvent` (:886). **Existing address guards (none fits the spec's check):** | Function | What it does | Reusable? | |---|---|---| | `edgesfile.PrivateAddress(addr string, cidrs []string) (string, string)` (`internal/edgesfile/private.go:15`) | Accepts private IPv4 inside given CIDRs | No, it's the inverse | | `usableDoorAddr(addr string) bool` (`internal/edge/door.go:142`) | `IsGlobalUnicast() &amp;&amp; !IsPrivate()` | No CGNAT, metadata or IPv6 special cases | | `publiclyDialable(addr string) bool` (`internal/provision/reconcile.go:471`) | Same check on host:port | Same gaps | | `geo.Locatable(ip net.IP) bool` (`internal/geo/mmdb.go:332`) | Refuses loopback, private, link-local, CGNAT (`var cgnat` 100.64/10), unspecified | Closest match, but it's a geo helper | None of them dials. There is no `net.Dialer{Control: ...}` anywhere in the repo, so the "dial the IP you checked" guard is new code. ## 6. Rate limiter - `type emailLimits struct` (`emailsignin_limits.go:126`). The zero value is ready to use. Fields are `mu`, `now func() time.Time` and a set of `keyedWindow`s. - `type keyedWindow struct { hits map[string][]time.Time }` (:38), with `trim/count/last/remove/add/sweep`. - The function to copy is `func (l *emailLimits) signinSend(addr, ip string) bool` (:192): an all-or-nothing hourly and daily check. Constants are `signinPerAddrHour = 5` and `signinPerAddrDay = 20`. - Server field: `limits emailLimits` (`server.go:1146`). There is no constructor. ## 7. Box side **internal/metrics/alert.go:** - `type Rules struct { DiskFrac, MemFrac float64; MemSustain; CPUFrac; CPUSustain; LagSecs int64; ClearBy float64; GeoIPSustain }` (:11) - `func DefaultRules() Rules` (:25), `func RulesFromEnv(getenv func(string) string) Rules` (:45) - `type Observation struct { At; CPUFrac, MemFrac, DiskFrac *float64; LagSecs *int64; GeoIP *float64 }` (:79) - `type RuleState struct { Firing bool; Since, FiredAt time.Time; Value float64 }` (:101) - `type AlertState struct { V int; Box string; UpdatedAt time.Time; Rules map[string]RuleState }` (:111) - `type Event struct { Rule string; Firing bool; Value float64; Box string }` (:120) - `func AlertKey(box string) string` (:129) - `func Evaluate(r Rules, st AlertState, obs Observation) (AlertState, []Event)` (:157) **internal/metrics/sample.go:** - `HostSample{CPUFrac, Load1, Load5, Load15, MemFrac, DiskFrac *float64}`. There is no disk total. - `Sample{At, Host, Units}`. **metrics_loop.go:** - Signature (:513): ```go func alertTick(ctx context.Context, s release.Store, box string, rules metrics.Rules, st *metrics.AlertState, latest metrics.Sample, statePath string, sinks *alertSinks) error ``` - It builds an `Observation` from `latest`, calls `Evaluate`, runs `putAlertState` only when there are events, then loops `sinks.deliver(ctx, rules, latest.At, ev)` over every event (:531-535), then persists to `&lt;dataDir&gt;/monitor/alerts.json`. - `metricsLoop` (:805) ticks every 60s: `sm.tick(probes)`, `latest := sm.buf[len(sm.buf)-1]`, `alertTick`, and `metricsFlush` every fifth tick. History is covered in finding 4. **internal/host/alertsink.go:** - `func (a *alertSinks) deliver(ctx context.Context, rules metrics.Rules, at time.Time, ev metrics.Event)` (:93). The webhook gets raw `json.Marshal(ev)`; SNS gets `formatAlert(rules, at, ev)` (:323). - Also `PageOperator` (:117) and `buildAlertSinks` (:284). **internal/alerting/alerting.go:** - `type Sinks struct { WebhookURL string; Post func(url string, body []byte) error; TopicARN string; Pub Publisher; WebhookFailed, SNSFailed func() }` (:54) - `func (s *Sinks) Page(ctx context.Context, level, subject, body string) error` (:115). The webhook gets `pagePayload{Kind:"page",Level,Subject,Body}`. - `func Arm(s *Sinks)` (:175), `func Page(ctx context.Context, level, subject, body string) error` (:183) - `func FromEnv(ctx context.Context, getenv func(string) string, newClient func(context.Context, string) (Publisher, error)) *Sinks` (:198) - `func PostJSON(url string, body []byte) error` (:224): 5s timeout, follows redirects. - `func NewSNSClient(ctx context.Context, region string) (Publisher, error)` (:272), via `rootaws.LoadDefaultConfig`. - `LevelIncident` and `LevelWarning` (:35-36). ## 8. Operator pages and the route checklist - Route registration: `server.go:1753`, `s.registerRoute("GET /fleet/metrics", s.handleFleetMetrics)`. - `func (s *Server) registerRoute(pattern string, h http.HandlerFunc)` (`claim_routes.go:68`). - `func (s *Server) operatorOnly(w http.ResponseWriter, r *http.Request) (address, rawToken string, ok bool)` (`server.go:3742`). - `var opRail = []opRailItem{...}` (`opshell.go:30`), e.g. `{Key: "metrics", Href: "/fleet/metrics", Label: "Metrics"}`. - `func (s *Server) opPage(addr, raw, rail string) page` (`opshell.go:69`). - Template to copy: `templates/ops_boxes.html` (`{{define "ops_boxes"}}{{template "op_top" .}}…`) or `ops_person.html`. Templates are picked up by the `templates/*.html` embed glob. Registries a new route or worker must satisfy (all paths under `internal/console/`): | Registry | Example entry | |---|---| | `testdata/claim-routes.txt` (`TestClaimConsoleRouteCensus`, `claim_routes_test.go:25`) | `route GET /fleet/metrics`, `worker StartAlertWatcher` | | `claim_invariant_fixtures_test.go` | `"route GET /fleet/metrics": claimRead("operator box metrics"),` (:903); `"worker StartAlertWatcher": claimNonApp("box alert state under alerts/boxes and operator mail"),` (:2174) | | `claim_invariant_probes_read_test.go` | `"route GET /fleet/metrics": claimPageRead(nil, "/fleet/metrics", "&lt;h1&gt;Metrics&lt;/h1&gt;"),` (:180) | | `claim_invariant_probes_worker_test.go` | `"worker StartAlertWatcher": {setup, do: claimWorkerReply(...), effect}` (:104) | | `perfTargets` (`perfwalk_test.go:481`) | Only needed for screens with path parameters or no 200 at the bare path | | `testdata/perf-budgets.txt` | `GET /a/{sqid}/fleets/{fleet} calls 2: &lt;reason&gt;`, or `&lt;screen&gt; skip: POST-only door…` | | `jobs_test.go:35` `jobPassFuncs` | `"StartAlertWatcher": {"alertPass", ...}` | | `jobs.go:278` `jobLabels` | `"StartAlertWatcher": "Alert checks"` | | `opshots_test.go:30` | `{"metrics", "/fleet/metrics"}` | | `store_gate.go` `claimSQLTables` | One entry per new table | | Record-write census | NewServer re-pin (section 2) | ## 9. Paging call sites | Site | Call | |---|---| | `cmd/console/main.go:652` → `armMovesPaging` :1831 | `if !cfg.HostClaim { return false }; alerting.Arm(alerting.FromEnv(ctx, getenv, nil))` | | `nocapacity.go:133` | `pageNoCapacity(ctx, alerting.LevelWarning, subject, body)`, in a goroutine with a 30s timeout; `var pageNoCapacity = alerting.Page` (:59) | | `egressfleet.go:451` | `page(sctx, alerting.LevelWarning, subject, body)`; `page` is `st.page` or `var pageEgressConflict = alerting.Page` (:161) | | `hostsused.go:394` | `alerting.Page(ctx, alerting.LevelIncident, reason, reason)` | | `lifetimes_floor.go:164` | `lifetimesPage(ctx, alerting.LevelIncident, subject, "its edges file at control/edges/"+f.Box+".json does not list "+capLifetimes1)`; `var lifetimesPage = alerting.Page` (:42) | | `lifetimes_cutover.go:474` | `alerting.Page(ctx, alerting.LevelIncident, pageLifetimesMarkerUnread, err.Error())` | | `movesrecovery.go:620` | `alerting.Page(ctx, level, subject, body)`; dedup through `move_pages` | | `claim_loss_pages.go:138` | `return alerting.Page(ctx, alerting.LevelWarning, subject, body)` | All of them share the shape `func(ctx context.Context, level, subject, body string) error`. Three already go through a package-level variable, which is the natural place to put one routing function. ## 10. AWS clients - SNS: `alerting.NewSNSClient(ctx, region)`, which uses `rootaws.LoadDefaultConfig(ctx context.Context, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error)` (`internal/rootaws/config.go:37`; plain SDK chain when not root). - SES: `mail.NewSESEmailSender(ctx context.Context, region string) (EmailSender, error)` (`internal/mail/sessend.go:21`), wired by `consoleMailer(...)` (`cmd/console/main.go:1291`). `type ConsoleMailer interface { Send(ctx, to, subject, body string) error; Ready(ctx) bool }` (`consolemail.go:33`). - `alerting` already imports the AWS SDK. A "core packages don't import AWS" SMS interface needs a new adapter package. - IAM: see finding 5. The only console mail grant is `host_console_mail` (SES, `main.tf:769`). ## 11. Fleet summary and certificate expiry - `status.Fleet.Services []struct{Name string; Up bool}` (`fleet.go:81`). The console reads it with `func FleetView(ctx context.Context, s release.Store) (*status.Fleet, error)` (`view.go:923`), a plain Get of `status/fleet.json` called through `opFleetJSON` (`opboxes.go:30`). The dashboard's "is down" line is at `opdashboard.go:101-104`. - `CertExpiresAt` arrives in the heartbeat's private `BoxMetrics.Aliases map[string]AliasReading` (`snapshot.go:646`). `AliasReading{Route, DNSStatus, DNSCheckedAt, CertExpiresAt int64}` (:736) is filled for routes with a stamp and for alias rows (:1026-1076). - Loader: `func aliasReadings(ctx context.Context, s release.Store, now time.Time) map[string]status.AliasReading` (`apidomains.go:1645`). It goes through `status.LoadBoxes(ctx, s)` (`fleet.go:151`), skips boxes where `status.BoxStale(b, now, status.SnapshotPeriod)` is true, and the freshest `DNSCheckedAt` wins. - `alerts=not-delivered` is only computed by the CLI (`cli.go:4163` `alertsWord`): `!Webhook &amp;&amp; !SNS &amp;&amp; !SNSUnavailable`. It is built from `BoxMetrics.Alerts *status.AlertDelivery` (`snapshot.go:557`). The console reads that field nowhere today. `AlertDelivery.Delivered()` (:771) ignores `SNSUnavailable`, so it doesn't give the same answer. ## 12. Running tests - Gate: `make test`, which runs `.amadan/test-gate.sh` (vet, gofmt, tests with `-count=1`). `internal/console` is split 8 ways (`TEST_SPLIT=./internal/console=8 ...`). - Single package: `go test ./internal/console -run X -count=1`. - In the sandbox, AGENTS.md:284 says to use `GOCACHE=/tmp/claude-1001/gocache GOFLAGS=-mod=mod GOPROXY=off`; go may need the sandbox off ("read-only file system" is the sign). Separately, my own read-only commands hit the bwrap mount error, so I ran them with the sandbox off as you allowed. - `TestMain` moves TMPDIR/GOTMPDIR out from under a `.carlos/config` (root package). Nothing else wraps the tests, and there is no `-exec`. - Census: - `make census-card` runs `TestPlan14RootReadCensusPropose` with `CARLOS_CENSUS_CARD=1` and writes nothing. - `make census-propose NAME=&lt;branch&gt; CLAIMS=&lt;file&gt;` writes the overlay, its chain line and the card. - Record-write census: `go test ./internal/provision -run TestPlan9B8RecordWriteCensus -count=1`.</result> <usage><subagent_tokens>205509</subagent_tokens><tool_uses>78</tool_uses><duration_ms>339285</duration_ms></usage> </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
new file mode 100644
index 000000000..ea9d1604e
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-30-fleet-alerts-1-engine-connectors.md
@@ -0,0 +1,455 @@
+# Fleet alerts Plan 1: engine, connectors, fleet rules — Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** 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.
+
+**Tech Stack:** Go, SQLite (console.db), `html/template`, `release.Store` / `GetIfChanged`, Ed25519, AES-256-GCM.
+
+**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.
+
+## 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
+ - 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.
+- 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").
+
+## 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.
+
+---
+
+## File structure
+
+| 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 |
+
+---
+
+### Task 1: Disk forecast rule (pure)
+
+**Files:**
+- Create: `internal/metrics/forecast.go`, `internal/metrics/forecast_test.go`
+- Modify: `internal/metrics/alert.go` (`Rules` :11, `DefaultRules` :25, `RulesFromEnv` :45, `Observation` :79, `Evaluate` :157)
+- Test: `internal/metrics/alert_test.go`
+
+**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"`
+
+- [ ] **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`.
+
+ 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.
+- [ ] **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
+
+**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"\``)
+- Test: `internal/host/metrics_loop_test.go`
+
+**Interfaces:**
+- Consumes: `metrics.DiskPoint`, `metrics.DiskETA`, `Observation.DiskETAHours` (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).
+
+- [ ] **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`.
+- [ ] **Step 4: Run them, expect PASS.**
+- [ ] **Step 5: Commit.** `git commit -m "host: disk trend ring, disk_eta observation, box sinks incident-only"`
+
+### Task 3: Slack-shaped sink body; engine-silent backstop
+
+**Files:**
+- 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)
+- 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.
+
+- [ ] **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.
+- [ ] **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 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"`.
+
+### Task 4: Alert tables, connector seal
+
+**Files:**
+- Create: `internal/console/alertstore.go`, `internal/console/alertseal.go`, plus `_test.go` for each
+- Modify:
+ - `internal/console/store.go` (call `s.migrateAlerts()` after the list, as `migrateOperatorPages`, :605-655)
+ - `internal/console/store_gate.go:190` (`claimSQLTables`)
+
+**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.
+- Produces:
+ - `type alertConnector struct{ ID int64; Scope, Kind, Name, TargetHint 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)`
+ - 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.
+
+- [ ] **Step 1: Write failing tests.**
+ - `TestAlertTablesMigrateTwice`: running migrate twice is a no-op.
+ - `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.
+ - `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.
+- [ ] **Step 4: Run them, expect PASS.**
+- [ ] **Step 5: Commit.** `git commit -m "console: alert tables and connector seal"`
+
+### Task 5: Guarded outside-URL client and alert signing
+
+**Files:**
+- Create: `internal/console/alertdial.go`, `internal/console/alertsign.go`, plus tests
+- Modify: `internal/console/store.go` (`AlertSigningKey()`, copying `MailEventsSigningKey` :140 with name `'alert-sign'`)
+
+**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`
+ - `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.
+ - `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.
+ - `TestAlertClientNoRedirect`
+ - `TestPostAlertReadsAtMost1KiB`
+ - `TestSignAlertVerifies`: the signature verifies over the label, timestamp and body. A mail-event label doesn't verify.
+- [ ] **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"`
+
+### Task 6: Senders and the delivery queue
+
+**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`)
+- 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.
+ - `func (s *Server) sendTestAlert(ctx context.Context, scope string, id int64) error`
+
+- [ ] **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`
+- [ ] **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 4: Run them, expect PASS.**
+- [ ] **Step 5: Commit.** `git commit -m "console: alert senders and delivery queue"`
+
+### Task 7: Incident engine (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:
+ - `TestStepOneFireOneClear`
+ - `TestStepGroupsFiveBoxes`: one fire, members = 5
+ - `TestStepLateMemberUpdateHourly`
+ - `TestStepFlapping`
+ - `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.
+- [ ] **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"`
+
+### Task 8: Engine worker, signals, console pages routed, watcher retired
+
+**Files:**
+- Create: `internal/console/alertsignals.go`, plus test
+- 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`
+
+**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)
+- 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.
+
+- [ ] **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"`
+
+### Task 9: Copy deck
+
+**Files:**
+- 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.
+- [ ] **Step 4: Commit.** `git commit -m "console: approved alert copy"`
+
+### Task 10: `/fleet/alerts` pages and public token doors
+
+**Files:**
+- Create: `internal/console/alertpages.go`, `internal/console/templates/ops_alerts.html`, `ops_alerts_history.html`, plus `alertpages_test.go`
+- Modify:
+ - `server.go` (register 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`
+
+**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`
+ - `POST /fleet/alerts/connectors/{id}/delete`
+ - `POST /fleet/alerts/rules/{rule}`: enabled, threshold, connector IDs
+ - `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`).
+
+- [ ] **Step 1: Write failing tests.**
+ - `TestFleetAlertsNotOperator404`
+ - `TestFleetAlertsAddSlackSendsTest`
+ - `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.
+ - `TestAlertsSigningKeyServed`
+ - Add a probe and fixture for each route. The registry tests fail until they're 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"`
+
+### Task 11: Docs, roll notes, branch gate
+
+**Files:**
+- Modify: `README.md` (alerting section near :923-942)
+- Create: `docs/superpowers/notes/roll-fleet-alerts-1.md`
+
+- [ ] **Step 1: README.** Document:
+ - `/fleet/alerts`
+ - the connector kinds
+ - `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"`
+
+---
+
+## 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.
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 ecdb2bd2d..6160a8f09 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
@@ -1,6 +1,6 @@
# Alerts, connectors and fleet traffic
-Status: draft for Paul, 2026-10-30. Branch `design-fleet-alerts`.
+Status: APPROVED by Paul 2026-10-30 ("go ahead"). Branch `design-fleet-alerts`.
One alert engine, with connectors (Slack, email, SMS, signed webhook),
serving three audiences: fleet operators, account owners and app owners.
@@ -174,8 +174,21 @@ multiply setup.
Connector secrets (Slack URLs, webhook URLs) are sealed at rest and
never shown again after saving. The page shows the host and the last
-four characters. The builder picks the sealing mechanism the console
-already uses for app secrets.
+four characters.
+
+The console has no seal it can open today. `appconfig.Sealer` seals to a
+box's key, and the console only holds the public half
+(`server.go:654-660`).
+
+So, my call (plan time):
+- **Key:** an AES-256-GCM key in its own 0600 file beside console.db,
+ created on first use.
+- **Why a separate file:** the key must not be in the database. console.db
+ is replicated to the bucket, so a replica or backup alone must not
+ reveal a Slack URL.
+- **If the key file is lost** (a restore from the replica alone), each
+ sealed connector shows "needs re-entering" and is skipped, with one
+ operator incident. Nothing fails silently.
### 5.2 Subscription
@@ -301,6 +314,12 @@ The **disk forecast** is computed on the box from its own samples:
and has stayed under it for the hold window
- it clears when the projection passes 1.5x the threshold
- 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
+ (time, used bytes), one point a minute for 6 hours
+- it needs at least 2 hours of points before it forecasts anything, so
+ after an agent restart it stays silent for 2 hours (my call; not worth
+ persisting)
Other forecasts (memory creep, a region filling) are left for later.
The same fitting function should be reusable.
@@ -509,7 +528,11 @@ Rule 6 (something Paul can see lands first) shapes the order.
The alert watcher retires.
- **First merge Paul can see:** a Slack message to the operators'
channel for a forecast disk on dev.
- - **SMS adapter:** in this plan, for operators.
+ - **SMS adapter:** moved to Plan 3 (plan-time call). No Terraform
+ grants `sns:Publish` today. SMS needs an IAM change and an SNS SMS
+ origination setup, both under the production-infrastructure rule.
+ Holding Plan 1 for that would delay the Slack path Paul asked for
+ first.
- **Switch-on:** at its release.
2. **Fleet traffic.** Edge fleet counters, unknown-host counting,
heartbeat fields, console.db series, the `/fleet/traffic` page, and
@@ -518,7 +541,9 @@ Rule 6 (something Paul can see lands first) shapes the order.
3. **Account and app alerts.** Per-app window object, enforced-only
refusal counters, edge timing,
the account and app Alerts tabs, member self-serve email, SMS for
- paid plans, and plan caps re-routed.
+ operators and paid plans, quiet hours and "also send to" (§5.2,
+ both off by default; moved here at plan time), and plan caps
+ re-routed.
- **Switch-on:** at its release. New apps get the defaults from
§7.3.
@@ -564,7 +589,6 @@ AWS SDK.
- Table shapes, names, and the incident ID format.
- The Slack block layout, within copy review.
-- The sealing mechanism for connector secrets, reusing an existing one.
- Histogram bucket boundaries for timing.
- Whether the engine's heartbeat reads share `status.LoadBoxes`' cache.
- The SMS sender ID and origination setup on AWS. This needs scoped