Skip to main content

agentmux_srv_core/backend/audit_activity/
store.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The day files: `activity-YYYY-MM-DD.jsonl` in the audit folder, appended by a writer thread (the recording is
5//! queued, so the transcript's hot path does no I/O here), and dropped when older than [`KEEP_DAYS`].
6
7use std::io::Write;
8use std::path::{Path, PathBuf};
9use std::sync::mpsc::{channel, Sender};
10use std::sync::OnceLock;
11
12use super::{ActivityRow, KEEP_DAYS};
13
14static SINK: OnceLock<Sender<ActivityRow>> = OnceLock::new();
15
16const PREFIX: &str = "activity-";
17const SUFFIX: &str = ".jsonl";
18
19/// A day's file and the day it holds (`YYYY-MM-DD`, UTC).
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct DayFile {
22    pub day: String,
23    pub path: PathBuf,
24}
25
26/// The UTC day (`YYYY-MM-DD`) of `ms`.
27pub(super) fn day_of(ms: u64) -> String {
28    chrono::DateTime::from_timestamp_millis(ms as i64).unwrap_or_default().format("%Y-%m-%d").to_string()
29}
30
31/// The day files in `dir`, newest day first. A file that is not named for a day is not listed.
32pub fn day_files(dir: &Path) -> Vec<DayFile> {
33    let Ok(read) = std::fs::read_dir(dir) else { return Vec::new() };
34    let mut files: Vec<DayFile> = read
35        .filter_map(Result::ok)
36        .filter_map(|e| {
37            let name = e.file_name().into_string().ok()?;
38            let day = name.strip_prefix(PREFIX)?.strip_suffix(SUFFIX)?.to_string();
39            chrono::NaiveDate::parse_from_str(&day, "%Y-%m-%d").ok()?;
40            Some(DayFile { day, path: e.path() })
41        })
42        .collect();
43    files.sort_by(|a, b| b.day.cmp(&a.day));
44    files
45}
46
47fn file_in(dir: &Path, day: &str) -> PathBuf {
48    dir.join(format!("{PREFIX}{day}{SUFFIX}"))
49}
50
51/// Deletes the day files in `dir` older than [`KEEP_DAYS`] days before `today`. Returns how many went.
52pub(super) fn prune(dir: &Path, today: &str) -> usize {
53    let Ok(today) = chrono::NaiveDate::parse_from_str(today, "%Y-%m-%d") else { return 0 };
54    let mut gone = 0;
55    for file in day_files(dir) {
56        let Ok(day) = chrono::NaiveDate::parse_from_str(&file.day, "%Y-%m-%d") else { continue };
57        if (today - day).num_days() > KEEP_DAYS as i64 && std::fs::remove_file(&file.path).is_ok() {
58            gone += 1;
59        }
60    }
61    gone
62}
63
64/// Starts the writer for the rest of this process: rows go to `dir`, stamped with `channel`. The first call wins.
65pub fn install(dir: PathBuf, channel_name: String) -> std::io::Result<()> {
66    let (tx, _writer) = spawn_writer(dir, channel_name)?;
67    let _ = SINK.set(tx);
68    Ok(())
69}
70
71/// The writer thread for `dir`: it ends when the sender is dropped.
72pub(super) fn spawn_writer(dir: PathBuf, channel_name: String) -> std::io::Result<(Sender<ActivityRow>, std::thread::JoinHandle<()>)> {
73    std::fs::create_dir_all(&dir)?;
74    let (tx, rx) = channel::<ActivityRow>();
75    let writer = std::thread::Builder::new().name("audit-activity-writer".into()).spawn(move || {
76        let mut open: Option<(String, std::fs::File)> = None;
77        for mut row in rx {
78            // The row's own day, so a day's file holds only that day and files never overlap in time.
79            let day = day_of(row.ts);
80            if open.as_ref().is_none_or(|(d, _)| *d != day) {
81                let path = file_in(&dir, &day);
82                match std::fs::OpenOptions::new().create(true).append(true).open(&path) {
83                    Ok(file) => open = Some((day.clone(), file)),
84                    Err(e) => {
85                        tracing::warn!(path = %path.display(), error = %e, "audit activity: could not open the day file");
86                        continue;
87                    }
88                }
89                prune(&dir, &day_of(agentmux_common::time::now_ms_u64()));
90            }
91            row.channel = Some(channel_name.clone());
92            let Ok(mut line) = serde_json::to_vec(&row) else { continue };
93            line.push(b'\n');
94            if let Some((_, file)) = open.as_mut() {
95                // One write call per line, so lines from several srvs don't interleave.
96                match file.write_all(&line).and_then(|_| file.flush()) {
97                    Ok(()) => crate::backend::audit_live::poke(),
98                    Err(e) => tracing::warn!(error = %e, "audit activity: could not append a row"),
99                }
100            }
101        }
102    })?;
103    Ok((tx, writer))
104}
105
106/// Queues `row` for its day file. Nothing happens before [`install`].
107pub fn record(row: ActivityRow) {
108    if let Some(tx) = SINK.get() {
109        let _ = tx.send(row);
110    }
111}
112
113/// Starts recording where the jekt audit goes: the shared audit folder, or this srv's own while it does not use it.
114pub fn install_for_this_srv() {
115    let Some(dir) = crate::backend::reactive::audit_store::write_path().and_then(|p| p.parent().map(Path::to_path_buf)) else { return };
116    let channel_name = std::env::var("AGENTMUX_INSTANCE_CHANNEL").unwrap_or_default();
117    if let Err(e) = install(dir.clone(), channel_name) {
118        tracing::warn!(dir = %dir.display(), error = %e, "audit activity: not kept");
119    }
120}