Skip to main content

agentmux_srv_core/backend/reactive/
action_audit.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The audit line for a recorded RPC call (`backend::rpc::action_record`): kept
5//! like the jekt lines, in the ring behind `GET /agentmux/reactive/audit` and in
6//! the audit file. `event_kind` is `action`; `outcome` is the command;
7//! `source_agent` is the actor (`agent:<id>`, `operator` or `unproven`);
8//! `target_agent` and `block_id` are what it acted on; `reason` names the
9//! identifier it acted on; `success` and `error_message` say how it went.
10
11use super::handler::ReactiveHandler;
12use super::types::AuditLogEntry;
13use super::{audit_hash, now_unix_millis, AUDIT_LOG_MAX};
14use crate::backend::rpc::action_record::ActionRecord;
15
16fn entry(rec: &ActionRecord, target_agent: String) -> AuditLogEntry {
17    action_entry(
18        Some(rec.actor.label()),
19        target_agent,
20        rec.target.block_id.clone().unwrap_or_default(),
21        &rec.command,
22        rec.error.is_none(),
23        rec.error.clone(),
24        &rec.request_id,
25        rec.target.subject.clone(),
26    )
27}
28
29/// One action row: `outcome` is the command, `reason` what it acted on or the caller's note, and no message
30/// length, so the Audit view shows no byte count or token estimate for it.
31fn action_entry(
32    source_agent: Option<String>,
33    target_agent: String,
34    block_id: String,
35    command: &str,
36    success: bool,
37    error: Option<String>,
38    request_id: &str,
39    reason: Option<String>,
40) -> AuditLogEntry {
41    AuditLogEntry {
42        timestamp: now_unix_millis(),
43        source_agent,
44        target_agent,
45        block_id,
46        message_hash: audit_hash(command),
47        message_length: 0,
48        success,
49        error_message: error,
50        request_id: request_id.to_string(),
51        outcome: Some(command.to_string()),
52        reason,
53        event_kind: "action".to_string(),
54        evicted_block: None,
55        evicted_agent: None,
56        audit_source_uid: String::new(),
57        lan_claimed_uid: String::new(),
58        wan: None,
59        cli_native: None,
60        turn: None,
61        host: None,
62        channel: None,
63        version: None,
64        tier: None,
65        trust: None,
66        msg_id: None,
67        prompt: None,
68        answer: None,
69        level: None,
70        standing: None,
71    }
72}
73
74/// The most action entries the in-memory ring holds, so the rest stays for other events.
75const ACTIONS_IN_RING_MAX: usize = AUDIT_LOG_MAX / 2;
76
77impl ReactiveHandler {
78    /// Record one call. A call that names a pane is recorded against the agent
79    /// running in it. Runs on the reply path, so a poisoned lock is recovered rather than
80    /// allowed to stop the reply.
81    pub fn audit_action(&self, rec: &ActionRecord) {
82        let mut handler = self.inner.lock();
83        // A pane's own registration says whom it acts on; an agent field in the request is only a
84        // claim (a command may ignore it), so it is used when no pane is named or registered.
85        let target = rec
86            .target
87            .block_id
88            .as_deref()
89            .and_then(|b| handler.names_for_block(b).into_iter().next())
90            .or_else(|| rec.target.agent.clone())
91            .unwrap_or_default();
92        // Calls come in bursts; they may not push the deliveries and registrations out of the
93        // ring that `GET /agentmux/reactive/audit` serves. The audit file keeps every one.
94        let ring = &mut handler.audit_log;
95        if ring.iter().filter(|e| e.event_kind == "action").count() >= ACTIONS_IN_RING_MAX {
96            if let Some(oldest) = ring.iter().position(|e| e.event_kind == "action") {
97                ring.remove(oldest);
98            }
99        }
100        super::audit_store::push(ring, AUDIT_LOG_MAX, entry(rec, target));
101    }
102
103    /// Record a fleet action (an AWS credential grant, a seat change, a rename, a pane close) written by
104    /// [`ReactiveHandler::log_fleet_action_audit`]: an action row, like a recorded RPC call, with the caller's own
105    /// `source_agent` (a plain agent id, or `you` for the person) and the target it already resolved.
106    #[allow(clippy::too_many_arguments)]
107    pub(super) fn audit_fleet_action(
108        &self,
109        source_agent: Option<&str>,
110        target_agent: &str,
111        block_id: &str,
112        action: &str,
113        success: bool,
114        error_message: Option<&str>,
115        request_id: &str,
116        reason: Option<&str>,
117    ) {
118        let e = action_entry(
119            source_agent.map(str::to_string),
120            target_agent.to_string(),
121            block_id.to_string(),
122            action,
123            success,
124            error_message.map(str::to_string),
125            request_id,
126            reason.map(str::to_string),
127        );
128        let mut handler = self.inner.lock();
129        let ring = &mut handler.audit_log;
130        if ring.iter().filter(|e| e.event_kind == "action").count() >= ACTIONS_IN_RING_MAX {
131            if let Some(oldest) = ring.iter().position(|e| e.event_kind == "action") {
132                ring.remove(oldest);
133            }
134        }
135        super::audit_store::push(ring, AUDIT_LOG_MAX, e);
136    }
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142    use crate::backend::rpc::action_record::Target;
143    use crate::backend::rpc::actor::Actor;
144
145    fn rec(i: usize) -> ActionRecord {
146        ActionRecord { actor: Actor::Operator, command: format!("c{i}"), target: Target::default(), request_id: i.to_string(), error: None }
147    }
148
149    #[test]
150    fn a_burst_of_calls_does_not_push_the_other_events_out_of_the_ring() {
151        let handler = ReactiveHandler::new();
152        {
153            let mut inner = handler.inner.lock();
154            for i in 0..AUDIT_LOG_MAX {
155                let mut e = entry(&rec(i), String::new());
156                e.event_kind = "delivery".to_string();
157                super::super::audit_store::push(&mut inner.audit_log, AUDIT_LOG_MAX, e);
158            }
159        }
160        for i in 0..300 {
161            handler.audit_action(&rec(i));
162        }
163        let log = handler.get_audit_log(AUDIT_LOG_MAX);
164        let actions = log.iter().filter(|e| e.event_kind == "action").count();
165        assert_eq!(log.len(), AUDIT_LOG_MAX);
166        assert_eq!(actions, ACTIONS_IN_RING_MAX);
167        assert_eq!(log[0].outcome.as_deref(), Some("c299"), "the newest call is kept");
168    }
169
170    #[test]
171    fn a_fleet_action_is_one_action_row_with_the_callers_note_and_no_message_length() {
172        let handler = ReactiveHandler::new();
173        handler.log_fleet_action_audit(Some("korp"), "opaz", "blk-9", "agent.rename", true, None, "req-1", Some("renamed Pulse #2"));
174        handler.log_fleet_action_audit(Some("you"), "opaz", "blk-9", "agent.spend", false, Some("refused"), "req-2", None);
175        let log = handler.get_audit_log(2);
176        let (refused, done) = (&log[0], &log[1]);
177        assert!(log.iter().all(|e| e.event_kind == "action" && e.message_length == 0));
178        assert_eq!((done.source_agent.as_deref(), done.target_agent.as_str(), done.block_id.as_str()), (Some("korp"), "opaz", "blk-9"));
179        assert_eq!((done.outcome.as_deref(), done.reason.as_deref(), done.success, done.request_id.as_str()), (Some("agent.rename"), Some("renamed Pulse #2"), true, "req-1"));
180        assert_eq!((refused.success, refused.error_message.as_deref(), refused.source_agent.as_deref()), (false, Some("refused"), Some("you")));
181    }
182
183    #[test]
184    fn the_panes_registration_names_the_target_not_an_agent_field_in_the_request() {
185        let handler = ReactiveHandler::new();
186        handler.inner.lock().register_agent("victim", "blk-1", None).unwrap();
187        let mut r = rec(1);
188        r.target = Target { agent: Some("someone-else".into()), block_id: Some("blk-1".into()), subject: None };
189        handler.audit_action(&r);
190        let mut r = rec(2);
191        r.target = Target { agent: Some("named".into()), block_id: Some("unregistered".into()), subject: None };
192        handler.audit_action(&r);
193        let log = handler.get_audit_log(2);
194        assert_eq!(log[1].target_agent, "victim");
195        assert_eq!(log[0].target_agent, "named", "an unregistered pane falls back to the named agent");
196    }
197}