carlos / platform Public

alerting: Slack body, no redirects; host: engine_silent backstop, refused for root agents

Census claim: internal/host/enginebeat.go engineBeatLstat: Lstat of CARLOS_ALERT_ENGINE_BEAT, reached only when euid != 0 (engineBeatArmed refuses root before any lookup; TestEngineBeatRootRefusedBeforeLookup)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev ce6970832cd4dc52db4f180e8bcbd11816ca1f18 parent 0ea2aaf
16 files changed, +964 −50
  • cli.go +20 −5
  • docs/superpowers/notes/census-card-fleet-alerts-1.txt +23 −0
  • internal/alerting/alerting.go +40 −4
  • internal/alerting/alerting_test.go +116 −0
  • internal/host/agent.go +3 −2
  • internal/host/alertsink.go +36 −10
  • internal/host/alertsink_test.go +81 −14
  • internal/host/enginebeat.go +161 −0
  • internal/host/enginebeat_linux_test.go +338 −0
  • internal/host/metrics_loop.go +19 −5
  • internal/host/metrics_loop_test.go +9 −9
  • internal/metrics/alert.go +22 −1
  • internal/metrics/alert_test.go +36 −0
  • internal/status/snapshot.go +16 −0
  • internal/status/snapshot_test.go +38 −0
  • statuslive_test.go +6 −0

Intent

Human

<task-notification> <task-id>add4bc7ae26abb707</task-id> <tool-use-id>toolu_01HTJVDaQX8sDN4AAr8uT7zM</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/add4bc7ae26abb707.output</output-file> <status>completed</status> <summary>Agent "Implement Task 2: box disk trend" 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>**Status:** DONE_WITH_CONCERNS **Commit:** 0ea2aaf1 "host: disk trend ring, disk_eta, box sinks incident-only" **Tests:** The targeted tests pass, and so does a wider run over the changed host and status code. `go vet` is clean, and the darwin and windows builds of `internal/host` succeed. - Deletion scenario (46 GiB start, +1 GiB/h until it fires, drop 4 GiB, then flat): the clear comes 100 minutes after the drop, inside the 2 h. - Sustained flat: the clear comes 187 minutes after usage goes flat, before the 6 h bound. The test asserts the fit still forecasts growth on every tick before it. **Concerns:** - The deletion test drops 4 GiB and then holds flat. If usage kept growing at +1 GiB/h after the drop, the median slope would stay positive and nothing would clear. - The heartbeat calls `verdict(time.Now())` itself instead of reading a cached last ETA, so it gets the 5-minute stale guard. It costs a few ms every 5 minutes. - Mem, cpu, lag and geoip transitions no longer reach box sinks, as the brief says. No existing test relied on them. - The default go cache is read-only inside the sandbox, so go commands ran with the sandbox disabled. - The commit trailer says Sonnet 5.5, from the session's attribution instruction. `env.md` names Opus 5.5. - The commit printed the `packed-refs.lock` warning, but it landed. **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/.superpowers/sdd/2026-10-30-fleet-alerts-1-engine-connectors/task-2-report.md</result> <usage><subagent_tokens>106545</subagent_tokens><tool_uses>25</tool_uses><duration_ms>465117</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>ad0b037e7b140d7d5</task-id> <tool-use-id>toolu_01Lc9UrhXkdzYEA5wWyEyiK3</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/ad0b037e7b140d7d5.output</output-file> <status>completed</status> <summary>Agent "Review Task 2 (spec + quality)" 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>### Spec Compliance - ✅ Spec compliant. Every brief item and controller ruling has a matching hunk. - `diskTrend` is in `internal/host/disktrend.go:124-152`. It has a 360 cap, `add`, and `verdict(now)`, which returns Unknown when the newest point is more than 5 minutes old (`disktrend.go:157-163`). - `readDiskBytes` is in `internal/host/probes.go`. `readDiskFrac` and `sampleProbes.diskFrac` are untouched. - `sampleProbes.diskBytes` is added and wired in `realSampleProbes`. - `alertTick` takes `trend *diskTrend` as its last parameter (`internal/host/metrics_loop.go:521`). - The sink loop skips any event where `!boxSinkRule(ev.Rule)` (`metrics_loop.go` near the old :531). - `BoxMetrics.DiskFullETAHours` carries the `json:"disk_full_eta_hours,omitempty"` tag. - All five brief tests are present, plus `TestDiskTrendVerdictIgnoresStaleSeries`, `TestRecordDiskPoint` and `TestBoxSinkRule`. - `recordDiskPoint` (`disktrend.go:168-177`) adds a point only when the read is `ok` and total &gt; 0. It adds one per tick, stamped with the tick time (`latest.At`). - ⚠️ Deviation from the brief: the brief says the snapshot writer "reads the trend's last ETA". `diskETAProbe` (`disktrend.go:182-191`, called at `agent.go` statusLoop) recomputes `verdict(time.Now())` instead. It still yields the ETA only when the verdict is `TrendGrowing`, and it gains the 5-minute staleness guard. The cost is one extra O(n²) fit at n ≤ 360, about 64k pairs, per 5-minute heartbeat. I judge this acceptable, but the controller should confirm the departure from "last ETA". - ⚠️ Cannot verify from the diff: whether `engine_silent` exists as a rule name anywhere yet. `boxSinkRule` hard-codes it, as the brief says, and nothing in this diff emits it. ### Strengths - The ring is small and correct. `snapshot` copies under the lock and the O(n²) fit runs outside it (`disktrend.go:143-163`), so the writer never waits on the fit. - `readDiskBytes` rejects `avail &gt; total` and a zero total, so a bad statfs cannot underflow `uint64` or divide by zero (`probes.go`, `readDiskBytes`). - The staleness test pins the boundary: exactly 5 minutes is still Growing, and 5 minutes plus 1 second is Unknown (`disktrend_test.go:264-269`). - The deletion and sustained-flat tests drive the real `alertTick` and `metrics.Evaluate` at 1-minute steps. The flat test asserts the verdict and ETA on every tick before the clear, so the clear cannot arrive early or late unnoticed (`metrics_loop_test.go`, `TestAlertTickSustainedFlatClears`). - `TestAlertTickSinksIncidentOnly` would fail without the gate. It asserts the sink received nothing for the `disk_eta` fire, that the state file and published state contain `disk_eta`, and that a following `disk` fire reaches the sink. ### Named-risk checks - **`alertTick` callers.** I grepped for `alertTick(`. There is one non-test caller (`metrics_loop.go:888`, passes `&amp;processDiskTrend`) and the test callers in `alertsink_test.go` and `metrics_loop_test.go`. All pass the extra argument. `sampleProbes{` literals in tests (`metrics_owner_test.go:69,135`, `metrics_loop_test.go:35,116,369`) leave `diskBytes` nil, and `recordDiskPoint` handles nil. - **darwin and windows builds.** `diskBytes(dir) (total, avail uint64, err error)` exists in both `statfs_unix.go:15` and `statfs_windows.go:13` with the same signature. `probes.go` is untagged and `readDiskFrac` already called it. The new files use only `sync` and `time`, so no platform-specific code was added. I did not run the cross builds; the implementer reports they pass. - **Concurrency.** The metrics loop is the only writer, through `add`. The status loop reads through `verdict`, which calls `snapshot`. Both take `d.mu`, and the fit runs on the copy. This is safe. `processDiskTrend` is a package-level zero-value variable like `processAlertCounters`. `mu` is a value inside the struct and the variable is only ever used by address, so there is no copy-lock issue. - **gofmt.** `gofmt -l` is clean on all touched files. ### Issues #### Critical (Must Fix) None. #### Important (Should Fix) None. #### Minor (Nice to Have) - `metrics_loop.go:~877-888` and `agent.go` (the `DiskFullETAHours: diskETAProbe(...)` line): the wiring that records a point each tick, and the statusLoop line that fills the probe, are not covered by any test. Tests call `diskTrend.add`, `recordDiskPoint` and `diskETAProbe` directly. A one-line tick test with a fake `diskBytes` would pin `recordDiskPoint` being called before `alertTick`. - `metrics_loop_test.go:712`: `for name, path := range map[string]string{"state file": r.statePath}` loops over a one-entry map. A plain `os.ReadFile` would be clearer. - Behaviour to know about, from Task 1 code rather than this diff: when a firing `disk_eta` meets a stale or empty ring (statfs failing for more than 5 minutes), the verdict is Unknown and `evalETA` returns early (`internal/metrics/alert.go:288`). The rule then stays firing, held rather than cleared. That seems the right conservative choice, but no test pins it for the stalled-sampler case. ### Assessment **Task quality:** Approved **Reasoning:** The ring, probe, sink gating and heartbeat field match the brief and rulings. Concurrency is correct, callers are all updated, and the platform-specific statfs signatures match. Tests exercise real `alertTick` and `Evaluate` behaviour, and the only gaps are Minor wiring-coverage ones.</result> <usage><subagent_tokens>72453</subagent_tokens><tool_uses>5</tool_uses><duration_ms>53279</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a20e0a155120d0ca9</task-id> <tool-use-id>toolu_01BheZ8k99dqNSfVPN8QGtz3</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/a20e0a155120d0ca9.output</output-file> <status>completed</status> <summary>Agent "Implement Task 3: Slack sink and engine_silent" 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>- **Status:** BLOCKED at step 5, the census. Nothing is committed. The code and tests are finished and pass, and the changes are in the worktree uncommitted. - **Blocker:** the census card lists one new unit from this change: `internal/host/enginebeat.go:var engineBeatLstat` reads `+file:Lstat` (new disposition `legacy`). The census only reads source: every file read in the `carlos` binary counts as a root read, so it can't see the runtime `euid == 0` refusal. No non-root read in `internal/host` can get a clean card. At runtime the refusal holds: `TestEngineBeatRootRefusedBeforeLookup` makes zero stat calls as root and the rule never appears. - **Your call:** accept it as a `new` unit, with a claim saying it runs only for non-root agents and naming that test, for the reviewer on #280 at Task 11. Or rule some other way. The exact `git add` line for committing as-is is in the report. - **Commits:** none. - **Tests:** the new and touched tests pass in alerting, status, metrics, host (all 30 in the filter, Task 2's forecast tests unchanged) and the `TestPrintLiveBoxes` group. Build, vet, and darwin and windows builds pass. darwin vet of `internal/host` fails on an older test (`hawake_wiring_test.go`, `claimsOnEnv`) that fails the same way at base 0ea2aaf1. - **Engine-beat status:** I carried it in the heartbeat's `AlertDelivery` as `engine_beat` and `engine_beat_why`, so `carlos status --live` shows `engine-beat=off (agent runs as root)`. The agent's log says the same at startup. - **Concerns:** - The 10-minute grace runs from the later of agent start and the last fresh read. Inside it, "no evidence" gives nil rather than false, so only a fresh beat clears the alert. - A stale beat fires immediately, as the brief says. A console-box reboot longer than 10 minutes therefore sends one fire and one clear. - Two additions beyond the brief: release refusals also get the Slack body, and `SlackBody` escapes `&amp;`, `&lt;` and `&gt;`. - The wording of `engine_silent` alerts is left to Task 9. - **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/.superpowers/sdd/2026-10-30-fleet-alerts-1-engine-connectors/task-3-report.md - **Census card (untracked):** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/docs/superpowers/notes/census-card-fleet-alerts-1.txt</result> <usage><subagent_tokens>179293</subagent_tokens><tool_uses>54</tool_uses><duration_ms>687377</duration_ms></usage> </task-notification>

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

diff --git a/cli.go b/cli.go
index eed6c7e8f..f2b804ac3 100644
--- a/cli.go
+++ b/cli.go
@@ -4114,10 +4114,10 @@ func printLiveBoxesWith(w io.Writer, boxes []status.Box, now time.Time, places l
fmt.Fprintf(w, "%-24s %-12s ok (no metrics block — pre-upgrade host)\n", b.Label, orDash(liveRegion(b, places)))
continue
}
- fmt.Fprintf(w, "%-24s %-12s release=%s tunnel=%s mem=%s/%s load=%s disk-free=%s alerts=%s\n",
+ fmt.Fprintf(w, "%-24s %-12s release=%s tunnel=%s mem=%s/%s load=%s disk-free=%s alerts=%s%s\n",
b.Label, orDash(liveRegion(b, places)), orDash(m.Release), orDash(m.Tunnel),
humanBytes(m.MemAvailBytes), humanBytes(m.MemTotalBytes),
- humanFloat(m.Load1), humanBytes(m.DiskFreeBytes), alertsWord(m.Alerts))
+ humanFloat(m.Load1), humanBytes(m.DiskFreeBytes), alertsWord(m.Alerts), engineBeatWord(m.Alerts))
for _, r := range m.ReleaseRefusals {
if r.Kind == release.RefusalWrongProgram {
fmt.Fprintf(w, " refused %s %s since %s: wrong program (%s)\n", r.Host, r.Version, r.RefusedAt.UTC().Format(time.RFC3339), strings.TrimPrefix(r.Reason, "wrong program: "))
@@ -4164,6 +4164,9 @@ func alertsWord(a *status.AlertDelivery) string {
if a == nil {
return "-"
}
+ if a.NotDelivered() {
+ return "not-delivered"
+ }
var sinks []string
if a.Webhook {
sinks = append(sinks, "webhook")
@@ -4171,9 +4174,6 @@ func alertsWord(a *status.AlertDelivery) string {
if a.SNS {
sinks = append(sinks, "sns")
}
- if len(sinks) == 0 && !a.SNSUnavailable {
- return "not-delivered"
- }
out := strings.Join(sinks, "+")
if a.SNSUnavailable {
// A topic is configured but its client could not be built. Alone it
@@ -4193,6 +4193,21 @@ func alertsWord(a *status.AlertDelivery) string {
return out
}
+// engineBeatWord is the engine_silent backstop's state beside alerts=, with
+// its leading space, or nothing on a box where it is not configured. "off"
+// carries its reason: a root-run agent refuses to watch the beat (fleet
+// alerts spec §8).
+func engineBeatWord(a *status.AlertDelivery) string {
+ if a == nil || a.EngineBeat == "" {
+ return ""
+ }
+ out := " engine-beat=" + a.EngineBeat
+ if a.EngineBeatWhy != "" {
+ out += " (" + a.EngineBeatWhy + ")"
+ }
+ return out
+}
+
// orDash, humanBytes and humanFloat render one field of a metrics block.
// Unknown is a dash in all three — never a zero, never a blank column: the
// status package carries "I couldn't measure this" as a nil pointer all the
diff --git a/docs/superpowers/notes/census-card-fleet-alerts-1.txt b/docs/superpowers/notes/census-card-fleet-alerts-1.txt
new file mode 100644
index 000000000..1d7644bd4
--- /dev/null
+++ b/docs/superpowers/notes/census-card-fleet-alerts-1.txt
@@ -0,0 +1,23 @@
+# Census approval: <name>
+
+Ruling `census-ruling-<name>`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/host/agent.go` `statusLoop` | body | unchanged (6) | (no claim yet) |
+| `internal/status/snapshot.go` `CollectBox` | body | unchanged (28) | (no claim yet) |
+
+Envelopes re-pinned: `.`, `internal/alerting`, `internal/host`, `internal/metrics`, `internal/status`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/host/agent.go` `statusLoop`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): the status tick's context carries the box's lifetime judge; read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 953b9fda (its later changes, regional box names and self-serve moves plan 1 among them, under main's own census rulings), where the tick fills rootfs_ready and rootfs_blocked from armedRootfs.Load().probe, which each tick runs NestedOK's checks and asks the control socket's GET /ready/rootfs (never the store); the same four direct sites;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 11 and #329 plan 3 Task 7: takes root's GET /egress reader and fills p.Egress = egressStatusProbe(egressStatus, routes, provision.PolicyReadStates()) and p.SizeCommittedMiB = sizeCommittedMiB(armedSizeSource.Load(), routes); the two added whole:Route sites are the tick's own registry list handed to those two units (decision rows), which read root's control socket and the activator's memory; no store request added; the four existing sites unchanged, offsets moved.
+- `internal/status/snapshot.go` `CollectBox`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-apps-2;basis=copies Probes.RootfsReady and RootfsBlocked into BoxMetrics (private, like Layout); the same 28 sites, no read added;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 11 and #329 plan 3 Task 7: copies Probes.Egress and Probes.SizeCommittedMiB into BoxMetrics (private, like Layout) and counts them in the condition that builds Metrics; the same 28 sites, no read added.;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3: comment only, the Hibernate count is left as is (display);rev3=census-ruling-regional-domains-447;basis=#447 Task 7: copies Probes.AliasesRead into BoxMetrics.AliasesRead (json aliases_read, omitempty) and counts it in the condition that builds Metrics; the same 28 sites, no read added
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/host/enginebeat.go:var engineBeatLstat`: reads +file:Lstat; written legacy, accepted-legacy, frozen
+
+Seal now: `1379d066c8dd2335d95d5f6e9c7bce65ff57f00b2b287a308d9b3f47911ae5e7`. Dry run: nothing written.
diff --git a/internal/alerting/alerting.go b/internal/alerting/alerting.go
index ec088e105..e9666abf6 100644
--- a/internal/alerting/alerting.go
+++ b/internal/alerting/alerting.go
@@ -15,6 +15,7 @@ import (
"fmt"
"log"
"net/http"
+ "net/url"
"regexp"
"strings"
"sync"
@@ -105,7 +106,8 @@ type pagePayload struct {
}
// Page sends one page to every configured sink: the webhook gets
-// {"kind":"page","level","subject","body"}, SNS the subject (made to fit
+// {"kind":"page","level","subject","body"} (or SlackBody when it is a Slack
+// incoming webhook, IsSlackWebhook), SNS the subject (made to fit
// SNS's rules) and the body, with the level as a message attribute so a
// subscription can filter on it. The caller's subject and body are the
// whole message: no URL, ARN or credential is added here, and the caller
@@ -121,7 +123,13 @@ func (s *Sinks) Page(ctx context.Context, level, subject, body string) error {
}
var errs []error
if s.HasWebhook() {
- b, err := json.Marshal(pagePayload{Kind: "page", Level: level, Subject: subject, Body: body})
+ var b []byte
+ var err error
+ if IsSlackWebhook(s.WebhookURL) {
+ b = SlackBody(subject, body)
+ } else {
+ b, err = json.Marshal(pagePayload{Kind: "page", Level: level, Subject: subject, Body: body})
+ }
if err == nil {
err = s.PostWebhook(b)
}
@@ -219,10 +227,38 @@ func FromEnv(ctx context.Context, getenv func(string) string, newClient func(con
return s
}
+// IsSlackWebhook is whether u is a Slack incoming webhook: https on
+// hooks.slack.com. Slack rejects any body but its own, so a box or console
+// pointed at one sends SlackBody instead of its own JSON (fleet alerts spec
+// §8). A look-alike host or a plain-http URL is not one.
+func IsSlackWebhook(u string) bool {
+ p, err := url.Parse(strings.TrimSpace(u))
+ return err == nil && p.Scheme == "https" && strings.EqualFold(p.Hostname(), "hooks.slack.com")
+}
+
+// slackEscaper escapes the three characters Slack reads as markup in text,
+// as Slack documents: without it a "<channel>" in a message vanishes and a
+// "<!channel>" pings everyone in the channel.
+var slackEscaper = strings.NewReplacer("&", "&amp;", "<", "&lt;", ">", "&gt;")
+
+// SlackBody is a Slack incoming-webhook body: {"text":"*<subject>*\n<body>"},
+// the subject in bold over the body.
+func SlackBody(subject, body string) []byte {
+ b, _ := json.Marshal(struct {
+ Text string `json:"text"`
+ }{"*" + slackEscaper.Replace(subject) + "*\n" + slackEscaper.Replace(body)})
+ return b
+}
+
// PostJSON is the production webhook post: a 5 second POST with a JSON
-// content type. Any non-2xx status is an error.
+// content type. Any non-2xx status is an error. It follows no redirect: the
+// 3xx is the answer, and an error, so a body meant for one URL is never
+// re-sent somewhere the operator did not configure.
func PostJSON(url string, body []byte) error {
- client := &http.Client{Timeout: 5 * time.Second}
+ client := &http.Client{
+ Timeout: 5 * time.Second,
+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
+ }
resp, err := client.Post(url, "application/json", bytes.NewReader(body))
if err != nil {
return err
diff --git a/internal/alerting/alerting_test.go b/internal/alerting/alerting_test.go
index c84a93f87..3bdb3c944 100644
--- a/internal/alerting/alerting_test.go
+++ b/internal/alerting/alerting_test.go
@@ -6,7 +6,10 @@ import (
"encoding/json"
"errors"
"log"
+ "net/http"
+ "net/http/httptest"
"strings"
+ "sync/atomic"
"testing"
"github.com/aws/aws-sdk-go-v2/service/sns"
@@ -239,3 +242,116 @@ func TestFromEnvBuildsTheConsoleSinks(t *testing.T) {
t.Fatalf("nothing set: %+v", s)
}
}
+
+// slackText decodes a Slack incoming-webhook body and returns its text,
+// failing when the body has any other key: Slack rejects a body it does not
+// know, so nothing else may ride along.
+func slackText(t *testing.T, body []byte) string {
+ t.Helper()
+ var got map[string]any
+ if err := json.Unmarshal(body, &got); err != nil {
+ t.Fatalf("slack body %s: %v", body, err)
+ }
+ text, ok := got["text"].(string)
+ if !ok || len(got) != 1 {
+ t.Fatalf("slack body %s, want only a text string", body)
+ }
+ return text
+}
+
+// A page to a Slack incoming webhook goes as Slack's {"text"} body, the
+// subject in bold over the body (fleet alerts spec §8). SNS is unchanged.
+func TestPageSlackBody(t *testing.T) {
+ var posts []posted
+ pub := &fakeSNS{}
+ url := "https://hooks.slack.com/services/T000/B000/XXXX"
+ s := &Sinks{WebhookURL: url, Post: poster(&posts, nil), TopicARN: testTopicARN, Pub: pub}
+ if err := s.Page(context.Background(), LevelIncident, "carlos move stuck: shop.example", "the body.\nsecond line."); err != nil {
+ t.Fatal(err)
+ }
+ if len(posts) != 1 || posts[0].url != url {
+ t.Fatalf("webhook posts: %+v", posts)
+ }
+ if got, want := slackText(t, posts[0].body), "*carlos move stuck: shop.example*\nthe body.\nsecond line."; got != want {
+ t.Fatalf("slack text %q, want %q", got, want)
+ }
+ if len(pub.in) != 1 || *pub.in[0].Message != "the body.\nsecond line." {
+ t.Fatalf("sns publish changed: %+v", pub.in)
+ }
+}
+
+// Anything that is not an https URL on hooks.slack.com keeps today's
+// {"kind":"page"} body, including look-alikes.
+func TestPageNonSlackUnchanged(t *testing.T) {
+ for _, url := range []string{
+ "http://example.test/hook",
+ "http://hooks.slack.com/services/T000/B000/XXXX",
+ "https://hooks.slack.com.example.test/services/T000",
+ "https://example.test/hooks.slack.com/services/T000",
+ "https://example.test/?u=https://hooks.slack.com/",
+ "not a url",
+ } {
+ var posts []posted
+ s := &Sinks{WebhookURL: url, Post: poster(&posts, nil)}
+ if err := s.Page(context.Background(), LevelWarning, "subj", "body"); err != nil {
+ t.Fatal(err)
+ }
+ var got map[string]string
+ if len(posts) != 1 || json.Unmarshal(posts[0].body, &got) != nil {
+ t.Fatalf("%s: posts %+v", url, posts)
+ }
+ if got["kind"] != "page" || got["level"] != "warning" || got["subject"] != "subj" || got["body"] != "body" {
+ t.Errorf("%s: payload %s, want the page body", url, posts[0].body)
+ }
+ }
+}
+
+func TestIsSlackWebhook(t *testing.T) {
+ for url, want := range map[string]bool{
+ "https://hooks.slack.com/services/T000/B000/XXXX": true,
+ "https://HOOKS.slack.com/services/T000": true,
+ " https://hooks.slack.com/services/T000 ": true,
+ "http://hooks.slack.com/services/T000": false,
+ "https://hooks.slack.com.example.test/services": false,
+ "https://example.test/hooks.slack.com": false,
+ "https://user@example.test/": false,
+ "": false,
+ } {
+ if got := IsSlackWebhook(url); got != want {
+ t.Errorf("IsSlackWebhook(%q) = %v, want %v", url, got, want)
+ }
+ }
+}
+
+// Slack reads &, < and > as markup (a <!channel> would ping everyone), so
+// they are escaped the way Slack documents.
+func TestSlackBodyEscapes(t *testing.T) {
+ got := slackText(t, SlackBody("a <b> & c", "run carlos promote --retry v1 <channel>"))
+ if want := "*a &lt;b&gt; &amp; c*\nrun carlos promote --retry v1 &lt;channel&gt;"; got != want {
+ t.Fatalf("slack text %q, want %q", got, want)
+ }
+}
+
+// PostJSON follows no redirect: a 3xx is the answer, and a non-2xx one is an
+// error. The redirect's target is never contacted (fleet alerts constraints,
+// outbound HTTP).
+func TestPostJSONRefusesRedirect(t *testing.T) {
+ var reached atomic.Int32
+ target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ reached.Add(1)
+ }))
+ defer target.Close()
+ for _, code := range []int{http.StatusMovedPermanently, http.StatusFound, http.StatusTemporaryRedirect, http.StatusPermanentRedirect} {
+ hook := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, target.URL+"/elsewhere", code)
+ }))
+ err := PostJSON(hook.URL, []byte(`{}`))
+ hook.Close()
+ if err == nil {
+ t.Errorf("%d: PostJSON returned nil, want a non-2xx error", code)
+ }
+ }
+ if n := reached.Load(); n != 0 {
+ t.Fatalf("the redirect target was reached %d times", n)
+ }
+}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 8a3d267d0..04eb831af 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -4345,8 +4345,9 @@ func statusLoop(reg *registry.Registry, svc *activator.Service, buildStates func
RestartPathRunning: restartPathActive(),
// Whether this box's own alert rules have anywhere to deliver,
// read from the env the metrics loop's sinks are built from
- // (discussion #192: an unset webhook was silent for weeks).
- Alerts: alertDeliveryProbe(os.Getenv, nil),
+ // (discussion #192: an unset webhook was silent for weeks),
+ // and whether the engine_silent backstop is on.
+ Alerts: alertDeliveryProbe(os.Getenv, nil, os.Geteuid()),
// ExpiredCanaries answers spec §5 for this box's own routes; see
// countExpiredCanaries and the canaryStore/canaryPub comment above.
ExpiredCanaries: countExpiredCanaries(ctx, routes, canaryStore, canaryPub, time.Now()),
diff --git a/internal/host/alertsink.go b/internal/host/alertsink.go
index 2a1509634..95bd4f682 100644
--- a/internal/host/alertsink.go
+++ b/internal/host/alertsink.go
@@ -21,7 +21,8 @@ import (
//
// Two sinks, either, both, or neither:
//
-// CARLOS_ALERT_WEBHOOK the event as JSON, POSTed (httpPostWebhook)
+// CARLOS_ALERT_WEBHOOK the event as JSON, POSTed (httpPostWebhook),
+// or Slack's text body for a Slack URL
// CARLOS_ALERT_SNS_TOPIC_ARN a plain-text subject and message, published
// to that SNS topic with the box's instance role
//
@@ -95,7 +96,16 @@ func (a *alertSinks) deliver(ctx context.Context, rules metrics.Rules, at time.T
return
}
if a.sinks.HasWebhook() {
- evBody, err := json.Marshal(ev)
+ var evBody []byte
+ var err error
+ if alerting.IsSlackWebhook(a.sinks.WebhookURL) {
+ // Slack rejects the raw event; it gets the email's words
+ // (fleet alerts spec §8).
+ subject, message := formatAlert(rules, at, ev)
+ evBody = alerting.SlackBody(subject, message)
+ } else {
+ evBody, err = json.Marshal(ev)
+ }
if err != nil {
log.Printf("host: alert event %s: marshal: %v", ev.Rule, err)
} else if err := a.sinks.PostWebhook(evBody); err != nil {
@@ -154,13 +164,19 @@ func (a *alertSinks) deliverRelease(ctx context.Context, r release.Refusal) {
return
}
if a.sinks.HasWebhook() {
- body, err := json.Marshal(struct {
- Kind string `json:"kind"`
- // The record's own Kind is shadowed by the envelope's "kind"
- // above, so it travels as refusal_kind.
- RefusalKind string `json:"refusal_kind,omitempty"`
- release.Refusal
- }{"release_refused", r.Kind, r})
+ var body []byte
+ var err error
+ if alerting.IsSlackWebhook(a.sinks.WebhookURL) {
+ body = alerting.SlackBody(formatReleaseAlert(r))
+ } else {
+ body, err = json.Marshal(struct {
+ Kind string `json:"kind"`
+ // The record's own Kind is shadowed by the envelope's "kind"
+ // above, so it travels as refusal_kind.
+ RefusalKind string `json:"refusal_kind,omitempty"`
+ release.Refusal
+ }{"release_refused", r.Kind, r})
+ }
if err == nil {
if err := a.sinks.PostWebhook(body); err != nil {
log.Printf("host: alert webhook post (release refusal %s): %v", r.Host, err)
@@ -242,7 +258,12 @@ func parseAlertTopicARN(s string) (region string, err error) { return alerting.P
// counts, which buildAlertSinks fills in. So the snapshot reports the sink the
// agent really holds: a topic ARN that does not parse is not a sink, and one
// whose client failed to build reads SNS=false, SNSUnavailable=true.
-func alertDeliveryProbe(getenv func(string) string, counts *alertCounters) *status.AlertDelivery {
+//
+// It also carries the engine_silent backstop's state, from the same
+// engineBeatArmed the metrics loop arms on (euid is the agent's): "on", or
+// "off" with the reason, so a root-run agent's refusal is visible in
+// carlos status --live and not only in the journal.
+func alertDeliveryProbe(getenv func(string) string, counts *alertCounters, euid int) *status.AlertDelivery {
if counts == nil {
counts = &processAlertCounters
}
@@ -251,6 +272,11 @@ func alertDeliveryProbe(getenv func(string) string, counts *alertCounters) *stat
WebhookFailures: counts.webhook.Load(),
SNSFailures: counts.sns.Load(),
}
+ if _, armed, why := engineBeatArmed(getenv, euid); armed {
+ out.EngineBeat = "on"
+ } else if why != "" {
+ out.EngineBeat, out.EngineBeatWhy = "off", why
+ }
if _, err := parseAlertTopicARN(getenv("CARLOS_ALERT_SNS_TOPIC_ARN")); err == nil {
// Only an initialised client is a sink. snsInitUnknown (not built
// yet, or the metrics loop never got there) is neither available
diff --git a/internal/host/alertsink_test.go b/internal/host/alertsink_test.go
index 8a033bf29..fa0a7994c 100644
--- a/internal/host/alertsink_test.go
+++ b/internal/host/alertsink_test.go
@@ -2,6 +2,7 @@ package host
import (
"context"
+ "encoding/json"
"errors"
"os"
"path/filepath"
@@ -241,10 +242,10 @@ func TestAlertTickDeliversThroughSinks(t *testing.T) {
disk := 0.95
latest := metrics.Sample{At: sinkTestAt, Host: metrics.HostSample{DiskFrac: &disk}}
- if err := alertTick(ctx, store, box, rules, st, latest, statePath, sinks, nil); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, latest, statePath, sinks, nil, nil); err != nil {
t.Fatal(err)
}
- if err := alertTick(ctx, store, box, rules, st, latest, statePath, sinks, nil); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, latest, statePath, sinks, nil, nil); err != nil {
t.Fatal(err)
}
if len(pub.in) != 1 {
@@ -257,7 +258,7 @@ func TestAlertTickDeliversThroughSinks(t *testing.T) {
// Clearing is a transition too.
low := 0.30
cleared := metrics.Sample{At: sinkTestAt.Add(time.Minute), Host: metrics.HostSample{DiskFrac: &low}}
- if err := alertTick(ctx, store, box, rules, st, cleared, statePath, sinks, nil); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, cleared, statePath, sinks, nil, nil); err != nil {
t.Fatal(err)
}
if len(pub.in) != 2 || !strings.Contains(deref(pub.in[1].Subject), "cleared") {
@@ -307,12 +308,12 @@ func TestAlertDeliveryProbe(t *testing.T) {
env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } }
counts := &alertCounters{}
- got := alertDeliveryProbe(env(nil), counts)
+ got := alertDeliveryProbe(env(nil), counts, 1000)
if got.Webhook || got.SNS || got.Delivered() {
t.Errorf("nothing set: %+v, want nothing delivered", got)
}
- got = alertDeliveryProbe(env(map[string]string{"CARLOS_ALERT_WEBHOOK": "http://x"}), counts)
+ got = alertDeliveryProbe(env(map[string]string{"CARLOS_ALERT_WEBHOOK": "http://x"}), counts, 1000)
if !got.Webhook || got.SNS || !got.Delivered() {
t.Errorf("webhook only: %+v", got)
}
@@ -320,32 +321,98 @@ func TestAlertDeliveryProbe(t *testing.T) {
// A valid ARN alone is not a sink until buildAlertSinks has built the
// client: before that (a stalled build, or a metrics loop that exited
// first) the box must not claim sns.
- got = alertDeliveryProbe(env(map[string]string{"CARLOS_ALERT_SNS_TOPIC_ARN": testTopicARN}), counts)
+ got = alertDeliveryProbe(env(map[string]string{"CARLOS_ALERT_SNS_TOPIC_ARN": testTopicARN}), counts, 1000)
if got.SNS || got.SNSUnavailable || got.Delivered() {
t.Errorf("sink not yet built must not read as sns: %+v", got)
}
counts.snsInit.Store(snsInitOK)
- got = alertDeliveryProbe(env(map[string]string{"CARLOS_ALERT_SNS_TOPIC_ARN": testTopicARN}), counts)
+ got = alertDeliveryProbe(env(map[string]string{"CARLOS_ALERT_SNS_TOPIC_ARN": testTopicARN}), counts, 1000)
if got.Webhook || !got.SNS || !got.Delivered() {
t.Errorf("sns only: %+v", got)
}
// A malformed ARN is not a sink: the box has nowhere to deliver, and
// the snapshot must say so rather than claim an sns sink it cannot use.
- got = alertDeliveryProbe(env(map[string]string{"CARLOS_ALERT_SNS_TOPIC_ARN": "nonsense"}), counts)
+ got = alertDeliveryProbe(env(map[string]string{"CARLOS_ALERT_SNS_TOPIC_ARN": "nonsense"}), counts, 1000)
if got.SNS || got.Delivered() {
t.Errorf("bad arn counted as a sink: %+v", got)
}
counts.sns.Add(3)
counts.webhook.Add(2)
- got = alertDeliveryProbe(env(map[string]string{"CARLOS_ALERT_SNS_TOPIC_ARN": testTopicARN}), counts)
+ got = alertDeliveryProbe(env(map[string]string{"CARLOS_ALERT_SNS_TOPIC_ARN": testTopicARN}), counts, 1000)
if got.SNSFailures != 3 || got.WebhookFailures != 2 {
t.Errorf("failure counts not carried: %+v", got)
}
}
+// The engine-beat answer rides the alerts block: absent with the env unset,
+// on for a non-root agent with a usable path, and off with the reason for a
+// root-run one (Paul's ruling, 2026-10-31).
+func TestAlertDeliveryProbeEngineBeat(t *testing.T) {
+ env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } }
+ beat := map[string]string{"CARLOS_ALERT_ENGINE_BEAT": "/data/console/alert-engine.beat"}
+ cases := []struct {
+ name string
+ env map[string]string
+ euid int
+ want string
+ wantWhy string
+ }{
+ {"unset", nil, 1000, "", ""},
+ {"unset as root", nil, 0, "", ""},
+ {"armed", beat, 1000, "on", ""},
+ {"root", beat, 0, "off", "agent runs as root"},
+ {"relative path", map[string]string{"CARLOS_ALERT_ENGINE_BEAT": "alert-engine.beat"}, 1000, "off", "path is not absolute"},
+ }
+ for _, c := range cases {
+ got := alertDeliveryProbe(env(c.env), &alertCounters{}, c.euid)
+ if got.EngineBeat != c.want || got.EngineBeatWhy != c.wantWhy {
+ t.Errorf("%s: engine beat %q (%q), want %q (%q)", c.name, got.EngineBeat, got.EngineBeatWhy, c.want, c.wantWhy)
+ }
+ }
+}
+
+// TestBoxDeliverSlackBody: with a Slack incoming-webhook URL the box posts
+// Slack's {"text"} body (the email's subject in bold over its body), not the
+// raw event Slack would reject (fleet alerts spec §8). Release refusals take
+// the same shape. Any other URL keeps the event JSON.
+func TestBoxDeliverSlackBody(t *testing.T) {
+ var bodies [][]byte
+ post := func(_ string, body []byte) error { bodies = append(bodies, body); return nil }
+ s := newAlertSinks("https://hooks.slack.com/services/T000/B000/XXXX", post, "", nil, &alertCounters{})
+ ev := metrics.Event{Rule: "disk", Firing: true, Value: 0.95, Box: "box-a"}
+ s.deliver(context.Background(), metrics.DefaultRules(), sinkTestAt, ev)
+ if len(bodies) != 1 {
+ t.Fatalf("posts = %d, want 1", len(bodies))
+ }
+ var got map[string]any
+ if err := json.Unmarshal(bodies[0], &got); err != nil || len(got) != 1 {
+ t.Fatalf("slack body %s: %v, want only text", bodies[0], err)
+ }
+ subject, message := formatAlert(metrics.DefaultRules(), sinkTestAt, ev)
+ if want := "*" + subject + "*\n" + message; got["text"] != want {
+ t.Fatalf("slack text %q, want %q", got["text"], want)
+ }
+
+ s.deliverRelease(context.Background(), release.Refusal{Host: "shop.example", Version: "v2", RestoredVersion: "v1", Recovered: true, RefusedAt: sinkTestAt, Reason: "did not start"})
+ got = nil
+ if len(bodies) != 2 || json.Unmarshal(bodies[1], &got) != nil || len(got) != 1 {
+ t.Fatalf("release refusal slack body: %s", bodies[len(bodies)-1])
+ }
+ if text, _ := got["text"].(string); !strings.HasPrefix(text, "*shop.example: v2 did not start, rolled back to v1*\n") {
+ t.Fatalf("release refusal slack text %q", text)
+ }
+
+ bodies = nil
+ webhookSinks("https://example.test/hook", post).deliver(context.Background(), metrics.DefaultRules(), sinkTestAt, ev)
+ var raw metrics.Event
+ if len(bodies) != 1 || json.Unmarshal(bodies[0], &raw) != nil || raw != ev {
+ t.Fatalf("non-slack body %s, want the event", bodies)
+ }
+}
+
// fakeClientFactory is the buildAlertSinks seam: it records the region it
// was asked for and either hands back a fake or fails.
type fakeClientFactory struct {
@@ -375,7 +442,7 @@ func TestBuildAlertSinksInitialisedSNS(t *testing.T) {
if len(f.pub.in) != 1 {
t.Fatalf("publishes = %d, want 1", len(f.pub.in))
}
- got := alertDeliveryProbe(env(map[string]string{"CARLOS_ALERT_SNS_TOPIC_ARN": testTopicARN}), counts)
+ got := alertDeliveryProbe(env(map[string]string{"CARLOS_ALERT_SNS_TOPIC_ARN": testTopicARN}), counts, 1000)
if !got.SNS || got.SNSUnavailable || got.SNSFailures != 0 {
t.Errorf("a working sink must read as sns: %+v", got)
}
@@ -395,7 +462,7 @@ func TestBuildAlertSinksClientFailureIsVisible(t *testing.T) {
sinks.deliver(context.Background(), metrics.DefaultRules(), sinkTestAt,
metrics.Event{Rule: "disk", Firing: true, Value: 0.95, Box: "box-a"})
- got := alertDeliveryProbe(env, counts)
+ got := alertDeliveryProbe(env, counts, 1000)
if got.SNS || !got.SNSUnavailable || got.Delivered() {
t.Errorf("failed init must read as unavailable and not delivered: %+v", got)
}
@@ -405,7 +472,7 @@ func TestBuildAlertSinksClientFailureIsVisible(t *testing.T) {
// With a webhook as well, the box still delivers, and says what is wrong.
envMap["CARLOS_ALERT_WEBHOOK"] = "http://example.test/hook"
- got = alertDeliveryProbe(env, counts)
+ got = alertDeliveryProbe(env, counts, 1000)
if !got.Webhook || got.SNS || !got.SNSUnavailable || !got.Delivered() {
t.Errorf("webhook alone must still deliver: %+v", got)
}
@@ -424,7 +491,7 @@ func TestBuildAlertSinksBadARNIsNotASinkAndBuildsNoClient(t *testing.T) {
if len(f.regions) != 0 {
t.Errorf("a subscription ARN must not build a client: %v", f.regions)
}
- got := alertDeliveryProbe(env, counts)
+ got := alertDeliveryProbe(env, counts, 1000)
if got.SNS || got.Delivered() {
t.Errorf("subscription ARN counted as a sink: %+v", got)
}
@@ -437,7 +504,7 @@ func TestBuildAlertSinksNothingConfigured(t *testing.T) {
if len(f.regions) != 0 {
t.Errorf("no ARN set, yet a client was built: %v", f.regions)
}
- got := alertDeliveryProbe(func(string) string { return "" }, counts)
+ got := alertDeliveryProbe(func(string) string { return "" }, counts, 1000)
if got.Delivered() || got.SNSUnavailable {
t.Errorf("nothing configured: %+v", got)
}
diff --git a/internal/host/enginebeat.go b/internal/host/enginebeat.go
new file mode 100644
index 000000000..21c5f808d
--- /dev/null
+++ b/internal/host/enginebeat.go
@@ -0,0 +1,161 @@
+package host
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+)
+
+// The engine_silent backstop (fleet alerts spec §8). The console's alert
+// engine writes a beat file every pass; on the box that runs the console,
+// the agent pages its own sinks when that beat is over 10 minutes old, or
+// when no usable beat has turned up within 10 minutes of the agent starting.
+// The agent's sinks do not run through the console, so this is the one
+// alert that still reaches someone when the engine has stopped.
+//
+// A root-run agent does not watch the beat at all (Paul, 2026-10-31, after
+// plan review R2 #1). The beat is a file the console writes, and a root
+// process reading a console-written path crosses the root trust boundary,
+// so engineBeatArmed refuses on euid 0 before the path is ever looked at,
+// and the heartbeat says why. A non-root agent reads it with os.Lstat, so a
+// symlink is not followed and reads as beatNotRegular.
+
+const (
+ // engineBeatEnv names the beat file the console writes
+ // (Config.AlertEngineBeatPath on the console side).
+ engineBeatEnv = "CARLOS_ALERT_ENGINE_BEAT"
+ // engineBeatStale is how old a beat may be and still be fresh.
+ engineBeatStale = 10 * time.Minute
+ // engineBeatGrace is how long the armed agent waits for a fresh beat
+ // before no beat at all counts as silence. It runs from arming (agent
+ // start), or from the last fresh read, so a restart restarts it.
+ engineBeatGrace = 10 * time.Minute
+ // engineBeatSkew is how far ahead of the agent's tick time a beat's
+ // mtime may be and still be read as written now: the engine can write
+ // between the sample and the read. Further ahead is beatFuture.
+ engineBeatSkew = time.Minute
+)
+
+// beatState is what one read of the beat file found.
+type beatState int
+
+const (
+ beatFresh beatState = iota // a regular file at most engineBeatStale old
+ beatStale // a regular file older than engineBeatStale
+ beatMissing // no file, or one the agent cannot stat
+ beatNotRegular // a symlink, directory or anything not a plain file
+ beatFuture // an mtime more than engineBeatSkew ahead of now
+)
+
+func (s beatState) String() string {
+ switch s {
+ case beatFresh:
+ return "fresh"
+ case beatStale:
+ return "stale"
+ case beatMissing:
+ return "missing"
+ case beatNotRegular:
+ return "not regular"
+ case beatFuture:
+ return "future"
+ }
+ return "unknown"
+}
+
+// engineBeatLstat is the one filesystem call the backstop makes. A package
+// var so a test can prove a root-run agent never makes it.
+var engineBeatLstat = os.Lstat
+
+// engineBeatArmed is whether this agent watches the engine beat, and the
+// path it watches. Unset (or blank) is unarmed with no reason: the box does
+// not run a console. euid 0 is refused before anything else is done with
+// the path, with why "agent runs as root". A relative path is refused too:
+// the agent's working directory is not where the console writes.
+func engineBeatArmed(getenv func(string) string, euid int) (path string, armed bool, why string) {
+ raw := strings.TrimSpace(getenv(engineBeatEnv))
+ if raw == "" {
+ return "", false, ""
+ }
+ if euid == 0 {
+ return "", false, "agent runs as root"
+ }
+ if !filepath.IsAbs(raw) {
+ return "", false, "path is not absolute"
+ }
+ return filepath.Clean(raw), true, ""
+}
+
+// readEngineBeat reads the beat at path as of now, with the age of its
+// mtime for a fresh, stale or future beat. Only a non-root agent calls it
+// (engineBeatArmed). Lstat, not Stat: a symlink in the beat's place is
+// beatNotRegular, never followed. A stat error of any kind is beatMissing:
+// a beat the agent cannot see is no evidence the engine is alive.
+func readEngineBeat(path string, now time.Time) (beatState, time.Duration) {
+ fi, err := engineBeatLstat(path)
+ if err != nil {
+ return beatMissing, 0
+ }
+ if !fi.Mode().IsRegular() {
+ return beatNotRegular, 0
+ }
+ age := now.Sub(fi.ModTime())
+ switch {
+ case age < -engineBeatSkew:
+ return beatFuture, age
+ case age < 0:
+ return beatFresh, 0
+ case age > engineBeatStale:
+ return beatStale, age
+ }
+ return beatFresh, age
+}
+
+// engineBeatWatch is one armed agent's watch on the beat: the path, when it
+// was armed, and when it last read a fresh beat (zero for never). The
+// metrics loop owns it; alertTick asks it for each tick's reading.
+type engineBeatWatch struct {
+ path string
+ armedAt time.Time
+ lastFresh time.Time
+}
+
+// newEngineBeatWatch arms a watch at now, the agent's start, or returns nil
+// when engineBeatArmed says the agent does not watch: nil is the unarmed
+// rule, which never reads the beat and never creates the rule's key.
+func newEngineBeatWatch(getenv func(string) string, euid int, now time.Time) *engineBeatWatch {
+ path, armed, _ := engineBeatArmed(getenv, euid)
+ if !armed {
+ return nil
+ }
+ return &engineBeatWatch{path: path, armedAt: now}
+}
+
+// silent is the tick's metrics.Observation.EngineSilent. A fresh beat is
+// false and a stale one true. A missing, non-regular or future beat is true
+// once engineBeatGrace has passed since arming or the last fresh read,
+// whichever is later (plan R2 #3: whether or not a beat was ever seen), and
+// nil before that: no evidence either way, so a firing rule restored after a
+// restart neither clears nor pages again. Safe on nil, which is nil.
+func (w *engineBeatWatch) silent(now time.Time) *bool {
+ if w == nil {
+ return nil
+ }
+ yes, no := true, false
+ switch st, _ := readEngineBeat(w.path, now); st {
+ case beatFresh:
+ w.lastFresh = now
+ return &no
+ case beatStale:
+ return &yes
+ }
+ since := w.armedAt
+ if w.lastFresh.After(since) {
+ since = w.lastFresh
+ }
+ if now.Sub(since) >= engineBeatGrace {
+ return &yes
+ }
+ return nil
+}
diff --git a/internal/host/enginebeat_linux_test.go b/internal/host/enginebeat_linux_test.go
new file mode 100644
index 000000000..9b314d194
--- /dev/null
+++ b/internal/host/enginebeat_linux_test.go
@@ -0,0 +1,338 @@
+//go:build linux
+
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/metrics"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+var beatT0 = time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC)
+
+// beatEnv is a getenv with CARLOS_ALERT_ENGINE_BEAT set to path, or with
+// nothing set when path is empty.
+func beatEnv(path string) func(string) string {
+ return func(k string) string {
+ if k == "CARLOS_ALERT_ENGINE_BEAT" {
+ return path
+ }
+ return ""
+ }
+}
+
+// writeBeat creates the beat file at path with mtime.
+func writeBeat(t *testing.T, path string, mtime time.Time) {
+ t.Helper()
+ if err := os.WriteFile(path, []byte("beat\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chtimes(path, mtime, mtime); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// beatRig runs alertTick the way metricsLoop does, with no host readings,
+// and keeps every event the box's webhook sink was sent.
+type beatRig struct {
+ t *testing.T
+ store release.Store
+ statePath string
+ st *metrics.AlertState
+ sinks *alertSinks
+ posted []metrics.Event
+}
+
+func newBeatRig(t *testing.T) *beatRig {
+ t.Helper()
+ r := &beatRig{
+ t: t,
+ store: release.NewDirStore(t.TempDir()),
+ statePath: filepath.Join(t.TempDir(), "monitor", "alerts.json"),
+ st: &metrics.AlertState{V: 1, Box: "box-a", Rules: map[string]metrics.RuleState{}},
+ }
+ r.sinks = webhookSinks("http://example.test/webhook", func(_ string, body []byte) error {
+ var ev metrics.Event
+ if err := json.Unmarshal(body, &ev); err != nil {
+ t.Errorf("sink body is not an event: %s", body)
+ }
+ r.posted = append(r.posted, ev)
+ return nil
+ })
+ return r
+}
+
+// tick runs one alertTick at at and returns what reached the sink on it.
+func (r *beatRig) tick(at time.Time, beat *engineBeatWatch) []metrics.Event {
+ r.t.Helper()
+ before := len(r.posted)
+ if err := alertTick(context.Background(), r.store, "box-a", metrics.DefaultRules(), r.st,
+ metrics.Sample{At: at}, r.statePath, r.sinks, nil, beat); err != nil {
+ r.t.Fatal(err)
+ }
+ return r.posted[before:]
+}
+
+// minutes ticks once a minute from from to to (inclusive) and returns the
+// minute offsets from beatT0 at which the rule fired or cleared.
+func (r *beatRig) minutes(from, to int, beat *engineBeatWatch) (fired, cleared []int) {
+ r.t.Helper()
+ for m := from; m <= to; m++ {
+ for _, ev := range r.tick(beatT0.Add(time.Duration(m)*time.Minute), beat) {
+ if ev.Rule != "engine_silent" {
+ r.t.Fatalf("minute %d: unexpected event %+v", m, ev)
+ }
+ if ev.Firing {
+ fired = append(fired, m)
+ } else {
+ cleared = append(cleared, m)
+ }
+ }
+ }
+ return fired, cleared
+}
+
+// countLstat replaces the beat's stat with one that counts its calls.
+func countLstat(t *testing.T) *int {
+ t.Helper()
+ calls := 0
+ prev := engineBeatLstat
+ engineBeatLstat = func(name string) (fs.FileInfo, error) {
+ calls++
+ return prev(name)
+ }
+ t.Cleanup(func() { engineBeatLstat = prev })
+ return &calls
+}
+
+// TestEngineBeatRootRefusedBeforeLookup is Paul's ruling (2026-10-31, after
+// plan R2 #1): a root-run agent never stats, opens or resolves the beat path,
+// says why, and the rule never appears, even with a beat that would fire.
+func TestEngineBeatRootRefusedBeforeLookup(t *testing.T) {
+ calls := countLstat(t)
+ path := filepath.Join(t.TempDir(), "alert-engine.beat")
+ writeBeat(t, path, beatT0.Add(-time.Hour))
+
+ p, armed, why := engineBeatArmed(beatEnv(path), 0)
+ if armed || p != "" || why != "agent runs as root" {
+ t.Fatalf("root: engineBeatArmed = %q, %v, %q; want unarmed, no path, agent runs as root", p, armed, why)
+ }
+ w := newEngineBeatWatch(beatEnv(path), 0, beatT0)
+ if w != nil {
+ t.Fatalf("root built a watch: %+v", w)
+ }
+ r := newBeatRig(t)
+ if fired, _ := r.minutes(0, 15, w); fired != nil {
+ t.Fatalf("root fired at %v", fired)
+ }
+ if _, ok := r.st.Rules["engine_silent"]; ok {
+ t.Fatal("root created the engine_silent rule")
+ }
+ if *calls != 0 {
+ t.Fatalf("root made %d stat calls on the beat, want 0", *calls)
+ }
+
+ // The same env as a plain user does read it: the counter is live.
+ if w := newEngineBeatWatch(beatEnv(path), 1000, beatT0); w == nil || w.silent(beatT0) == nil || *calls == 0 {
+ t.Fatalf("non-root did not read the beat (calls %d)", *calls)
+ }
+}
+
+func TestEngineBeatArmed(t *testing.T) {
+ cases := []struct {
+ name, env string
+ euid int
+ wantPath string
+ wantArmed bool
+ wantWhy string
+ }{
+ {"unset", "", 1000, "", false, ""},
+ {"blank", " ", 1000, "", false, ""},
+ {"unset as root", "", 0, "", false, ""},
+ {"armed", "/data/console/alert-engine.beat", 1000, "/data/console/alert-engine.beat", true, ""},
+ {"cleaned", "/data/console/../console/alert-engine.beat", 1000, "/data/console/alert-engine.beat", true, ""},
+ {"root", "/data/console/alert-engine.beat", 0, "", false, "agent runs as root"},
+ {"relative", "console/alert-engine.beat", 1000, "", false, "path is not absolute"},
+ }
+ for _, c := range cases {
+ p, armed, why := engineBeatArmed(beatEnv(c.env), c.euid)
+ if p != c.wantPath || armed != c.wantArmed || why != c.wantWhy {
+ t.Errorf("%s: got %q, %v, %q; want %q, %v, %q", c.name, p, armed, why, c.wantPath, c.wantArmed, c.wantWhy)
+ }
+ }
+}
+
+// A symlink is not the beat, even one pointing at a fresh regular file: the
+// read does not follow it. A directory is not the beat either.
+func TestReadEngineBeatSymlinkNotRegular(t *testing.T) {
+ dir := t.TempDir()
+ target := filepath.Join(dir, "real.beat")
+ writeBeat(t, target, beatT0)
+ if st, _ := readEngineBeat(target, beatT0); st != beatFresh {
+ t.Fatalf("the target itself reads %v, want fresh", st)
+ }
+ link := filepath.Join(dir, "alert-engine.beat")
+ if err := os.Symlink(target, link); err != nil {
+ t.Fatal(err)
+ }
+ if st, _ := readEngineBeat(link, beatT0); st != beatNotRegular {
+ t.Fatalf("symlink reads %v, want not regular", st)
+ }
+ if st, _ := readEngineBeat(dir, beatT0); st != beatNotRegular {
+ t.Fatalf("directory reads %v, want not regular", st)
+ }
+}
+
+// An mtime ahead of the agent's clock is not a beat; one a few seconds
+// ahead (the engine wrote between the sample and the read) still is.
+func TestReadEngineBeatFutureMtime(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "alert-engine.beat")
+ cases := []struct {
+ mtime time.Time
+ want beatState
+ age time.Duration
+ }{
+ {beatT0.Add(time.Hour), beatFuture, -time.Hour},
+ {beatT0.Add(2 * time.Minute), beatFuture, -2 * time.Minute},
+ {beatT0.Add(30 * time.Second), beatFresh, 0},
+ {beatT0, beatFresh, 0},
+ {beatT0.Add(-10 * time.Minute), beatFresh, 10 * time.Minute},
+ {beatT0.Add(-11 * time.Minute), beatStale, 11 * time.Minute},
+ }
+ for _, c := range cases {
+ writeBeat(t, path, c.mtime)
+ if st, age := readEngineBeat(path, beatT0); st != c.want || age != c.age {
+ t.Errorf("mtime %v: got %v %v, want %v %v", c.mtime.Sub(beatT0), st, age, c.want, c.age)
+ }
+ }
+ if st, _ := readEngineBeat(filepath.Join(t.TempDir(), "absent.beat"), beatT0); st != beatMissing {
+ t.Errorf("absent file reads %v, want missing", st)
+ }
+}
+
+// R2 #3: an engine that never wrote its beat fires once the armed agent has
+// run 10 minutes, not before and not never.
+func TestEngineSilentNeverCreatedBeatFires(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "alert-engine.beat")
+ w := newEngineBeatWatch(beatEnv(path), 1000, beatT0)
+ r := newBeatRig(t)
+ fired, cleared := r.minutes(0, 20, w)
+ if len(fired) != 1 || fired[0] != 10 || cleared != nil {
+ t.Fatalf("fired at %v, cleared at %v; want one fire at minute 10", fired, cleared)
+ }
+ if _, ok := r.st.Rules["engine_silent"]; !ok || !r.st.Rules["engine_silent"].Firing {
+ t.Fatalf("committed state: %+v", r.st.Rules)
+ }
+
+ // A symlink or a future mtime in its place is no better than nothing.
+ for _, setup := range []func(){
+ func() { _ = os.Symlink("/dev/null", path) },
+ func() { writeBeat(t, path, beatT0.Add(time.Hour)) },
+ } {
+ _ = os.Remove(path)
+ setup()
+ w := newEngineBeatWatch(beatEnv(path), 1000, beatT0)
+ r := newBeatRig(t)
+ if fired, _ := r.minutes(0, 12, w); len(fired) != 1 || fired[0] != 10 {
+ t.Fatalf("fired at %v, want minute 10", fired)
+ }
+ }
+}
+
+// A beat that vanishes after a fresh read gets the same 10 minutes from that
+// read: it fires at 10 minutes without a fresh read, not at once.
+func TestEngineSilentMissingAfterFreshWaitsGrace(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "alert-engine.beat")
+ w := newEngineBeatWatch(beatEnv(path), 1000, beatT0)
+ r := newBeatRig(t)
+ for m := 0; m <= 20; m++ {
+ writeBeat(t, path, beatT0.Add(time.Duration(m)*time.Minute))
+ if evs := r.tick(beatT0.Add(time.Duration(m)*time.Minute), w); len(evs) != 0 {
+ t.Fatalf("minute %d: %v with a fresh beat", m, evs)
+ }
+ }
+ if err := os.Remove(path); err != nil {
+ t.Fatal(err)
+ }
+ fired, _ := r.minutes(21, 35, w)
+ if len(fired) != 1 || fired[0] != 30 {
+ t.Fatalf("fired at %v, want minute 30 (10 minutes after the last fresh read)", fired)
+ }
+}
+
+// An agent restart restarts the grace. Before the fire, the rule waits 10
+// minutes from the restart. After it, a restart that kept its state stays
+// firing (no clear, no repeat page), and one that lost its state fires again
+// 10 minutes after the restart.
+func TestEngineSilentRestartWhileMissing(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "alert-engine.beat")
+
+ // Restart at minute 5, before the fire: the fire moves to minute 15.
+ r := newBeatRig(t)
+ if fired, _ := r.minutes(0, 4, newEngineBeatWatch(beatEnv(path), 1000, beatT0)); fired != nil {
+ t.Fatalf("fired before the restart at %v", fired)
+ }
+ restarted := newEngineBeatWatch(beatEnv(path), 1000, beatT0.Add(5*time.Minute))
+ if fired, _ := r.minutes(5, 20, restarted); len(fired) != 1 || fired[0] != 15 {
+ t.Fatalf("fired at %v, want minute 15", fired)
+ }
+
+ // Restart at minute 22 with the persisted state: still firing, nothing sent.
+ if fired, cleared := r.minutes(22, 40, newEngineBeatWatch(beatEnv(path), 1000, beatT0.Add(22*time.Minute))); fired != nil || cleared != nil {
+ t.Fatalf("restart with state: fired %v, cleared %v; want nothing", fired, cleared)
+ }
+ if !r.st.Rules["engine_silent"].Firing {
+ t.Fatal("restart with state dropped the fire")
+ }
+
+ // Restart at minute 45 with the state file lost: fires again at 55.
+ r2 := newBeatRig(t)
+ if fired, _ := r2.minutes(45, 60, newEngineBeatWatch(beatEnv(path), 1000, beatT0.Add(45*time.Minute))); len(fired) != 1 || fired[0] != 55 {
+ t.Fatalf("restart without state fired at %v, want minute 55", fired)
+ }
+}
+
+// TestEngineSilentFiresThroughAlertTick: an 11-minute-old beat fires at
+// once, the fire is published and reaches the box's sink, and a fresh beat
+// clears it the same way. With the env unset the rule never appears.
+func TestEngineSilentFiresThroughAlertTick(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "alert-engine.beat")
+ writeBeat(t, path, beatT0.Add(-11*time.Minute))
+ w := newEngineBeatWatch(beatEnv(path), 1000, beatT0)
+ r := newBeatRig(t)
+
+ evs := r.tick(beatT0, w)
+ if len(evs) != 1 || evs[0] != (metrics.Event{Rule: "engine_silent", Firing: true, Value: 1, Box: "box-a"}) {
+ t.Fatalf("sink got %+v, want the engine_silent fire", evs)
+ }
+ pub, _, err := r.store.Get(context.Background(), metrics.AlertKey("box-a"))
+ if err != nil || !strings.Contains(string(pub), `"engine_silent"`) {
+ t.Fatalf("published state lacks engine_silent: %v %s", err, pub)
+ }
+
+ writeBeat(t, path, beatT0.Add(time.Minute))
+ evs = r.tick(beatT0.Add(time.Minute), w)
+ if len(evs) != 1 || evs[0].Rule != "engine_silent" || evs[0].Firing {
+ t.Fatalf("sink got %+v, want the engine_silent clear", evs)
+ }
+
+ unset := newEngineBeatWatch(beatEnv(""), 1000, beatT0)
+ if unset != nil {
+ t.Fatalf("unset env built a watch: %+v", unset)
+ }
+ r2 := newBeatRig(t)
+ if fired, _ := r2.minutes(0, 15, unset); fired != nil {
+ t.Fatalf("unset env fired at %v", fired)
+ }
+ if _, ok := r2.st.Rules["engine_silent"]; ok {
+ t.Fatal("unset env created the engine_silent rule")
+ }
+}
diff --git a/internal/host/metrics_loop.go b/internal/host/metrics_loop.go
index ad2a27e7b..8d16cc2f8 100644
--- a/internal/host/metrics_loop.go
+++ b/internal/host/metrics_loop.go
@@ -492,9 +492,11 @@ func pruneStaleRaw(ctx context.Context, s release.Store, box string, now time.Ti
// still firing with no new event and nothing left to retry.
//
// trend is the box's disk ring (disktrend.go); its verdict at the tick time
-// feeds the disk_eta forecast rule. nil leaves that rule alone. Only
-// boxSinkRule's incident rules reach the sinks; every transition still
-// reaches the published and local state.
+// feeds the disk_eta forecast rule. nil leaves that rule alone. beat is the
+// engine_silent backstop's watch (enginebeat.go); nil is the unarmed rule,
+// which reads nothing and never appears in the state. Only boxSinkRule's
+// incident rules reach the sinks; every transition still reaches the
+// published and local state.
//
// Delivery to the sinks is still attempted this tick regardless of whether
// publish succeeded — it's independently fire-and-forget, logged and counted
@@ -520,7 +522,7 @@ func pruneStaleRaw(ctx context.Context, s release.Store, box string, now time.Ti
// their very first over-threshold tick instead of a sustain deadline.
func alertTick(ctx context.Context, s release.Store, box string, rules metrics.Rules,
st *metrics.AlertState, latest metrics.Sample, statePath string,
- sinks *alertSinks, trend *diskTrend) error {
+ sinks *alertSinks, trend *diskTrend, beat *engineBeatWatch) error {
obs := metrics.Observation{
At: latest.At,
@@ -534,6 +536,7 @@ func alertTick(ctx context.Context, s release.Store, box string, rules metrics.R
v, eta := trend.verdict(latest.At)
obs.DiskTrend, obs.DiskETAHours = &v, eta
}
+ obs.EngineSilent = beat.silent(latest.At)
newState, events := metrics.Evaluate(rules, *st, obs)
var publishErr error
@@ -868,6 +871,17 @@ func metricsLoop(execRoot string, src unitSources, owners func() map[string]metr
log.Printf("agent: metrics loop armed (60s ticks, 5min flush), publishing to %s", target)
+ // The engine_silent backstop, armed from the agent's start (its grace
+ // runs from here). A root-run agent refuses it before the path is
+ // looked at, and says so here and in the heartbeat (alertDeliveryProbe).
+ euid := os.Geteuid()
+ if path, armed, why := engineBeatArmed(os.Getenv, euid); armed {
+ log.Printf("agent: engine beat: watching %s", path)
+ } else if why != "" {
+ log.Printf("agent: engine beat: off (%s)", why)
+ }
+ beat := newEngineBeatWatch(os.Getenv, euid, time.Now())
+
sm := &sampler{}
probes := realSampleProbes(execRoot, src, owners)
tick := 0
@@ -885,7 +899,7 @@ func metricsLoop(execRoot string, src unitSources, owners func() map[string]metr
sm.tick(probes)
latest := sm.buf[len(sm.buf)-1]
recordDiskPoint(&processDiskTrend, probes.diskBytes, latest.At)
- if err := alertTick(ctx, s, box, rules, &st, latest, statePath, sinks, &processDiskTrend); err != nil {
+ if err := alertTick(ctx, s, box, rules, &st, latest, statePath, sinks, &processDiskTrend, beat); err != nil {
log.Printf("agent: alert tick: %v", err)
}
diff --git a/internal/host/metrics_loop_test.go b/internal/host/metrics_loop_test.go
index e175d2362..f27e45356 100644
--- a/internal/host/metrics_loop_test.go
+++ b/internal/host/metrics_loop_test.go
@@ -143,7 +143,7 @@ func TestMetricsLoopStoreHonorsFleetPrefix(t *testing.T) {
firing := 0.95
latest := metrics.Sample{At: at, Host: metrics.HostSample{DiskFrac: &firing}}
statePath := filepath.Join(t.TempDir(), "monitor", "alerts.json")
- if err := alertTick(ctx, s, box, rules, st, latest, statePath, nil, nil); err != nil {
+ if err := alertTick(ctx, s, box, rules, st, latest, statePath, nil, nil, nil); err != nil {
t.Fatal(err)
}
if _, _, err := under.Get(ctx, "fleets/pi/"+metrics.AlertKey(box)); err != nil {
@@ -222,7 +222,7 @@ func TestAlertTickPersistsPublishesAndPosts(t *testing.T) {
return nil
}
- if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil, nil); err != nil {
t.Fatal(err)
}
@@ -248,7 +248,7 @@ func TestAlertTickPersistsPublishesAndPosts(t *testing.T) {
}
// Second, identical tick: already firing, no new transition -> no post.
- if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil, nil); err != nil {
t.Fatal(err)
}
if len(posts) != 1 {
@@ -274,7 +274,7 @@ func TestAlertTickWebhookFailureDoesNotBlock(t *testing.T) {
}
post := func(url string, body []byte) error { return errors.New("webhook unreachable") }
- if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil, nil); err != nil {
t.Fatalf("alertTick must not fail on a webhook error: %v", err)
}
if _, err := os.Stat(statePath); err != nil {
@@ -316,7 +316,7 @@ func TestAlertTickPersistFailureDoesNotSuppressPublish(t *testing.T) {
return nil
}
- if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil, nil); err != nil {
t.Fatalf("alertTick must not fail just because the local state write failed: %v", err)
}
if !posted {
@@ -550,7 +550,7 @@ func TestAlertTickRetriesTransitionAfterPublishFailure(t *testing.T) {
}
failStore := &failingPutStore{Store: release.NewDirStore(t.TempDir())}
- if err := alertTick(ctx, failStore, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil); err == nil {
+ if err := alertTick(ctx, failStore, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil, nil); err == nil {
t.Fatal("expected alertTick to return the publish error against a Put-always-fails store")
}
if st.Rules["disk"].Firing {
@@ -563,7 +563,7 @@ func TestAlertTickRetriesTransitionAfterPublishFailure(t *testing.T) {
// Retry with the SAME observation against a working store: the pending
// transition must reproduce, publish, and post again.
workingStore := release.NewDirStore(t.TempDir())
- if err := alertTick(ctx, workingStore, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil); err != nil {
+ if err := alertTick(ctx, workingStore, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil, nil); err != nil {
t.Fatalf("retry against a working store: %v", err)
}
if !st.Rules["disk"].Firing {
@@ -963,7 +963,7 @@ func (r *forecastRig) tick(used uint64) (fired, cleared bool) {
r.trend.add(metrics.DiskPoint{At: r.at, UsedBytes: used, TotalBytes: 100 * gib})
was := r.st.Rules["disk_eta"].Firing
latest := metrics.Sample{At: r.at}
- if err := alertTick(context.Background(), r.store, r.box, r.rules, r.st, latest, r.statePath, r.sinks, r.trend); err != nil {
+ if err := alertTick(context.Background(), r.store, r.box, r.rules, r.st, latest, r.statePath, r.sinks, r.trend, nil); err != nil {
r.t.Fatal(err)
}
now := r.st.Rules["disk_eta"].Firing
@@ -1006,7 +1006,7 @@ func TestAlertTickSinksIncidentOnly(t *testing.T) {
r.at = r.at.Add(time.Minute)
full := 0.95
latest := metrics.Sample{At: r.at, Host: metrics.HostSample{DiskFrac: &full}}
- if err := alertTick(context.Background(), r.store, r.box, r.rules, r.st, latest, r.statePath, r.sinks, r.trend); err != nil {
+ if err := alertTick(context.Background(), r.store, r.box, r.rules, r.st, latest, r.statePath, r.sinks, r.trend, nil); err != nil {
t.Fatal(err)
}
if len(posted) != 1 || posted[0].Rule != "disk" || !posted[0].Firing {
diff --git a/internal/metrics/alert.go b/internal/metrics/alert.go
index 47a1a03d9..9b2fdd302 100644
--- a/internal/metrics/alert.go
+++ b/internal/metrics/alert.go
@@ -107,6 +107,12 @@ type Observation struct {
// is treated the same: the rule's state is left alone.
DiskTrend *TrendVerdict
DiskETAHours float64
+ // EngineSilent is the engine_silent backstop on a console box (fleet
+ // alerts spec §8): true when the console's alert engine has gone
+ // silent, false on a fresh beat. nil when the rule is unarmed, or when
+ // the box cannot tell yet; the agent has already applied the 10 minute
+ // grace and staleness, so the rule has no sustain here.
+ EngineSilent *bool
}
// RuleState is one rule's sustain/hysteresis bookkeeping. Since and FiredAt
@@ -133,7 +139,7 @@ type AlertState struct {
V int `json:"v"` // 1
Box string `json:"box"`
UpdatedAt time.Time `json:"updated_at"`
- Rules map[string]RuleState `json:"rules"` // "disk","mem","cpu","lag","geoip","disk_eta"
+ Rules map[string]RuleState `json:"rules"` // "disk","mem","cpu","lag","geoip","disk_eta","engine_silent"
}
// Event is emitted on a firing or clearing transition — never on every
@@ -349,5 +355,20 @@ func Evaluate(r Rules, st AlertState, obs Observation) (AlertState, []Event) {
evalETA("disk_eta", obs.DiskTrend, obs.DiskETAHours, r.DiskETAHours, r.DiskETAHold)
+ // engine_silent fires on the first silent reading and clears on the
+ // first fresh one. Value is 1 firing, 0 clear. Like every rule, only a
+ // transition writes the key, so an unarmed box (nil every tick) never
+ // has one.
+ if obs.EngineSilent != nil {
+ if cur := out.Rules["engine_silent"]; cur.Firing != *obs.EngineSilent {
+ if *obs.EngineSilent {
+ out.Rules["engine_silent"] = RuleState{Firing: true, Since: obs.At, FiredAt: obs.At, Value: 1}
+ } else {
+ out.Rules["engine_silent"] = RuleState{Value: 0}
+ }
+ emit("engine_silent", *obs.EngineSilent, out.Rules["engine_silent"].Value)
+ }
+ }
+
return out, events
}
diff --git a/internal/metrics/alert_test.go b/internal/metrics/alert_test.go
index e29f4bb58..8d320bbde 100644
--- a/internal/metrics/alert_test.go
+++ b/internal/metrics/alert_test.go
@@ -390,3 +390,39 @@ func TestRulesFromEnvDiskETAHours(t *testing.T) {
}
}
}
+
+// engine_silent (fleet alerts spec §8, plan ruling R-1): the host has
+// already applied the grace and staleness, so Evaluate fires on the first
+// silent reading and clears on the first fresh one. nil is unarmed: the key
+// is never created and a firing state is left alone.
+func TestEvaluateEngineSilent(t *testing.T) {
+ r := DefaultRules()
+ st := AlertState{V: 1, Box: "b", Rules: map[string]RuleState{}}
+ at := time.Date(2026, 10, 31, 10, 0, 0, 0, time.UTC)
+ yes, no := true, false
+
+ st, ev := Evaluate(r, st, Observation{At: at})
+ if _, ok := st.Rules["engine_silent"]; ok || len(ev) != 0 {
+ t.Fatalf("unarmed created the key or emitted: %+v %v", st.Rules, ev)
+ }
+ st, ev = Evaluate(r, st, Observation{At: at, EngineSilent: &no})
+ if st.Rules["engine_silent"].Firing || len(ev) != 0 {
+ t.Fatalf("fresh while quiet: %+v %v", st.Rules, ev)
+ }
+ st, ev = Evaluate(r, st, Observation{At: at.Add(time.Minute), EngineSilent: &yes})
+ if len(ev) != 1 || ev[0] != (Event{Rule: "engine_silent", Firing: true, Value: 1, Box: "b"}) || !st.Rules["engine_silent"].Firing {
+ t.Fatalf("silent must fire at once: %v", ev)
+ }
+ st, ev = Evaluate(r, st, Observation{At: at.Add(2 * time.Minute), EngineSilent: &yes})
+ if len(ev) != 0 {
+ t.Fatalf("still silent emitted again: %v", ev)
+ }
+ st, ev = Evaluate(r, st, Observation{At: at.Add(3 * time.Minute)})
+ if len(ev) != 0 || !st.Rules["engine_silent"].Firing {
+ t.Fatalf("no reading must leave the fire alone: %v %+v", ev, st.Rules)
+ }
+ st, ev = Evaluate(r, st, Observation{At: at.Add(4 * time.Minute), EngineSilent: &no})
+ if len(ev) != 1 || ev[0] != (Event{Rule: "engine_silent", Firing: false, Value: 0, Box: "b"}) || st.Rules["engine_silent"].Firing {
+ t.Fatalf("fresh must clear at once: %v", ev)
+ }
+}
diff --git a/internal/status/snapshot.go b/internal/status/snapshot.go
index f5161dbd0..7e3e54eb4 100644
--- a/internal/status/snapshot.go
+++ b/internal/status/snapshot.go
@@ -773,11 +773,27 @@ type AlertDelivery struct {
SNSUnavailable bool `json:"sns_unavailable,omitempty"`
WebhookFailures int64 `json:"webhook_failures,omitempty"`
SNSFailures int64 `json:"sns_failures,omitempty"`
+ // EngineBeat is the engine_silent backstop on a console box (fleet
+ // alerts spec §8): "on" when the agent watches the engine's beat, "off"
+ // when CARLOS_ALERT_ENGINE_BEAT is set but the agent will not watch it,
+ // with EngineBeatWhy saying why (a root-run agent refuses, Paul
+ // 2026-10-31). Empty on a box where it is not configured.
+ EngineBeat string `json:"engine_beat,omitempty"`
+ EngineBeatWhy string `json:"engine_beat_why,omitempty"`
}
// Delivered is whether at least one sink is configured.
func (a AlertDelivery) Delivered() bool { return a.Webhook || a.SNS }
+// NotDelivered is whether a box that answered has no sink at all: nothing
+// configured, and no topic whose client merely failed to build (that is
+// unavailable, a different problem). A nil answer is a box that did not
+// say, never "not delivered". The live listing and the console read this
+// one test.
+func (a *AlertDelivery) NotDelivered() bool {
+ return a != nil && !a.Webhook && !a.SNS && !a.SNSUnavailable
+}
+
// RouteCounts is aggregate-only: no host, no socket path, just how many.
// Awake/Asleep stay null together whenever the socket table can't be read in
// full — partial knowledge published as a count would read as more certain
diff --git a/internal/status/snapshot_test.go b/internal/status/snapshot_test.go
index a6eb78bff..366850db7 100644
--- a/internal/status/snapshot_test.go
+++ b/internal/status/snapshot_test.go
@@ -178,6 +178,44 @@ func TestBoxMetricsCarryAlertDelivery(t *testing.T) {
}
}
+// TestAlertDeliveryNotDelivered: NotDelivered is the live listing's
+// "not-delivered" test, so the console and the CLI read one answer. A box
+// that did not say (nil) is not "not delivered"; a configured topic whose
+// client failed is unavailable, not absent.
+func TestAlertDeliveryNotDelivered(t *testing.T) {
+ cases := []struct {
+ name string
+ a *AlertDelivery
+ want bool
+ }{
+ {"did not say", nil, false},
+ {"nothing configured", &AlertDelivery{}, true},
+ {"failures but no sink", &AlertDelivery{WebhookFailures: 3}, true},
+ {"webhook", &AlertDelivery{Webhook: true}, false},
+ {"sns", &AlertDelivery{SNS: true}, false},
+ {"sns unavailable", &AlertDelivery{SNSUnavailable: true}, false},
+ {"engine beat alone is not a sink", &AlertDelivery{EngineBeat: "on"}, true},
+ }
+ for _, c := range cases {
+ if got := c.a.NotDelivered(); got != c.want {
+ t.Errorf("%s: NotDelivered() = %v, want %v", c.name, got, c.want)
+ }
+ }
+}
+
+// The engine-beat answer rides the private alerts block and is absent on a
+// box where the backstop is not configured.
+func TestAlertDeliveryCarriesEngineBeat(t *testing.T) {
+ out, _ := json.Marshal(AlertDelivery{EngineBeat: "off", EngineBeatWhy: "agent runs as root"})
+ if !strings.Contains(string(out), `"engine_beat":"off","engine_beat_why":"agent runs as root"`) {
+ t.Errorf("json lacks the engine beat: %s", out)
+ }
+ out, _ = json.Marshal(AlertDelivery{})
+ if strings.Contains(string(out), "engine_beat") {
+ t.Errorf("an unconfigured box carries an engine beat key: %s", out)
+ }
+}
+
func TestCollectBoxCarriesGeoIP(t *testing.T) {
box := CollectBox(nil, Probes{GeoIP: &GeoIPState{Mode: "mirror", SHA256: "abc", Type: "DBIP-City-Lite"}}, time.Now())
if box.Metrics == nil || box.Metrics.GeoIP == nil || box.Metrics.GeoIP.SHA256 != "abc" {
diff --git a/statuslive_test.go b/statuslive_test.go
index d76d22a5e..62304685c 100644
--- a/statuslive_test.go
+++ b/statuslive_test.go
@@ -114,6 +114,8 @@ func TestPrintLiveBoxesSaysWhetherAlertsAreDelivered(t *testing.T) {
{GeneratedAt: now, Label: "d-old", Metrics: &status.BoxMetrics{Tunnel: "connected"}},
{GeneratedAt: now, Label: "e-unavail", Metrics: &status.BoxMetrics{Alerts: &status.AlertDelivery{SNSUnavailable: true, SNSFailures: 1}}},
{GeneratedAt: now, Label: "f-hook-unavail", Metrics: &status.BoxMetrics{Alerts: &status.AlertDelivery{Webhook: true, SNSUnavailable: true}}},
+ {GeneratedAt: now, Label: "g-beat-root", Metrics: &status.BoxMetrics{Alerts: &status.AlertDelivery{SNS: true, EngineBeat: "off", EngineBeatWhy: "agent runs as root"}}},
+ {GeneratedAt: now, Label: "h-beat-on", Metrics: &status.BoxMetrics{Alerts: &status.AlertDelivery{Webhook: true, EngineBeat: "on"}}},
}, now)
want := map[string]string{
"a-none": "alerts=not-delivered",
@@ -122,6 +124,10 @@ func TestPrintLiveBoxesSaysWhetherAlertsAreDelivered(t *testing.T) {
"d-old": "alerts=-",
"e-unavail": "alerts=sns-unavailable (sns failed 1)",
"f-hook-unavail": "alerts=webhook (sns-unavailable)",
+ // The engine-silent backstop (fleet alerts spec §8) beside it, only
+ // on a box where it is configured; b-sns above shows none.
+ "g-beat-root": "alerts=sns engine-beat=off (agent runs as root)\n",
+ "h-beat-on": "alerts=webhook engine-beat=on\n",
}
lines := strings.Split(strings.TrimRight(buf.String(), "\n"), "\n")
if len(lines) != len(want) {