Skip to main content

agentmux_srv_core/backend/reactive/
audit_store.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The durable copy of the jekt audit trail. The handler keeps the last
5//! [`AUDIT_LOG_MAX`](super::AUDIT_LOG_MAX) entries in memory for
6//! `GET /agentmux/reactive/audit`, and loses them at every restart. Every entry
7//! is also appended here, as one JSON line, to a file that is never rotated or
8//! truncated: AgentMux keeps agent history, and the record of what agents did,
9//! forever.
10//!
11//! Entries hold a hash and the length of each message, never its text, plus the
12//! sender, target, outcome and a caller's free-text note. The file is shared by
13//! every srv instance on the machine, so each line names its channel.
14//!
15//! The handler records while holding its lock, so recording does no I/O: it
16//! queues the line for a writer thread.
17
18use std::io::Write;
19use std::path::{Path, PathBuf};
20use std::sync::mpsc::{channel, Sender};
21use std::sync::OnceLock;
22use std::thread::JoinHandle;
23
24use super::types::AuditLogEntry;
25
26static SINK: OnceLock<Sender<AuditLogEntry>> = OnceLock::new();
27
28/// `<shared root>/audit/jekt-audit.jsonl`, or `None` while this srv has given the shared folder up.
29pub fn default_path() -> Option<PathBuf> {
30    crate::registry::resolve_global_shared_root().map(|root| root.join("audit").join("jekt-audit.jsonl"))
31}
32
33/// The shared file to read, whether or not this srv may write to it: a srv that gave the folder up
34/// still lists what the account's other srvs recorded.
35pub fn shared_path_for_reading() -> Option<PathBuf> {
36    crate::registry::shared_root_ignoring_deferral().map(|root| root.join("audit").join("jekt-audit.jsonl"))
37}
38
39/// `<this channel's folder>/audit/jekt-audit.jsonl`: where a srv that gave the shared folder up keeps its own
40/// rows. A line goes to exactly one of this and the shared file. It is the channel's own folder, not the
41/// per-version data folder (`--wavedata`, `AGENTMUX_DATA_DIR`): a srv that deferred is usually upgraded next, and
42/// the new version must still find the rows the old one kept.
43pub fn own_path() -> Option<PathBuf> {
44    std::env::var_os("AGENTMUX_INSTANCE_DIR").filter(|d| !d.is_empty()).map(|d| PathBuf::from(d).join("audit").join("jekt-audit.jsonl"))
45}
46
47/// Where this srv appends: the shared file, or its own when it doesn't use the shared folder.
48pub fn write_path() -> Option<PathBuf> {
49    default_path().or_else(own_path)
50}
51
52/// Start recording where this srv writes ([`write_path`]), and say so in the log when that is its own file.
53pub fn install_for_this_srv() {
54    match write_path() {
55        Some(path) => {
56            if default_path().is_none() {
57                tracing::info!(path = %path.display(), "jekt audit: the shared folder is not used; this srv keeps its rows in its own file");
58            }
59            let channel_name = std::env::var("AGENTMUX_INSTANCE_CHANNEL").unwrap_or_default();
60            if let Err(e) = install(path.clone(), channel_name) {
61                tracing::warn!(path = %path.display(), error = %e, "jekt audit: not kept in a file");
62            }
63        }
64        None => tracing::warn!("jekt audit: no shared directory and no channel directory; not kept in a file"),
65    }
66    // The index of what agents do goes beside it.
67    crate::backend::audit_activity::install_for_this_srv();
68}
69
70/// Start recording to `path` for the rest of this process. The first call wins.
71pub fn install(path: PathBuf, channel_name: String) -> std::io::Result<()> {
72    let (tx, _writer) = spawn_writer(path, channel_name)?;
73    let _ = SINK.set(tx);
74    Ok(())
75}
76
77/// Queue `entry` for the audit file. Nothing happens before [`install`].
78pub fn record(entry: &AuditLogEntry) {
79    if let Some(tx) = SINK.get() {
80        let _ = tx.send(entry.clone());
81    }
82}
83
84/// Add `entry` to the in-memory `ring` that serves `GET /agentmux/reactive/audit`
85/// (the last `max` entries), and queue it for the audit file, which keeps every one.
86pub(super) fn push(ring: &mut Vec<AuditLogEntry>, max: usize, entry: AuditLogEntry) {
87    record(&entry);
88    if ring.len() >= max {
89        ring.remove(0);
90    }
91    ring.push(entry);
92}
93
94/// Open `path` for appending and start the thread that writes what is sent.
95/// The thread ends when the sender is dropped.
96pub(super) fn spawn_writer(
97    path: PathBuf,
98    channel_name: String,
99) -> std::io::Result<(Sender<AuditLogEntry>, JoinHandle<()>)> {
100    if let Some(dir) = path.parent() {
101        std::fs::create_dir_all(dir)?;
102    }
103    let mut file = std::fs::OpenOptions::new().create(true).append(true).open(&path)?;
104    let (tx, rx) = channel::<AuditLogEntry>();
105    let writer = std::thread::Builder::new().name("jekt-audit-writer".into()).spawn(move || {
106        for entry in rx {
107            if let Err(e) = write_line(&mut file, &channel_name, &entry) {
108                tracing::warn!(path = %path.display(), error = %e, "jekt audit: could not append an entry");
109                continue;
110            }
111            crate::backend::audit_live::poke();
112        }
113    })?;
114    Ok((tx, writer))
115}
116
117fn write_line(file: &mut std::fs::File, channel_name: &str, entry: &AuditLogEntry) -> std::io::Result<()> {
118    let mut line = serde_json::to_vec(&stamped(entry, channel_name)).map_err(std::io::Error::other)?;
119    line.push(b'\n');
120    // One write call per line, so lines from several instances don't interleave.
121    file.write_all(&line)?;
122    file.flush()
123}
124
125/// `entry` with where it is written from: this computer, the channel and the srv's version. Whatever the entry said
126/// of them is replaced: a row is written by the srv that recorded it.
127fn stamped(entry: &AuditLogEntry, channel_name: &str) -> AuditLogEntry {
128    static HOST: OnceLock<String> = OnceLock::new();
129    AuditLogEntry {
130        host: Some(HOST.get_or_init(super::registry::local_host_label).clone()),
131        channel: Some(channel_name.to_string()),
132        version: Some(env!("CARGO_PKG_VERSION").to_string()),
133        ..entry.clone()
134    }
135}
136
137/// The entries in the file at `path`, oldest first; lines that don't parse are skipped.
138#[allow(dead_code)] // used by the tests; no production reader yet
139pub fn read_all(path: &Path) -> Vec<AuditLogEntry> {
140    let Ok(text) = std::fs::read_to_string(path) else { return Vec::new() };
141    text.lines().filter_map(|l| serde_json::from_str(l).ok()).collect()
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    fn entry(target: &str, n: usize) -> AuditLogEntry {
149        AuditLogEntry {
150            timestamp: 1_000 + n as u64,
151            source_agent: Some("Korp".into()),
152            target_agent: target.into(),
153            block_id: "b1".into(),
154            message_hash: format!("{n:016x}"),
155            message_length: n,
156            success: true,
157            error_message: None,
158            request_id: format!("r{n}"),
159            outcome: None,
160            reason: None,
161            event_kind: "delivery".into(),
162            evicted_block: None,
163            evicted_agent: None,
164            audit_source_uid: String::new(),
165            lan_claimed_uid: String::new(),
166            wan: None,
167            cli_native: None,
168            turn: None,
169            host: None,
170            channel: None,
171            version: None,
172            tier: None,
173            trust: None,
174            msg_id: None,
175            prompt: None,
176            answer: None,
177            level: None,
178            standing: None,
179        }
180    }
181
182    #[test]
183    fn a_srv_without_the_shared_folder_keeps_its_rows_in_its_channel_folder_not_the_per_version_data_folder() {
184        let _g = crate::test_support::ISOLATED_AUTH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
185        let dir = tempfile::tempdir().unwrap();
186        let saved = (std::env::var_os("AGENTMUX_INSTANCE_DIR"), std::env::var_os("AGENTMUX_DATA_DIR"));
187        // The data folder is `<channel folder>/versions/<version>/data`: the next version does not see it.
188        std::env::set_var("AGENTMUX_INSTANCE_DIR", dir.path());
189        std::env::set_var("AGENTMUX_DATA_DIR", dir.path().join("versions").join("1.2.3").join("data"));
190        let own = own_path();
191        for (name, value) in [("AGENTMUX_INSTANCE_DIR", saved.0), ("AGENTMUX_DATA_DIR", saved.1)] {
192            match value {
193                Some(v) => std::env::set_var(name, v),
194                None => std::env::remove_var(name),
195            }
196        }
197        assert_eq!(own, Some(dir.path().join("audit").join("jekt-audit.jsonl")));
198    }
199
200    #[test]
201    fn every_entry_is_appended_with_its_channel_and_survives_a_restart() {
202        let dir = tempfile::tempdir().unwrap();
203        let path = dir.path().join("audit").join("jekt-audit.jsonl");
204
205        // More than the in-memory ring keeps.
206        let (tx, writer) = spawn_writer(path.clone(), "dev-a".into()).unwrap();
207        for n in 0..250 {
208            tx.send(entry("Lark", n)).unwrap();
209        }
210        drop(tx);
211        writer.join().unwrap();
212
213        // A second process appends to the same file.
214        let (tx, writer) = spawn_writer(path.clone(), "dev-b".into()).unwrap();
215        tx.send(entry("Lark", 250)).unwrap();
216        drop(tx);
217        writer.join().unwrap();
218
219        let entries = read_all(&path);
220        assert_eq!(entries.len(), 251, "nothing is dropped, and nothing is truncated on reopen");
221        assert_eq!(entries[0].message_length, 0);
222        assert_eq!(entries[250].message_length, 250);
223        let text = std::fs::read_to_string(&path).unwrap();
224        assert!(text.lines().next().unwrap().contains("\"channel\":\"dev-a\""));
225        assert!(text.lines().last().unwrap().contains("\"channel\":\"dev-b\""));
226        assert!(!text.contains("hello"), "message text is never written");
227    }
228
229    #[test]
230    fn a_line_that_does_not_parse_is_skipped_not_fatal() {
231        let dir = tempfile::tempdir().unwrap();
232        let path = dir.path().join("jekt-audit.jsonl");
233        let (tx, writer) = spawn_writer(path.clone(), "c".into()).unwrap();
234        tx.send(entry("Lark", 1)).unwrap();
235        drop(tx);
236        writer.join().unwrap();
237        std::fs::OpenOptions::new().append(true).open(&path).unwrap().write_all(b"{torn\n").unwrap();
238        assert_eq!(read_all(&path).len(), 1);
239    }
240}