Skip to main content

agentmux_srv_core/backend/audit_query/
provenance.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Where a jekt row came from and how it travelled (SPEC_AUDIT_LIVE_LOG_OF_EVERY_AGENT_ACTION ยง3.6), and the join of a
5//! message's two halves: the sender's `sent` line and the receiver's line, which carry one `msg_id`.
6
7use std::collections::HashMap;
8
9use crate::backend::reactive::sent_audit::SENT;
10use crate::backend::reactive::types::AuditLogEntry;
11use crate::backend::rpc_types::{AuditEntry, AuditProvenance};
12
13use super::KIND_JEKT;
14
15/// The provenance of a line, or none for a line that says nothing of it and proves nothing. A line from before the
16/// fields existed still has its tier where the line itself proves it: a WAN verdict is the cloud, a LAN-claimed UID is
17/// the LAN. That is marked `tier_inferred`; any other old line has no tier.
18pub(super) fn of(e: &AuditLogEntry) -> Option<AuditProvenance> {
19    let (tier, inferred) = match e.tier.as_deref() {
20        Some(t) => (Some(named(t)), false),
21        None if e.wan.is_some() => (Some("cloud".to_string()), true),
22        None if !e.lan_claimed_uid.is_empty() => (Some("lan".to_string()), true),
23        None => (None, false),
24    };
25    let provenance = AuditProvenance {
26        host: e.host.clone(),
27        channel: e.channel.clone(),
28        version: e.version.clone(),
29        tier,
30        tier_inferred: inferred.then_some(true),
31        trust: e.trust.clone(),
32        msg_id: e.msg_id.clone(),
33        sent_ms: None,
34        sent_only: (e.event_kind == SENT).then_some(true),
35    };
36    (provenance != AuditProvenance::default()).then_some(provenance)
37}
38
39/// A tier as the Audit names it: the handler's `wan` is the cloud.
40fn named(tier: &str) -> String {
41    if tier == "wan" { "cloud" } else { tier }.to_string()
42}
43
44/// The message id of a jekt entry, if it has one.
45fn msg_id(e: &AuditEntry) -> Option<&str> {
46    e.provenance.as_ref().and_then(|p| p.msg_id.as_deref()).filter(|_| e.kind == KIND_JEKT)
47}
48
49fn is_sent_only(e: &AuditEntry) -> bool {
50    e.provenance.as_ref().is_some_and(|p| p.sent_only == Some(true))
51}
52
53fn is_joined(e: &AuditEntry) -> bool {
54    e.provenance.as_ref().is_some_and(|p| p.sent_ms.is_some())
55}
56
57/// The rows of a page and where each message id was first seen in it, so the halves of one message come out as one row.
58#[derive(Default)]
59pub(super) struct Joiner {
60    seen: HashMap<String, usize>,
61}
62
63impl Joiner {
64    /// Whether `next` is the sender's half of a message the page already holds the other half of: it goes in the page
65    /// even when the page is full, so a page boundary does not split a message.
66    pub(super) fn completes(&self, next: &AuditEntry) -> bool {
67        is_sent_only(next) && msg_id(next).is_some_and(|id| self.seen.contains_key(id))
68    }
69
70    /// Adds `entry` to `entries`, joined into the row of the same message when one of the two is the sender's `sent`
71    /// line and the other is not yet joined. The joined row is the receiver's, with the time the sender handed the
72    /// message over; a `sent` line alone stays a row of its own, marked as such. Rows of one message that are both the
73    /// receiver's (a hold and its delivery) stay separate rows, and the `sent` line joins the newest.
74    pub(super) fn push(&mut self, entries: &mut Vec<AuditEntry>, entry: AuditEntry) {
75        let Some(id) = msg_id(&entry).map(str::to_string) else {
76            entries.push(entry);
77            return;
78        };
79        let Some(&at) = self.seen.get(&id) else {
80            self.seen.insert(id, entries.len());
81            entries.push(entry);
82            return;
83        };
84        if is_sent_only(&entry) == is_sent_only(&entries[at]) || is_joined(&entries[at]) {
85            entries.push(entry);
86            return;
87        }
88        let (mut receiver, sent_ms) = if is_sent_only(&entry) { (entries[at].clone(), entry.ts_ms) } else { (entry, entries[at].ts_ms) };
89        if let Some(p) = receiver.provenance.as_mut() {
90            p.sent_ms = Some(sent_ms);
91        }
92        entries[at] = receiver;
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99    use crate::backend::rpc_types::AuditLinks;
100
101    fn row(id: &str, ts: u64, msg: Option<&str>, sent: bool) -> AuditEntry {
102        AuditEntry {
103            id: id.into(),
104            ts_ms: ts,
105            kind: KIND_JEKT.into(),
106            agent_id: None,
107            from: None,
108            to: None,
109            summary: String::new(),
110            outcome: None,
111            reason: None,
112            cost: None,
113            links: AuditLinks::default(),
114            provenance: msg.map(|m| AuditProvenance { msg_id: Some(m.into()), sent_only: sent.then_some(true), ..Default::default() }),
115            prompt: None,
116            answer: None,
117            level: None,
118            standing: None,
119        }
120    }
121
122    fn page(rows: Vec<AuditEntry>) -> Vec<AuditEntry> {
123        let (mut joiner, mut out) = (Joiner::default(), Vec::new());
124        for r in rows {
125            joiner.push(&mut out, r);
126        }
127        out
128    }
129
130    #[test]
131    fn the_two_halves_of_a_message_are_one_row_whichever_comes_first() {
132        // Newest first: the receiver's line then the sender's, or (a peer's clock ahead) the other way round.
133        for rows in [vec![row("d", 20, Some("m"), false), row("s", 10, Some("m"), true)], vec![row("s", 30, Some("m"), true), row("d", 20, Some("m"), false)]] {
134            let sent_at = rows.iter().find(|r| r.id == "s").unwrap().ts_ms;
135            let out = page(rows);
136            assert_eq!(out.len(), 1);
137            assert_eq!((out[0].id.as_str(), out[0].provenance.as_ref().unwrap().sent_ms), ("d", Some(sent_at)));
138            assert!(out[0].provenance.as_ref().unwrap().sent_only.is_none());
139        }
140    }
141
142    #[test]
143    fn a_sent_line_with_no_other_end_stays_its_own_row_and_other_messages_are_not_touched() {
144        let out = page(vec![row("a", 40, Some("x"), true), row("b", 30, Some("y"), false), row("c", 20, None, false)]);
145        assert_eq!(out.len(), 3);
146        assert_eq!(out[0].provenance.as_ref().unwrap().sent_only, Some(true));
147        assert!(out.iter().all(|e| e.provenance.as_ref().is_none_or(|p| p.sent_ms.is_none())));
148    }
149
150    #[test]
151    fn a_hold_and_its_delivery_stay_two_rows_and_the_sent_line_joins_the_newest() {
152        let out = page(vec![row("delivered", 30, Some("m"), false), row("held", 20, Some("m"), false), row("sent", 10, Some("m"), true)]);
153        assert_eq!(out.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), vec!["delivered", "held"]);
154        assert_eq!(out[0].provenance.as_ref().unwrap().sent_ms, Some(10));
155        assert_eq!(out[1].provenance.as_ref().unwrap().sent_ms, None);
156    }
157
158    #[test]
159    fn a_sent_line_completes_a_page_that_holds_its_other_half() {
160        let (mut joiner, mut out) = (Joiner::default(), Vec::new());
161        joiner.push(&mut out, row("d", 20, Some("m"), false));
162        assert!(joiner.completes(&row("s", 10, Some("m"), true)));
163        assert!(!joiner.completes(&row("s2", 10, Some("other"), true)));
164        assert!(!joiner.completes(&row("d2", 10, Some("m"), false)));
165    }
166
167    #[test]
168    fn old_lines_get_a_tier_only_where_the_line_proves_it() {
169        let text = r#"{"timestamp":1,"target_agent":"a","block_id":"b","message_hash":"h","message_length":1,"success":true,"request_id":"r","channel":"dev"}"#;
170        let mut e: AuditLogEntry = serde_json::from_str(text).unwrap();
171        let p = of(&e).unwrap();
172        assert_eq!((p.channel.as_deref(), p.tier.as_deref(), p.tier_inferred), (Some("dev"), None, None));
173        e.lan_claimed_uid = "u".into();
174        let p = of(&e).unwrap();
175        assert_eq!((p.tier.as_deref(), p.tier_inferred), (Some("lan"), Some(true)));
176        e.tier = Some("wan".into());
177        let p = of(&e).unwrap();
178        assert_eq!((p.tier.as_deref(), p.tier_inferred), (Some("cloud"), None));
179    }
180}