Skip to main content

agentmux_srv/server/app_api/
audit_query.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `audit.query` (`backend::audit_query`): a page of the Audit view's list. The window's, not an agent API: the
5//! Audit is the operator's view of every agent, so a connection registered as an agent is refused.
6//!
7//! On the `machine` scope's first page it also asks the other channels on this computer for the rows they keep in
8//! their own file (`handle_audit_own`, the route they answer on), so a channel that stays out of the shared folder is
9//! still listed.
10
11use super::*;
12use crate::backend::audit_query::{self, Ctx, Sources};
13use crate::backend::rpc_types::{AuditChannelRows, AuditQueryReq, AuditQueryResult};
14use std::path::Path;
15
16/// A page from this srv's stores. `own_only` reads only what this srv keeps in its own files, and leaves out the
17/// shared audit file, the shared activity folder and the shared segment ledger: what another channel cannot read.
18pub(in crate::server) fn query_here(state: &AppState, req: &AuditQueryReq, own_only: bool) -> Result<AuditQueryResult, String> {
19    let slugs = state.mstore.shared_def_registry().and_then(|reg| reg.slug_index().ok());
20    let slug_of_uid = |uid: &str| slugs.as_ref().and_then(|s| s.get(uid)).map(|e| e.slug.clone());
21    let uid_of_slug = |slug: &str| {
22        let all = slugs.as_ref()?;
23        let by_slug = all.iter().find(|(_, e)| e.slug.eq_ignore_ascii_case(slug));
24        by_slug.or_else(|| all.iter().find(|(_, e)| e.former.iter().any(|f| f.eq_ignore_ascii_case(slug)))).map(|(uid, _)| uid.clone())
25    };
26    let pane_of_agent = |slug: &str| match state.reactive_handler.lookup_by_name(slug) {
27        crate::backend::reactive::handler::LookupOutcome::One(reg) => Some(reg.block_id).filter(|b| !b.is_empty()),
28        _ => None,
29    };
30    let block_exists = |id: &str| state.mstore.get::<crate::backend::obj::Block>(id).ok().flatten().is_some();
31    let file = crate::backend::reactive::audit_store::shared_path_for_reading().filter(|_| !own_only);
32    let own = crate::backend::reactive::audit_store::own_path();
33    let channel = std::env::var("AGENTMUX_INSTANCE_CHANNEL").unwrap_or_default();
34    let src = Sources {
35        channel: &channel,
36        jekt_file: file.as_deref(),
37        own_file: own.as_deref(),
38        activity_dir: file.as_deref().and_then(Path::parent),
39        own_activity_dir: own.as_deref().and_then(Path::parent),
40        segments: state.global_transcript_store.as_deref().filter(|_| !own_only),
41        ctx: Ctx { slug_of_uid: &slug_of_uid, uid_of_slug: &uid_of_slug, pane_of_agent: &pane_of_agent, block_exists: &block_exists },
42    };
43    let mut result = audit_query::query(&src, req)?;
44    // The task each row's agent held at the time, and its PR: from the Kanban's history.
45    let held = audit_query::tasks::from_store(&state.work_store);
46    audit_query::tasks::attach(&mut result.entries, &held);
47    Ok(result)
48}
49
50/// Whether a request is the first page of a scope that lists more than this channel, the only page that asks the
51/// other channels (and, for `lan`, the paired computers).
52fn asks_beyond_this_channel(req: &AuditQueryReq) -> bool {
53    req.cursor.is_none() && matches!(req.scope.as_deref().map(str::trim), None | Some("") | Some("machine") | Some("lan"))
54}
55
56/// A page of this computer's Audit as the window lists it: this channel's stores, and on the first page of a scope
57/// that lists more, the rows the other channels on this computer keep in their own files.
58pub(in crate::server) async fn machine_page(state: &AppState, req: &AuditQueryReq) -> Result<AuditQueryResult, String> {
59    let here = {
60        let (state, req) = (state.clone(), req.clone());
61        // Reads files, the whole segment ledger and the registry: off the async workers.
62        tokio::task::spawn_blocking(move || query_here(&state, &req, false)).await.map_err(|e| format!("audit.query: {e}"))?
63    };
64    let mut result = here?;
65    if asks_beyond_this_channel(req) {
66        result.other_channels = Some(other_channels(state, req).await).filter(|rows| !rows.is_empty());
67    }
68    Ok(result)
69}
70
71/// The other channels that are running, asked for their own rows.
72async fn other_channels(state: &AppState, req: &AuditQueryReq) -> Vec<AuditChannelRows> {
73    let entries = tokio::task::spawn_blocking(|| {
74        crate::registry::resolve_shared_reactive_dir().map(|dir| crate::backend::reactive::registry::list_all_shared(&dir)).unwrap_or_default()
75    })
76    .await
77    .unwrap_or_default();
78    let own_channel = crate::backend::reactive::registry::local_channel_id();
79    let now_ms = agentmux_common::time::now_ms_u64();
80    let targets = crate::backend::swarm_remote::channel_status_targets(&entries, &own_channel, &state.local_web_url, now_ms);
81    audit_query::other_channels::ask(&state.http_client, &targets, req).await
82}
83
84pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
85    let state = state.clone();
86    engine.register_typed(COMMAND_AUDIT_QUERY, move |req: AuditQueryReq, ctx| {
87        let state = state.clone();
88        async move {
89            ctx.operator_only("the Audit is the AgentMux window's, not an agent API")?;
90            let mut result = machine_page(&state, &req).await?;
91            // The paired computers are asked on the `lan` scope's first page, and shown and forgotten.
92            if req.cursor.is_none() && req.scope.as_deref().map(str::trim) == Some("lan") {
93                result.peers = Some(crate::server::remote_ops::audit_ops::ask_peers(&state, &req).await).filter(|rows| !rows.is_empty());
94            }
95            Ok(result)
96        }
97    });
98}
99
100/// `POST /agentmux/audit/own`: what this channel keeps in its own file, as an `audit.query` page, for another channel
101/// on this computer that is listing every channel. Full key only, never LAN; an agent's token is refused, as the
102/// Audit is not an agent API.
103pub(in crate::server) async fn handle_audit_own(
104    axum::extract::State(state): axum::extract::State<AppState>,
105    caller: Option<axum::Extension<crate::server::caller::Caller>>,
106    axum::Json(req): axum::Json<AuditQueryReq>,
107) -> axum::response::Response {
108    use axum::response::IntoResponse;
109    if caller.is_some_and(|c| c.0.uid().is_some()) {
110        return (axum::http::StatusCode::FORBIDDEN, "the Audit is the AgentMux window's, not an agent API").into_response();
111    }
112    match tokio::task::spawn_blocking(move || query_here(&state, &req, true)).await {
113        Ok(Ok(result)) => axum::Json(result).into_response(),
114        Ok(Err(e)) => (axum::http::StatusCode::BAD_REQUEST, e).into_response(),
115        Err(e) => (axum::http::StatusCode::INTERNAL_SERVER_ERROR, format!("audit own: {e}")).into_response(),
116    }
117}