agentmux_srv_core/backend/audit_query/
segments.rs1use super::{Ctx, KIND_AGENT_END, KIND_AGENT_START};
8use crate::backend::continuity_segments::{self as ledger, EndReason, Segment};
9use crate::backend::rpc_types::{AuditEntry, AuditHistoryLink, AuditLinks, AuditPaneLink};
10use crate::backend::storage::filestore::FileStore;
11
12fn agent_uids(store: &FileStore) -> Vec<String> {
14 store
15 .zone_ids_with_prefix("agent-uid:")
16 .unwrap_or_default()
17 .into_iter()
18 .filter_map(|zone| zone.strip_prefix("agent-uid:")?.strip_suffix(":segments").map(str::to_string))
19 .collect()
20}
21
22fn reason_word(reason: EndReason) -> String {
23 serde_json::to_value(reason).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default()
24}
25
26fn archived_at(store: &FileStore, current: &str) -> Vec<u64> {
29 let Some(prefix) = current.strip_suffix(":current").map(|p| format!("{p}:archive:")) else { return Vec::new() };
30 let mut times: Vec<u64> = store
31 .zone_ids_with_prefix(&prefix)
32 .unwrap_or_default()
33 .iter()
34 .filter_map(|z| z.strip_prefix(&prefix)?.parse().ok())
35 .collect();
36 times.sort_unstable();
37 times
38}
39
40fn zone_at(current: &str, archives: &[u64], at_ms: i64) -> String {
42 let prefix = current.strip_suffix(":current").map(|p| format!("{p}:archive:"));
43 match (archives.iter().find(|a| **a as i64 >= at_ms), prefix) {
44 (Some(ms), Some(prefix)) => format!("{prefix}{ms}"),
45 _ => current.to_string(),
46 }
47}
48
49fn entries_of(slug: &str, segment: &Segment, archives: &[u64], ctx: &Ctx) -> Vec<AuditEntry> {
52 let start = &segment.start;
53 let link = |at_ms: i64, byte: Option<i64>| AuditLinks {
54 history: Some(AuditHistoryLink {
55 agent_id: slug.to_string(),
56 definition_id: start.definition_id.clone(),
57 zone: start.zone.as_deref().filter(|_| byte.is_some()).map(|z| zone_at(z, archives, at_ms)),
58 at_ms: at_ms.max(0) as u64,
59 at_byte: byte.map(|b| b.max(0) as u64),
60 }),
61 pane: Some(start.block_id.as_str()).filter(|b| !b.is_empty() && (ctx.block_exists)(b)).map(|b| AuditPaneLink { block_id: b.to_string() }),
62 task: None,
63 };
64 let how = match start.continuity_rung {
65 ledger::Rung::Native => "resumed its session",
66 ledger::Rung::Virtualized => "started a new session with its record",
67 ledger::Rung::Fresh => "started a new session",
68 };
69 let mut out = vec![AuditEntry {
70 id: format!("s:{}:start", start.segment_id),
71 ts_ms: start.started_at_ms.max(0) as u64,
72 kind: KIND_AGENT_START.to_string(),
73 agent_id: Some(slug.to_string()),
74 from: None,
75 to: None,
76 summary: format!("{slug} {how} ({})", start.provider),
77 outcome: None,
78 reason: None,
79 cost: None,
80 links: link(start.started_at_ms, start.byte_start),
81 provenance: None,
82 prompt: None,
83 answer: None,
84 level: None,
85 standing: None,
86 }];
87 if let (Some(at), Some(why)) = (segment.ended_at_ms, segment.end_reason) {
88 let word = reason_word(why);
89 out.push(AuditEntry {
90 id: format!("s:{}:end", start.segment_id),
91 ts_ms: at.max(0) as u64,
92 kind: KIND_AGENT_END.to_string(),
93 agent_id: Some(slug.to_string()),
94 from: None,
95 to: None,
96 summary: format!("{slug} stopped ({word})"),
97 outcome: None,
98 reason: Some(word),
99 cost: None,
100 links: link(at, segment.byte_end),
101 provenance: None,
102 prompt: None,
103 answer: None,
104 level: None,
105 standing: None,
106 });
107 }
108 out
109}
110
111pub(super) fn entries(store: &FileStore, only: Option<&str>, ctx: &Ctx) -> Vec<AuditEntry> {
113 let mut out = Vec::new();
114 for uid in agent_uids(store) {
115 let slug = (ctx.slug_of_uid)(&uid).unwrap_or_else(|| uid.clone());
116 if let Some(want) = only {
117 if !super::same_agent(&slug, want) {
118 continue;
119 }
120 }
121 let mut archives: std::collections::HashMap<String, Vec<u64>> = std::collections::HashMap::new();
122 for segment in ledger::segments(store, &uid) {
123 let times = match segment.start.zone.as_deref() {
124 Some(zone) => archives.entry(zone.to_string()).or_insert_with(|| archived_at(store, zone)).clone(),
125 None => Vec::new(),
126 };
127 out.extend(entries_of(&slug, &segment, ×, ctx));
128 }
129 }
130 out
131}