Skip to main content

agentmux_srv/server/remote_ops/
audit_ops.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `audit.query`: a paired computer reads this computer's Audit, and this computer reads theirs
5//! (SPEC_AUDIT_LIVE_LOG_OF_EVERY_AGENT_ACTION_2026_11_03.md ยง3.6 point 5). A read, answered only when the owner turned
6//! on `audit:sharewithpaired` (off unless set, like `tower:sharewithpaired`), and only to a peer whose install this
7//! computer has approved: the rows name agents and what they did. The answer is the first page of the `machine`
8//! scope, the same rows the window lists, with no message text, and without the links that only work here (a pane, a
9//! history, a Kanban task). The asking computer shows the rows and forgets them: nothing is stored, and the cloud never
10//! carries them.
11
12use std::collections::HashSet;
13use std::sync::{LazyLock, Mutex};
14use std::time::{Duration, Instant};
15
16use serde_json::Value;
17
18use super::op::{OpStatus, RemoteOpResult};
19use super::{AppState, RemoteCaller, RemoteRefusal, RemoteResult};
20use crate::backend::audit_query::peers::{self, QUERY_OP, SETTING_AUDIT_SHARE};
21use crate::backend::lan::discovery::LanInstance;
22use crate::backend::rpc_types::{AuditPeerRows, AuditQueryReq, AuditQueryResult};
23
24/// How long the Audit waits for one computer: it is a list on screen, and the others should not wait on a slow one.
25const ASK_FOR: Duration = Duration::from_secs(4);
26const REASON: &str = "list its Audit";
27/// How long the last answer of the paired computers is reused. The Audit asks again every ten seconds and on every
28/// row written here, and a computer need not be asked more often than this.
29const REUSE_FOR: Duration = Duration::from_secs(5);
30
31/// What the paired computers last said, for which request, and when.
32type LastAsked = Option<(String, Instant, Vec<AuditPeerRows>)>;
33static LAST_ASKED: LazyLock<Mutex<LastAsked>> = LazyLock::new(Default::default);
34
35fn shares(state: &AppState) -> bool {
36    state.config_watcher.get_settings().extra.get(SETTING_AUDIT_SHARE).and_then(Value::as_bool).unwrap_or(false)
37}
38
39/// The receiving half: this computer's page, when it shares.
40pub(super) async fn query(state: &AppState, _caller: &RemoteCaller, params: Value) -> RemoteResult {
41    if !shares(state) {
42        return Err(RemoteRefusal::new("not_shared", format!("this computer does not share its Audit with paired computers ({SETTING_AUDIT_SHARE})")));
43    }
44    let asked: AuditQueryReq = serde_json::from_value(params).map_err(|e| RemoteRefusal::failed(format!("audit.query: {e}")))?;
45    let req = peers::request_for_peer(&asked);
46    let mut page = crate::server::app_api::audit_query::machine_page(state, &req).await.map_err(RemoteRefusal::failed)?;
47    peers::without_local_links(&mut page.entries);
48    for channel in page.other_channels.iter_mut().flatten() {
49        peers::without_local_links(&mut channel.entries);
50    }
51    serde_json::to_value(&page).map_err(|e| RemoteRefusal::failed(format!("audit.query: {e}")))
52}
53
54/// The machines to ask, as `(name, host)`: `name` for the section, `host` as `send` takes it. One per computer, the
55/// first instance announced, named as `send::resolve_peer` takes it: `name`, or `name/channel`, or
56/// `name/channel/install` when the computer runs several, so the name picks exactly one. That instance answers for the
57/// computer's other channels too, which it asks over loopback.
58fn lan_hosts(instances: &[LanInstance]) -> Vec<(String, String)> {
59    let mut seen = HashSet::new();
60    let mut out = Vec::new();
61    for p in instances {
62        let name = p.hostname.trim();
63        if name.is_empty() || !seen.insert(name.to_ascii_lowercase()) {
64            continue;
65        }
66        let same_name: Vec<&LanInstance> = instances.iter().filter(|q| q.hostname.trim().eq_ignore_ascii_case(name)).collect();
67        let same_channel = same_name.iter().filter(|q| q.channel.eq_ignore_ascii_case(&p.channel)).count();
68        let host = match (same_name.len(), same_channel) {
69            (1, _) => name.to_string(),
70            (_, 1) => format!("{name}/{}", p.channel),
71            _ => format!("{name}/{}/{}", p.channel, p.install),
72        };
73        out.push((name.to_string(), host));
74    }
75    out
76}
77
78/// A computer's answer as its section: the rows, or why there are none.
79fn rows_from(name: &str, answer: RemoteOpResult) -> AuditPeerRows {
80    if answer.status != OpStatus::Done {
81        let error = answer.result.get("error").and_then(Value::as_str);
82        return peers::no_rows(name, &peers::note_for(answer.refused_reason.as_deref(), error));
83    }
84    match serde_json::from_value::<AuditQueryResult>(answer.result) {
85        Ok(page) => peers::rows_of(name, page),
86        Err(e) => peers::no_rows(name, &format!("its answer was not understood: {e}")),
87    }
88}
89
90/// The asking half: every paired computer on the LAN, concurrently, signed as one of this computer's agents. Empty
91/// while remote operations are off or no agent is running to sign with.
92pub(crate) async fn ask_peers(state: &AppState, req: &AuditQueryReq) -> Vec<AuditPeerRows> {
93    if !super::enabled(state) {
94        return Vec::new();
95    }
96    let Some(slug) = super::fleet_sync::signer(state) else { return Vec::new() };
97    let params = serde_json::to_value(peers::request_for_peer(req)).unwrap_or(Value::Null);
98    let hosts = lan_hosts(&state.lan_discovery.get_instances());
99    // What was asked, of whom and by whom: a newly paired computer, or another signer, is not answered from the last one.
100    let key = format!("{params}|{slug}|{}", hosts.iter().map(|(_, host)| host.as_str()).collect::<Vec<_>>().join(","));
101    if let Some((asked, at, rows)) = LAST_ASKED.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
102        if *asked == key && at.elapsed() < REUSE_FOR {
103            return rows.clone();
104        }
105    }
106    let rows = futures_util::future::join_all(hosts.into_iter().map(|(name, host)| {
107        let (slug, params) = (slug.clone(), params.clone());
108        async move {
109            match tokio::time::timeout(ASK_FOR, super::send::call(state, &slug, &host, QUERY_OP, params, REASON)).await {
110                Ok(answer) => rows_from(&name, answer),
111                Err(_) => peers::no_rows(&name, "it did not answer in time"),
112            }
113        }
114    }))
115    .await;
116    *LAST_ASKED.lock().unwrap_or_else(|e| e.into_inner()) = Some((key, Instant::now(), rows.clone()));
117    rows
118}
119
120#[cfg(test)]
121#[path = "audit_ops_tests.rs"]
122mod tests;