Skip to main content

agentmux_srv_core/backend/audit_query/
activity.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The activity rows (`tool`, `turn`, `thought`) of one audit folder's day files, newest first.
5//!
6//! A day's file holds only that day's rows (`audit_activity` names a row's file by its own time), so the files do not
7//! overlap in time: the stream reads the newest day to its start, then the day before, and so on. A page's cursor
8//! says which day and byte to carry on from.
9
10use std::path::Path;
11
12use super::ordered::Ordered;
13use super::{jekt_file, Ctx, Filter};
14use crate::backend::audit_activity::{day_files, ActivityRow, DayFile};
15use crate::backend::rpc_types::{AuditEntry, AuditHistoryLink, AuditLinks, AuditPaneLink, AuditProvenance};
16
17/// The start of the day after `day`, in Unix ms: a file whose day ended before the window started holds nothing of it.
18pub(super) fn day_end_ms(day: &str) -> u64 {
19    chrono::NaiveDate::parse_from_str(day, "%Y-%m-%d")
20        .ok()
21        .and_then(|d| d.succ_opt())
22        .and_then(|d| d.and_hms_opt(0, 0, 0))
23        .map_or(u64::MAX, |t| t.and_utc().timestamp_millis().max(0) as u64)
24}
25
26/// The Audit's entry for `row`, which is the line starting at byte `at` of the file for `day` in the folder tagged `tag`.
27pub(super) fn entry_of(tag: char, day: &str, at: u64, row: &ActivityRow, ctx: &Ctx) -> AuditEntry {
28    let slug = (ctx.slug_of_uid)(&row.agent).unwrap_or_else(|| row.agent.clone());
29    AuditEntry {
30        id: format!("a{tag}{day}:{at:016x}"),
31        ts_ms: row.ts,
32        kind: row.kind.clone(),
33        agent_id: Some(slug.clone()),
34        from: None,
35        to: None,
36        summary: row.summary.clone(),
37        outcome: row.outcome.clone(),
38        reason: None,
39        cost: row.cost.clone(),
40        links: AuditLinks {
41            history: Some(AuditHistoryLink {
42                agent_id: slug,
43                definition_id: Some(row.agent.clone()),
44                zone: Some(row.zone.clone()).filter(|_| row.byte.is_some()),
45                at_ms: row.ts,
46                at_byte: row.byte,
47            }),
48            pane: Some(row.block.as_str()).filter(|b| !b.is_empty() && (ctx.block_exists)(b)).map(|b| AuditPaneLink { block_id: b.to_string() }),
49            task: None,
50        },
51        // Where the row was written, which a channel scope and the Audit's sections read.
52        provenance: row.channel.as_ref().map(|c| AuditProvenance { channel: Some(c.clone()), ..Default::default() }),
53        prompt: None,
54        answer: None,
55        level: None,
56        standing: None,
57    }
58}
59
60/// One folder's activity entries that pass the filter, newest first.
61pub(super) struct DayStream<'a> {
62    tag: char,
63    ctx: &'a Ctx<'a>,
64    filter: &'a Filter,
65    after: Option<(u64, String)>,
66    /// The days still to open, newest first.
67    pending: std::vec::IntoIter<DayFile>,
68    /// The day being read, and where its lines may end when it was opened.
69    current: Option<(String, Option<u64>, Ordered<'a, ActivityRow>)>,
70    /// The day and byte a page before stopped at: older days than it are not read again.
71    resume_from: Option<(String, u64)>,
72}
73
74impl<'a> DayStream<'a> {
75    /// `dir`: the folder (None: no activity here). `resume` is `YYYY-MM-DD:<byte>` from the cursor of the page before.
76    pub fn new(dir: Option<&Path>, tag: char, filter: &'a Filter, ctx: &'a Ctx<'a>, after: Option<(u64, String)>, resume: Option<&str>) -> Self {
77        let resume_from = resume.and_then(|r| r.split_once(':')).and_then(|(day, byte)| Some((day.to_string(), byte.parse().ok()?)));
78        let days = dir
79            .map(day_files)
80            .unwrap_or_default()
81            .into_iter()
82            // A day newer than where the page before stopped was read already; one that ended before the window began holds none of it.
83            .filter(|f| resume_from.as_ref().is_none_or(|(day, _)| f.day <= *day))
84            .filter(|f| day_end_ms(&f.day) >= filter.since)
85            .collect::<Vec<_>>();
86        Self { tag, ctx, filter, after, pending: days.into_iter(), current: None, resume_from }
87    }
88
89    /// Opens days until the current one has an entry to give, or none are left.
90    fn fill(&mut self) {
91        loop {
92            if let Some((_, _, stream)) = self.current.as_mut() {
93                if stream.peek().is_some() {
94                    return;
95                }
96            }
97            let Some(file) = self.pending.next() else {
98                return;
99            };
100            let end = self.resume_from.as_ref().filter(|(day, _)| *day == file.day).map(|(_, byte)| *byte);
101            let (tag, ctx, filter, day) = (self.tag, self.ctx, self.filter, file.day.clone());
102            let lines = jekt_file::entries::<ActivityRow>(&file.path, end);
103            let stream = Ordered::new(lines, |row: &ActivityRow| row.ts, move |at, row| entry_of(tag, &day, at, row, ctx), move |e| filter.keep(e), filter.since, self.after.clone());
104            self.current = Some((file.day, end, stream));
105        }
106    }
107
108    pub fn peek(&mut self) -> Option<&AuditEntry> {
109        self.fill();
110        self.current.as_mut().and_then(|(_, _, s)| s.peek())
111    }
112
113    pub fn pop(&mut self) -> Option<AuditEntry> {
114        self.fill();
115        self.current.as_mut().and_then(|(_, _, s)| s.pop())
116    }
117
118    /// Where the next page carries on from, as `YYYY-MM-DD:<byte>`: the day being read and where in it. The days
119    /// before it are opened in turn. None when no day was opened.
120    pub fn resume(&self, previous: Option<&str>) -> Option<String> {
121        match self.current.as_ref() {
122            Some((day, opened_at, stream)) => Some(format!("{day}:{}", stream.resume(*opened_at)?)),
123            None => previous.map(str::to_string),
124        }
125    }
126}