1pub mod activity;
14pub mod jekt_file;
15pub mod message_stats;
16pub mod ordered;
17pub mod other_channels;
18pub mod peers;
19pub mod provenance;
20pub mod segments;
21pub mod tasks;
22pub mod totals;
23
24use std::collections::HashSet;
25use std::path::Path;
26
27use crate::backend::reactive::types::AuditLogEntry;
28use crate::backend::rpc_types::{AuditCost, AuditEnd, AuditEntry, AuditHistoryLink, AuditLinks, AuditPaneLink, AuditQueryReq, AuditQueryResult};
29use crate::backend::storage::filestore::FileStore;
30
31pub const KIND_JEKT: &str = "jekt";
32pub const KIND_ACTION: &str = "action";
33pub const KIND_REGISTRY: &str = "registry";
34pub const KIND_AGENT_START: &str = "agent_start";
35pub const KIND_AGENT_END: &str = "agent_end";
36pub const KIND_TOOL: &str = "tool";
37pub const KIND_THOUGHT: &str = "thought";
38
39pub const KIND_TURN: &str = "turn";
40
41const DEFAULT_KINDS: [&str; 5] = [KIND_JEKT, KIND_ACTION, KIND_REGISTRY, KIND_AGENT_START, KIND_AGENT_END];
43const RECORDED: [&str; 8] = [KIND_JEKT, KIND_ACTION, KIND_REGISTRY, KIND_AGENT_START, KIND_AGENT_END, KIND_TOOL, KIND_TURN, KIND_THOUGHT];
45const NOT_RECORDED: [&str; 0] = [];
47const DEFAULT_LIMIT: usize = 50;
48const MAX_LIMIT: usize = 200;
49
50pub struct Ctx<'a> {
52 pub slug_of_uid: &'a dyn Fn(&str) -> Option<String>,
54 pub uid_of_slug: &'a dyn Fn(&str) -> Option<String>,
56 pub pane_of_agent: &'a dyn Fn(&str) -> Option<String>,
58 pub block_exists: &'a dyn Fn(&str) -> bool,
59}
60
61pub struct Sources<'a> {
63 pub channel: &'a str,
65 pub jekt_file: Option<&'a Path>,
67 pub own_file: Option<&'a Path>,
69 pub activity_dir: Option<&'a Path>,
71 pub own_activity_dir: Option<&'a Path>,
72 pub segments: Option<&'a FileStore>,
73 pub ctx: Ctx<'a>,
74}
75
76fn route(name: &str) -> String {
77 crate::backend::reactive::sanitize::route_name(name).unwrap_or_default().to_lowercase()
78}
79
80const FAILURE_NOTE_MAX: usize = 160;
82
83fn failure_note(e: &AuditLogEntry) -> String {
86 if e.success {
87 return String::new();
88 }
89 let line = e.error_message.as_deref().and_then(|m| m.lines().map(str::trim).find(|l| !l.is_empty())).unwrap_or("");
90 match line.chars().count() {
91 0 => " (failed)".to_string(),
92 n if n <= FAILURE_NOTE_MAX => format!(" (failed: {line})"),
93 _ => format!(" (failed: {}…)", line.chars().take(FAILURE_NOTE_MAX).collect::<String>().trim_end()),
94 }
95}
96
97pub(crate) fn same_agent(a: &str, b: &str) -> bool {
99 let (a, b) = (route(a), route(b));
100 !a.is_empty() && a == b
101}
102
103#[derive(Default, Clone)]
106struct Place {
107 last: Option<(u64, String)>,
108 resume: Option<String>,
109}
110
111const LEDGER: usize = 0;
113const SHARED: usize = 1;
114const OWN: usize = 2;
115const ACTIVITY: usize = 3;
116const OWN_ACTIVITY: usize = 4;
117const STORES: usize = 5;
118
119#[derive(Default)]
122struct Cursor {
123 places: [Place; STORES],
124}
125
126impl Cursor {
127 fn encode(&self) -> String {
128 let mut out = "5".to_string();
129 for p in &self.places {
130 let (ts, id) = p.last.as_ref().map_or(("-".to_string(), String::new()), |(ts, id)| (ts.to_string(), id.clone()));
131 out.push_str(&format!("|{ts}|{id}|{}", p.resume.as_deref().unwrap_or("-")));
132 }
133 out
134 }
135
136 fn decode(text: &str) -> Result<Self, String> {
137 let bad = || "audit.query: that cursor isn't one this query gave".to_string();
138 let mut parts = text.split('|');
139 let version = parts.next();
140 let mut cursor = Self::default();
141 let last = |parts: &mut std::str::Split<'_, char>| -> Result<Option<(u64, String)>, String> {
143 let ts = parts.next().ok_or_else(bad)?;
144 let id = parts.next().ok_or_else(bad)?.to_string();
145 if ts == "-" {
146 Ok(None)
147 } else {
148 Ok(Some((ts.parse().map_err(|_| bad())?, id)))
149 }
150 };
151 let end = |parts: &mut std::str::Split<'_, char>| -> Result<Option<String>, String> {
152 match parts.next().ok_or_else(bad)? {
153 "-" => Ok(None),
154 n => Ok(Some(n.to_string())),
155 }
156 };
157 match version {
158 Some("5") => {
159 for place in cursor.places.iter_mut() {
160 place.last = last(&mut parts)?;
161 place.resume = end(&mut parts)?;
162 }
163 }
164 Some(v @ ("3" | "4")) => {
166 cursor.places[LEDGER].last = last(&mut parts)?;
167 cursor.places[SHARED].last = last(&mut parts)?;
168 cursor.places[SHARED].resume = end(&mut parts)?;
169 if v == "4" {
170 cursor.places[OWN].last = last(&mut parts)?;
171 cursor.places[OWN].resume = end(&mut parts)?;
172 }
173 }
174 _ => return Err(bad()),
175 }
176 for (i, place) in cursor.places.iter().enumerate() {
178 let ok = match (i, place.resume.as_deref()) {
179 (_, None) => true,
180 (ACTIVITY | OWN_ACTIVITY, Some(r)) => r.split_once(':').is_some_and(|(_, byte)| byte.parse::<u64>().is_ok()),
181 (_, Some(r)) => r.parse::<u64>().is_ok(),
182 };
183 if !ok {
184 return Err(bad());
185 }
186 }
187 Ok(cursor)
188 }
189}
190
191struct Filter {
192 agent: Option<String>,
193 kinds: HashSet<String>,
194 since: u64,
195 until: u64,
196 text: String,
197 channel: Option<String>,
199}
200
201impl Filter {
202 fn of(req: &AuditQueryReq, own_channel: &str) -> Result<Self, String> {
203 let kinds: HashSet<String> = match &req.kinds {
204 Some(kinds) if !kinds.is_empty() => kinds.iter().map(|k| k.trim().to_lowercase()).collect(),
205 _ => DEFAULT_KINDS.iter().map(|k| k.to_string()).collect(),
206 };
207 if let Some(unknown) = kinds.iter().find(|k| !RECORDED.contains(&k.as_str()) && !NOT_RECORDED.contains(&k.as_str())) {
208 return Err(format!("audit.query: unknown kind '{unknown}'; the kinds are jekt, action, registry, agent_start, agent_end, tool, turn and thought"));
209 }
210 let channel = match req.scope.as_deref().map(str::trim) {
211 Some("channel") => Some(own_channel.to_string()),
212 None | Some("") | Some("machine") | Some("lan") => None,
214 Some(other) => return Err(format!("audit.query: unknown scope '{other}'; the scopes are channel, machine and lan")),
215 };
216 Ok(Self {
217 agent: req.agent_id.as_deref().map(str::trim).filter(|a| !a.is_empty()).map(str::to_string),
218 kinds,
219 since: req.since_ms.unwrap_or(0),
220 until: req.until_ms.unwrap_or(u64::MAX),
221 text: req.text.as_deref().map(|t| t.trim().to_lowercase()).unwrap_or_default(),
222 channel,
223 })
224 }
225
226 fn key(&self) -> String {
228 let mut kinds: Vec<&str> = self.kinds.iter().map(String::as_str).collect();
229 kinds.sort_unstable();
230 format!("{:?}|{}|{}|{}|{}|{:?}", self.agent.as_deref().map(route), kinds.join(","), self.since, self.until, self.text, self.channel)
231 }
232
233 fn keep(&self, e: &AuditEntry) -> bool {
234 if !self.kinds.contains(&e.kind) || e.ts_ms < self.since || e.ts_ms > self.until {
235 return false;
236 }
237 if let (Some(own), Some(from)) = (&self.channel, e.provenance.as_ref().and_then(|p| p.channel.as_deref())) {
239 if from != own {
240 return false;
241 }
242 }
243 if let Some(want) = &self.agent {
244 let ends = [e.agent_id.as_deref(), e.from.as_ref().map(|f| f.agent_id.as_str()), e.to.as_ref().map(|t| t.agent_id.as_str())];
245 if !ends.into_iter().flatten().any(|a| same_agent(a, want)) {
246 return false;
247 }
248 }
249 if self.text.is_empty() {
250 return true;
251 }
252 let ends = [e.agent_id.as_deref(), e.from.as_ref().map(|f| f.agent_id.as_str()), e.to.as_ref().map(|t| t.agent_id.as_str())];
253 let haystack = [Some(e.summary.as_str()), e.outcome.as_deref(), e.reason.as_deref()].into_iter().chain(ends).flatten().collect::<Vec<_>>().join("\n").to_lowercase();
254 haystack.contains(&self.text)
255 }
256}
257
258fn end_of(name: &str, ts_ms: u64, block_id: Option<&str>, ctx: &Ctx) -> AuditEnd {
260 let slug = route(name);
261 let uid = (ctx.uid_of_slug)(&slug);
262 let pane = (ctx.pane_of_agent)(&slug).or_else(|| block_id.filter(|b| !b.is_empty() && (ctx.block_exists)(b)).map(str::to_string));
263 AuditEnd {
264 agent_id: slug.clone(),
265 links: AuditLinks {
266 history: uid.map(|uid| AuditHistoryLink { definition_id: Some(uid), agent_id: slug, zone: None, at_ms: ts_ms, at_byte: None }),
268 pane: pane.map(|block_id| AuditPaneLink { block_id }),
269 task: None,
270 },
271 }
272}
273
274fn from_audit(at: u64, e: &AuditLogEntry, ctx: &Ctx) -> AuditEntry {
276 from_audit_in('j', at, e, ctx)
277}
278
279fn from_audit_in(prefix: char, at: u64, e: &AuditLogEntry, ctx: &Ctx) -> AuditEntry {
282 let ts_ms = e.timestamp;
283 let id = format!("{prefix}{at:016x}");
284 let from = e.source_agent.as_deref().filter(|s| !s.trim().is_empty());
285 let who = from.map(route).unwrap_or_else(|| "unknown".to_string());
286 let to = route(&e.target_agent);
287 let blank = AuditEntry {
288 id,
289 ts_ms,
290 kind: String::new(),
291 agent_id: None,
292 from: None,
293 to: None,
294 summary: String::new(),
295 outcome: e.outcome.clone(),
296 reason: e.reason.clone(),
297 cost: None,
298 links: AuditLinks::default(),
299 provenance: provenance::of(e),
300 prompt: e.prompt.clone(),
301 answer: e.answer.clone(),
302 level: e.level.clone(),
303 standing: e.standing,
304 };
305 match e.event_kind.as_str() {
306 "register" | "unregister" | "swept" => AuditEntry {
307 kind: KIND_REGISTRY.to_string(),
308 agent_id: Some(to.clone()),
309 summary: format!("{to}: {}", e.event_kind),
310 outcome: Some(e.event_kind.clone()),
311 links: end_of(&e.target_agent, ts_ms, Some(&e.block_id), ctx).links,
312 ..blank
313 },
314 "action" => {
315 let source = e.source_agent.as_deref().unwrap_or("").trim();
317 let actor = source
320 .strip_prefix("agent:")
321 .or_else(|| Some(source).filter(|s| !matches!(*s, "" | "operator" | "unproven" | "you") && !s.contains(|c: char| c.is_whitespace() || c == '@')))
322 .map(route)
323 .filter(|a| !a.is_empty());
324 let target = Some(to.clone()).filter(|t| !t.is_empty());
325 let name = actor.clone().unwrap_or_else(|| if source.is_empty() { "unknown".to_string() } else { source.to_string() });
326 AuditEntry {
327 kind: KIND_ACTION.to_string(),
328 links: actor.as_deref().map(|a| end_of(a, ts_ms, None, ctx).links).unwrap_or_default(),
329 to: target.as_ref().map(|_| end_of(&e.target_agent, ts_ms, Some(&e.block_id), ctx)),
330 summary: format!(
331 "{name} {}{}{}",
332 e.outcome.as_deref().unwrap_or("acted"),
333 target.map(|t| format!(" on {t}")).unwrap_or_default(),
334 failure_note(e)
335 ),
336 agent_id: actor,
337 ..blank
338 }
339 }
340 crate::backend::reactive::sent_audit::SENT => AuditEntry {
342 kind: KIND_JEKT.to_string(),
343 from: from.map(|f| end_of(f, ts_ms, None, ctx)),
344 to: Some(end_of(&e.target_agent, ts_ms, None, ctx)),
345 summary: format!("{who} → {to}: sent, {} bytes", e.message_length),
346 ..blank
347 },
348 other => {
349 let cli = other == "cli_native";
350 let status = if !e.success {
351 format!("failed{}", e.error_message.as_deref().map(|m| format!(" ({m})")).unwrap_or_default())
352 } else {
353 e.outcome.clone().unwrap_or_else(|| "delivered".to_string())
354 };
355 AuditEntry {
356 kind: KIND_JEKT.to_string(),
357 from: from.map(|f| end_of(f, ts_ms, None, ctx)),
358 to: Some(end_of(&e.target_agent, ts_ms, Some(&e.block_id), ctx)),
359 summary: format!("{who} → {to}: {}{status}, {} bytes", if cli { "CLI message, " } else { "" }, e.message_length),
360 cost: (e.success && e.message_length > 0).then(|| AuditCost {
363 input: agentmux_common::tokens::tokens_for_chars(e.message_length as u64),
364 cache_read: 0,
365 output: 0,
366 cache_write: None,
367 usd: None,
368 basis: "estimated".to_string(),
369 }),
370 ..blank
371 }
372 }
373 }
374}
375
376fn file_stream<'a>(
379 path: Option<&'a Path>,
380 prefix: char,
381 src: &'a Sources,
382 filter: &'a Filter,
383 after: Option<(u64, String)>,
384 end: Option<u64>,
385) -> ordered::Ordered<'a, AuditLogEntry> {
386 let wants_any = [KIND_JEKT, KIND_ACTION, KIND_REGISTRY].iter().any(|k| filter.kinds.contains(*k));
387 let lines: Box<dyn Iterator<Item = _>> = match path.filter(|_| wants_any) {
388 Some(path) => Box::new(jekt_file::entries::<AuditLogEntry>(path, end)),
389 None => Box::new(std::iter::empty()),
390 };
391 ordered::Ordered::new(lines, |e: &AuditLogEntry| e.timestamp, move |at, e| from_audit_in(prefix, at, e, &src.ctx), move |e| filter.keep(e), filter.since, after)
392}
393
394trait Store {
396 fn peek(&mut self) -> Option<&AuditEntry>;
397 fn pop(&mut self) -> Option<AuditEntry>;
398 fn resume(&self, previous: Option<&str>) -> Option<String>;
400}
401
402impl Store for ordered::Ordered<'_, AuditLogEntry> {
403 fn peek(&mut self) -> Option<&AuditEntry> {
404 ordered::Ordered::peek(self)
405 }
406 fn pop(&mut self) -> Option<AuditEntry> {
407 ordered::Ordered::pop(self)
408 }
409 fn resume(&self, previous: Option<&str>) -> Option<String> {
410 ordered::Ordered::resume(self, previous.and_then(|p| p.parse().ok())).map(|b| b.to_string())
411 }
412}
413
414impl Store for activity::DayStream<'_> {
415 fn peek(&mut self) -> Option<&AuditEntry> {
416 activity::DayStream::peek(self)
417 }
418 fn pop(&mut self) -> Option<AuditEntry> {
419 activity::DayStream::pop(self)
420 }
421 fn resume(&self, previous: Option<&str>) -> Option<String> {
422 activity::DayStream::resume(self, previous)
423 }
424}
425
426struct LedgerStore(std::iter::Peekable<std::vec::IntoIter<AuditEntry>>);
428
429impl Store for LedgerStore {
430 fn peek(&mut self) -> Option<&AuditEntry> {
431 self.0.peek()
432 }
433 fn pop(&mut self) -> Option<AuditEntry> {
434 self.0.next()
435 }
436 fn resume(&self, _: Option<&str>) -> Option<String> {
437 None
438 }
439}
440
441pub fn query<'a>(src: &'a Sources<'a>, req: &AuditQueryReq) -> Result<AuditQueryResult, String> {
443 let filter = Filter::of(req, src.channel)?;
444 let limit = (req.limit.map_or(DEFAULT_LIMIT, |l| l as usize)).clamp(1, MAX_LIMIT);
445 let cursor = req.cursor.as_deref().map(Cursor::decode).transpose()?.unwrap_or_default();
446 let place = |i: usize| cursor.places[i].clone();
447
448 let mut ledger: Vec<AuditEntry> = if filter.kinds.contains(KIND_AGENT_START) || filter.kinds.contains(KIND_AGENT_END) {
450 src.segments.map(|s| segments::entries(s, filter.agent.as_deref(), &src.ctx)).unwrap_or_default()
451 } else {
452 Vec::new()
453 };
454 let past = place(LEDGER).last;
455 ledger.retain(|e| filter.keep(e) && past.as_ref().is_none_or(|(ts, id)| (e.ts_ms, e.id.as_str()) < (*ts, id.as_str())));
456 ledger.sort_by(|a, b| (b.ts_ms, &b.id).cmp(&(a.ts_ms, &a.id)));
457
458 let end_of = |i: usize| place(i).resume.and_then(|r| r.parse().ok());
459 let wants_activity = [KIND_TOOL, KIND_TURN, KIND_THOUGHT].iter().any(|k| filter.kinds.contains(*k));
460 let dir = |d: Option<&'a Path>| d.filter(|_| wants_activity);
461 let mut stores: [Box<dyn Store + '_>; STORES] = [
463 Box::new(LedgerStore(ledger.into_iter().peekable())),
464 Box::new(file_stream(src.jekt_file, 'j', src, &filter, place(SHARED).last, end_of(SHARED))),
465 Box::new(file_stream(src.own_file, 'o', src, &filter, place(OWN).last, end_of(OWN))),
466 Box::new(activity::DayStream::new(dir(src.activity_dir), 's', &filter, &src.ctx, place(ACTIVITY).last, place(ACTIVITY).resume.as_deref())),
467 Box::new(activity::DayStream::new(dir(src.own_activity_dir), 'o', &filter, &src.ctx, place(OWN_ACTIVITY).last, place(OWN_ACTIVITY).resume.as_deref())),
468 ];
469
470 let mut entries: Vec<AuditEntry> = Vec::new();
471 let mut joiner = provenance::Joiner::default();
472 let mut last: [Option<(u64, String)>; STORES] = std::array::from_fn(|i| place(i).last);
473 let mut more = false;
474 loop {
475 let mut newest: Option<(usize, (u64, String))> = None;
477 for (i, store) in stores.iter_mut().enumerate() {
478 if let Some(e) = store.peek() {
479 let key = (e.ts_ms, e.id.clone());
480 if newest.as_ref().is_none_or(|(_, best)| key > *best) {
481 newest = Some((i, key));
482 }
483 }
484 }
485 let Some((i, _)) = newest else { break };
486 if entries.len() == limit && !stores[i].peek().is_some_and(|e| joiner.completes(e)) {
488 more = true;
489 break;
490 }
491 if let Some(entry) = stores[i].pop() {
492 last[i] = Some((entry.ts_ms, entry.id.clone()));
493 joiner.push(&mut entries, entry);
494 }
495 }
496 let next_cursor = more.then(|| {
497 let mut next = Cursor::default();
498 for i in 0..STORES {
499 next.places[i] = Place { last: last[i].clone(), resume: stores[i].resume(cursor.places[i].resume.as_deref()) };
500 }
501 next.encode()
502 });
503 let not_recorded = NOT_RECORDED.iter().filter(|k| filter.kinds.contains(**k)).map(|k| k.to_string()).collect();
504 let totals = req.totals.unwrap_or(false).then(|| totals::of(src, &filter));
505 Ok(AuditQueryResult { entries, next_cursor, not_recorded, totals, channel: Some(src.channel.to_string()), other_channels: None, peers: None })
506}
507
508#[cfg(test)]
509#[path = "audit_query_tests.rs"]
510mod tests;