Skip to main content

agentmux_srv_core/backend/
audit_live.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Tells the open Audit panes that a row was written (docs/specs/SPEC_AUDIT_LIVE_LOG_OF_EVERY_AGENT_ACTION_2026_11_03.md ยง3.1).
5//!
6//! The two writer threads ([`reactive::audit_store`](super::reactive::audit_store) and
7//! [`audit_activity`](super::audit_activity)) call [`poke`] after each line they append. A pane that sees
8//! `audit:changed` asks `audit.query` for the newest rows, so a row it is told about and a row it lists are the
9//! same row, with the same id. A tool-heavy agent writes ten rows a second, so the pokes of one window
10//! ([`WINDOW`]) become one event.
11
12use std::sync::mpsc::{channel, Receiver, Sender};
13use std::sync::{Arc, OnceLock};
14use std::time::Duration;
15
16use super::mps::Broker;
17
18/// The pokes of this long are one event.
19pub const WINDOW: Duration = Duration::from_millis(100);
20
21static POKE: OnceLock<Sender<()>> = OnceLock::new();
22
23/// Start publishing `audit:changed` on `broker` for the rest of this process. The first call wins.
24pub fn install_broker(broker: Arc<Broker>) {
25    let publish = move || broker.publish_event::<super::mps_events::AuditChanged>(&(), vec![], 0);
26    if let Ok(tx) = spawn(publish, WINDOW) {
27        let _ = POKE.set(tx);
28    }
29}
30
31/// A row was written. Nothing happens before [`install_broker`].
32pub fn poke() {
33    if let Some(tx) = POKE.get() {
34        let _ = tx.send(());
35    }
36}
37
38/// The thread that turns the pokes of each `window` into one call of `publish`. It ends when the sender is dropped.
39fn spawn(publish: impl Fn() + Send + 'static, window: Duration) -> std::io::Result<Sender<()>> {
40    let (tx, rx) = channel::<()>();
41    std::thread::Builder::new().name("audit-live".into()).spawn(move || run(&rx, window, publish))?;
42    Ok(tx)
43}
44
45fn run(rx: &Receiver<()>, window: Duration, publish: impl Fn()) {
46    while rx.recv().is_ok() {
47        // The rest of the window's pokes are this event.
48        std::thread::sleep(window);
49        while rx.try_recv().is_ok() {}
50        publish();
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57    use std::sync::atomic::{AtomicUsize, Ordering};
58
59    #[test]
60    fn a_burst_of_pokes_is_one_event_and_a_later_poke_is_another() {
61        let events = Arc::new(AtomicUsize::new(0));
62        let seen = Arc::clone(&events);
63        let tx = spawn(move || { seen.fetch_add(1, Ordering::SeqCst); }, Duration::from_millis(40)).unwrap();
64
65        // Wait for the event the thread owes, however late a loaded machine runs it (a fixed sleep missed it on a
66        // busy macOS runner), then give a second one time to show up wrongly: the count must stay as it is.
67        let settles_at = |n: usize| {
68            let deadline = std::time::Instant::now() + Duration::from_secs(10);
69            while events.load(Ordering::SeqCst) < n {
70                assert!(std::time::Instant::now() < deadline, "no event number {n}");
71                std::thread::sleep(Duration::from_millis(10));
72            }
73            std::thread::sleep(Duration::from_millis(200));
74            events.load(Ordering::SeqCst)
75        };
76
77        for _ in 0..25 {
78            tx.send(()).unwrap();
79        }
80        assert_eq!(settles_at(1), 1, "the burst is one event");
81
82        tx.send(()).unwrap();
83        assert_eq!(settles_at(2), 2, "a later poke is another");
84    }
85
86    #[test]
87    fn a_poke_before_the_broker_is_attached_does_nothing() {
88        poke();
89    }
90}