Skip to main content

agentmux_srv_core/backend/
record_notice.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What is said of a flag of the record's rules
5//! (docs/specs/SPEC_LONG_RUNNING_ZERO_DEGRADATION_2026_11_16.md ยง7, task #47820): a quiet note in the status bar,
6//! and a note for the machine's steward agent. Nothing is stopped and the person is not interrupted.
7//!
8//! - The status bar follows the `record-flags` event: the flags still said (`record_flags::still_said`), shaped
9//!   like the host's `health-signal` payloads (`kind` is `record`; a `normal` level clears it). It is persisted,
10//!   so a window that opens later gets it. It is published when the rules look (once an hour), while there is
11//!   something to say and once more when there no longer is.
12//! - Each steward running here (an agent whose seat says so, `agent_seat::is_steward`) gets one held note for
13//!   the flags a look wrote: it waits for the agent's next turn and starts none, and a later one replaces one
14//!   not read yet. With no steward here nobody is told; the flags are in the record all the same.
15//!
16//! The decisions are pure ([`event`], [`note_text`]), so they are tested without a broker or an agent.
17
18use std::sync::atomic::{AtomicBool, Ordering};
19
20use serde_json::Value;
21
22use super::record_flags::{Flag, Looked};
23
24/// The key of the held note: a later note replaces an earlier one that its agent has not read yet.
25pub const NOTE_KEY: &str = "record-flags";
26
27/// One flag that is still said, as the record holds it: its rule, what it is about and its numbers.
28#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, ts_rs::TS)]
29#[ts(export, export_to = "../../../frontend/types/rpc/")]
30pub struct RecordFlagLine {
31    /// `stalls`, `long_stall` or `growth`.
32    pub rule: String,
33    /// What it is about: `ui_stall` or `srv_stall`, or a series (`core`, `core:srv`, `page:<window>:heap`,
34    /// `page:<window>:dom`).
35    pub key: String,
36    /// The end of the hour it was found in (ms since the epoch).
37    #[ts(type = "number")]
38    pub t: u64,
39    /// `stalls`: how many of 5 s or more in the hour.
40    #[ts(type = "number | null")]
41    pub n: Option<u64>,
42    /// `stalls`, `long_stall`: the longest, in ms.
43    #[ts(type = "number | null")]
44    pub worst_ms: Option<u64>,
45    /// `growth`: what `level` and `rise` count: `bytes`, `mb` or `elements`.
46    pub unit: Option<String>,
47    /// `growth`: the size's level over the last day.
48    #[ts(type = "number | null")]
49    pub level: Option<u64>,
50    /// `growth`: what its trend gained in the last day.
51    #[ts(type = "number | null")]
52    pub rise: Option<u64>,
53}
54
55/// The `record-flags` event's payload (`mps_events::RecordFlags`), shaped like the host's `health-signal`
56/// payloads so the status bar's store takes it: `kind` is `record`, and a `normal` level clears the signal.
57#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, ts_rs::TS)]
58#[ts(export, export_to = "../../../frontend/types/rpc/")]
59pub struct RecordFlagsEvent {
60    /// Always `record`.
61    #[ts(type = "\"record\"")]
62    pub kind: String,
63    /// `warn` while a flag is said, else `normal`. A flag is never critical: it is a note, not an alarm.
64    #[ts(type = "\"normal\" | \"warn\"")]
65    pub level: String,
66    /// The time of the oldest flag still said; absent while normal.
67    #[ts(type = "number | null")]
68    pub since_ms: Option<u64>,
69    /// The flags still said, oldest first.
70    pub flags: Vec<RecordFlagLine>,
71}
72
73fn line(e: &Value) -> Option<RecordFlagLine> {
74    let n = |field: &str| e[field].as_u64();
75    Some(RecordFlagLine {
76        rule: e["rule"].as_str()?.to_string(),
77        key: e["key"].as_str()?.to_string(),
78        t: n("t")?,
79        n: n("n"),
80        worst_ms: n("worst_ms"),
81        unit: e["unit"].as_str().map(str::to_string),
82        level: n("level"),
83        rise: n("rise"),
84    })
85}
86
87/// The event for the flags still said (`Looked::said`).
88pub fn event(said: &[Value]) -> RecordFlagsEvent {
89    let flags: Vec<RecordFlagLine> = said.iter().filter_map(line).collect();
90    RecordFlagsEvent {
91        kind: "record".to_string(),
92        level: if flags.is_empty() { "normal" } else { "warn" }.to_string(),
93        since_ms: flags.iter().map(|f| f.t).min(),
94        flags,
95    }
96}
97
98/// What a flag is about, in a few words, for the steward's note.
99fn about(flag: &Flag) -> String {
100    let stalled = if flag.key == "ui_stall" { "the window host's UI thread" } else { "srv's runtime" };
101    let n = |field: &str| flag.fields[field].as_u64().unwrap_or(0);
102    match flag.rule {
103        "stalls" => format!("{stalled} stalled {} times for 5 s or more in one hour (the longest {} s)", n("n"), n("worst_ms") / 1000),
104        "long_stall" => format!("{stalled} stalled for {} s", n("worst_ms") / 1000),
105        "growth" => format!("{} has grown two days running, by more than a fifth of its size each day", flag.key),
106        other => format!("{other}: {}", flag.key),
107    }
108}
109
110/// What the stewards are told about the flags a look wrote; nothing when it wrote none.
111pub fn note_text(new: &[Flag]) -> Option<String> {
112    if new.is_empty() {
113        return None;
114    }
115    let what: Vec<String> = new.iter().map(about).collect();
116    Some(format!(
117        "[AgentMux] The record of this AgentMux flagged {}: {}. \
118         Nothing was stopped and the person was not interrupted; the status bar shows a note. \
119         `App record` (view \"summary\") has the numbers and the days behind them. \
120         If it is real, file it for the seat that owns it, with the export of those days.",
121        if new.len() == 1 { "one thing".to_string() } else { format!("{} things", new.len()) },
122        what.join("; ")
123    ))
124}
125
126/// The stewards running here, as a note is addressed to them (uid, else id), each once.
127fn steward_targets(mstore: &crate::backend::storage::store::Store) -> Vec<String> {
128    let defs = mstore.agent_def_list().unwrap_or_default();
129    let mut out: Vec<String> = Vec::new();
130    for rec in crate::backend::reactive::get_global_handler().list_agents() {
131        let def = defs.iter().find(|d| rec.uid.as_deref() == Some(d.id.as_str()) || d.slug == rec.agent_id || d.id == rec.agent_id);
132        if !def.and_then(|d| crate::backend::agent_seat::effective_seat(mstore, d)).is_some_and(|seat| crate::backend::agent_seat::is_steward(&seat)) {
133            continue;
134        }
135        let target = rec.uid.clone().filter(|u| !u.is_empty()).unwrap_or(rec.agent_id.clone());
136        if !out.contains(&target) {
137            out.push(target);
138        }
139    }
140    out
141}
142
143/// Whether the last event published said anything: one more is published when it no longer does.
144static SAID: AtomicBool = AtomicBool::new(false);
145
146/// Say what a look found: the event for the status bar, then the note for the stewards. BLOCKING (the note takes
147/// the message handler's lock); call it where the look ran, off the async workers. The event goes first, so a
148/// handler that cannot be reached costs the note and not the status bar.
149pub fn tell(broker: &crate::backend::mps::Broker, mstore: &crate::backend::storage::store::Store, looked: &Looked) {
150    let event = event(&looked.said);
151    let says = !event.flags.is_empty();
152    let said_before = SAID.swap(says, Ordering::Relaxed);
153    if says || said_before {
154        broker.publish_event::<crate::backend::mps_events::RecordFlags>(&event, vec![], 1);
155    }
156    let Some(text) = note_text(&looked.new) else { return };
157    let handler = crate::backend::reactive::get_global_handler();
158    let targets = steward_targets(mstore);
159    if targets.is_empty() {
160        tracing::info!("[record] flags were written and no steward is here to be told");
161    }
162    for target in targets {
163        match handler.hold_system_note(&target, NOTE_KEY, &text) {
164            Ok(()) => tracing::info!(agent = %target, "[record] the steward has a note about the flags"),
165            Err(e) => tracing::debug!(agent = %target, error = %e, "[record] the steward was not told"),
166        }
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173    use serde_json::json;
174
175    /// 2026-11-16 12:00 UTC.
176    const END: u64 = 1_794_830_400_000;
177
178    #[test]
179    fn the_event_carries_each_flag_still_said_with_its_numbers_and_is_normal_with_none() {
180        let said = vec![
181            json!({ "t": END - 3_600_000, "kind": "flag", "rule": "growth", "key": "page:main:heap", "unit": "mb", "level": 306, "rise": 72, "rise_before": 70, "content_pct": 2 }),
182            json!({ "t": END, "kind": "flag", "rule": "stalls", "key": "srv_stall", "n": 4, "worst_ms": 6_200 }),
183            // A line that is not a whole flag is left out.
184            json!({ "t": END, "kind": "flag", "rule": "growth" }),
185        ];
186        let e = event(&said);
187        assert_eq!((e.kind.as_str(), e.level.as_str(), e.since_ms), ("record", "warn", Some(END - 3_600_000)));
188        assert_eq!(e.flags.len(), 2);
189        assert_eq!(
190            e.flags[0],
191            RecordFlagLine { rule: "growth".into(), key: "page:main:heap".into(), t: END - 3_600_000, n: None, worst_ms: None, unit: Some("mb".into()), level: Some(306), rise: Some(72) }
192        );
193        assert_eq!((e.flags[1].rule.as_str(), e.flags[1].n, e.flags[1].worst_ms), ("stalls", Some(4), Some(6_200)));
194
195        let none = event(&[]);
196        assert_eq!((none.level.as_str(), none.since_ms, none.flags.len()), ("normal", None, 0));
197        // As the page reads it: the shape of a health signal.
198        let wire = serde_json::to_value(&e).unwrap();
199        assert_eq!(wire["kind"], "record");
200        assert_eq!(wire["flags"][1]["worst_ms"], 6_200);
201    }
202
203    #[test]
204    fn the_steward_is_told_once_for_what_a_look_wrote_and_nothing_for_a_look_that_wrote_nothing() {
205        assert_eq!(note_text(&[]), None);
206        let one = note_text(&[Flag { rule: "long_stall", key: "ui_stall".into(), fields: json!({ "n": 1, "worst_ms": 41_000 }) }]).unwrap();
207        assert!(one.starts_with("[AgentMux] The record of this AgentMux flagged one thing: the window host's UI thread stalled for 41 s."), "{one}");
208        let two = note_text(&[
209            Flag { rule: "stalls", key: "srv_stall".into(), fields: json!({ "n": 4, "worst_ms": 6_200 }) },
210            Flag { rule: "growth", key: "core:srv".into(), fields: json!({ "unit": "bytes", "level": 300, "rise": 90 }) },
211        ])
212        .unwrap();
213        assert!(two.contains("flagged 2 things: srv's runtime stalled 4 times for 5 s or more in one hour (the longest 6 s); core:srv has grown two days running"), "{two}");
214        assert!(two.contains("`App record`"));
215        assert!(two.contains("Nothing was stopped"));
216    }
217}