Skip to main content

weirdnet_agent/
trace.rs

1//! Traces, steps and citations.
2//!
3//! Every search, fetch, tool call, approval and notice in a task becomes a
4//! [`TraceStep`]. Answers cite sources with [`Citation`]s that name the steps
5//! behind them; [`validate_citations`] rejects any cited URL that no listed
6//! fetch step retrieved, and [`retain_valid`] drops such citations before display.
7
8use std::collections::BTreeMap;
9
10use serde::{Deserialize, Serialize};
11
12use crate::identity::AgentId;
13use crate::policy::{DenyReason, Scope, Tier};
14
15/// Index of a step in its trace, starting at 1 (as shown in footnotes).
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
17#[serde(transparent)]
18pub struct StepId(pub u32);
19
20/// Which browsing session a step used.
21#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
22#[serde(rename_all = "snake_case", tag = "session")]
23#[non_exhaustive]
24pub enum SessionMark {
25    #[default]
26    LoggedOut,
27    SignedIn {
28        profile: String,
29    },
30}
31
32/// How an approval was resolved.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case", tag = "outcome")]
35#[non_exhaustive]
36pub enum ApprovalOutcome {
37    Approved {
38        scope: Scope,
39    },
40    /// Skipped because of a site grant or task approval (`allow_id` is `None`) or a standing allow.
41    AutoAllowed {
42        allow_id: Option<u64>,
43    },
44    Denied,
45    Blocked {
46        reason: DenyReason,
47    },
48}
49
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(rename_all = "snake_case", tag = "kind")]
52#[non_exhaustive]
53pub enum StepKind {
54    Model { model: String, tool_calls: u32 },
55    Search { provider: String, query: String, results: u32 },
56    Fetch { url: String, status: Option<u16>, bytes: u64 },
57    Extract { url: String, chars: u64 },
58    Tool { source: String, tool: String, args_summary: String, result_bytes: u64, is_error: bool },
59    Approval { tool: String, tier: Tier, outcome: ApprovalOutcome },
60    Skipped { reason: String, url: Option<String> },
61    Notice { text: String },
62    Cancelled,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66pub struct TraceStep {
67    pub id: StepId,
68    pub at_unix_ms: u64,
69    pub agent: AgentId,
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub node: Option<String>,
72    #[serde(default)]
73    pub session: SessionMark,
74    #[serde(flatten)]
75    pub kind: StepKind,
76}
77
78/// The ordered record of one task.
79#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
80pub struct Trace {
81    pub task_id: String,
82    pub agent: AgentId,
83    pub steps: Vec<TraceStep>,
84}
85
86impl Trace {
87    pub fn new(task_id: impl Into<String>, agent: AgentId) -> Self {
88        Self { task_id: task_id.into(), agent, steps: Vec::new() }
89    }
90
91    /// Appends a step and returns its id.
92    pub fn push(&mut self, kind: StepKind, session: SessionMark, node: Option<String>, at_unix_ms: u64) -> StepId {
93        let id = StepId(self.steps.len() as u32 + 1);
94        self.steps.push(TraceStep { id, at_unix_ms, agent: self.agent.clone(), node, session, kind });
95        id
96    }
97
98    pub fn step(&self, id: StepId) -> Option<&TraceStep> {
99        id.0.checked_sub(1).and_then(|i| self.steps.get(i as usize))
100    }
101
102    /// Fetched URLs and the steps that fetched them.
103    pub fn fetched_urls(&self) -> BTreeMap<String, Vec<StepId>> {
104        let mut out: BTreeMap<String, Vec<StepId>> = BTreeMap::new();
105        for s in &self.steps {
106            if let StepKind::Fetch { url, .. } = &s.kind {
107                out.entry(normalize_url(url)).or_default().push(s.id);
108            }
109        }
110        out
111    }
112
113    /// Counts for the trace summary line ("9 steps · 1 search · 1 MCP call · 4 pages").
114    pub fn summary(&self) -> TraceSummary {
115        let mut s = TraceSummary { steps: self.steps.len() as u32, ..Default::default() };
116        for step in &self.steps {
117            match step.kind {
118                StepKind::Search { .. } => s.searches += 1,
119                StepKind::Fetch { .. } => s.pages += 1,
120                StepKind::Tool { .. } => s.tool_calls += 1,
121                _ => {}
122            }
123        }
124        s
125    }
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
129pub struct TraceSummary {
130    pub steps: u32,
131    pub searches: u32,
132    pub pages: u32,
133    pub tool_calls: u32,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(rename_all = "snake_case", tag = "type")]
138#[non_exhaustive]
139pub enum CitationTarget {
140    Url { url: String, quote: Option<String> },
141    ToolResult { source: String, tool: String },
142}
143
144/// A footnote `[n]` in an answer.
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
146pub struct Citation {
147    pub n: u32,
148    pub target: CitationTarget,
149    pub steps: Vec<StepId>,
150}
151
152#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
153#[serde(rename_all = "snake_case", tag = "error")]
154#[non_exhaustive]
155pub enum CitationError {
156    #[error("citation [{n}] names no steps")]
157    NoSteps { n: u32 },
158    #[error("citation [{n}] names step {step:?}, which is not in the trace")]
159    UnknownStep { n: u32, step: StepId },
160    #[error("citation [{n}] cites {url}, which none of its steps fetched")]
161    UrlNotFetched { n: u32, url: String },
162    #[error("citation [{n}] cites {tool_source}.{tool}, which none of its steps called")]
163    ToolNotCalled { n: u32, tool_source: String, tool: String },
164}
165
166fn normalize_url(url: &str) -> String {
167    let no_frag = url.split('#').next().unwrap_or_default();
168    let trimmed = no_frag.strip_suffix('/').unwrap_or(no_frag);
169    match trimmed.split_once("://") {
170        Some((scheme, rest)) => {
171            let (host, path) = rest.split_at(rest.find('/').unwrap_or(rest.len()));
172            format!("{}://{}{}", scheme.to_ascii_lowercase(), host.to_ascii_lowercase(), path)
173        }
174        None => trimmed.to_string(),
175    }
176}
177
178fn check(trace: &Trace, c: &Citation) -> Option<CitationError> {
179    if c.steps.is_empty() {
180        return Some(CitationError::NoSteps { n: c.n });
181    }
182    let mut steps = Vec::with_capacity(c.steps.len());
183    for id in &c.steps {
184        match trace.step(*id) {
185            Some(s) => steps.push(s),
186            None => return Some(CitationError::UnknownStep { n: c.n, step: *id }),
187        }
188    }
189    match &c.target {
190        CitationTarget::Url { url, .. } => {
191            let want = normalize_url(url);
192            let ok = steps.iter().any(|s| matches!(&s.kind, StepKind::Fetch { url, .. } if normalize_url(url) == want));
193            (!ok).then(|| CitationError::UrlNotFetched { n: c.n, url: url.clone() })
194        }
195        CitationTarget::ToolResult { source, tool } => {
196            let ok =
197                steps.iter().any(|s| matches!(&s.kind, StepKind::Tool { source: s2, tool: t2, is_error: false, .. } if s2 == source && t2 == tool));
198            (!ok).then(|| CitationError::ToolNotCalled { n: c.n, tool_source: source.clone(), tool: tool.clone() })
199        }
200    }
201}
202
203/// Checks that every citation maps to steps in `trace`: each cited URL must be
204/// fetched by one of its listed steps, and each cited tool result must come from
205/// one of its listed (successful) tool steps.
206pub fn validate_citations(trace: &Trace, citations: &[Citation]) -> Result<(), Vec<CitationError>> {
207    let errors: Vec<_> = citations.iter().filter_map(|c| check(trace, c)).collect();
208    if errors.is_empty() { Ok(()) } else { Err(errors) }
209}
210
211/// Keeps only valid citations: a citation with no backing step is never shown.
212pub fn retain_valid(trace: &Trace, citations: Vec<Citation>) -> Vec<Citation> {
213    citations.into_iter().filter(|c| check(trace, c).is_none()).collect()
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219
220    fn sample() -> Trace {
221        let mut t = Trace::new("7f3a", AgentId::new("atlas"));
222        let lo = SessionMark::LoggedOut;
223        t.push(StepKind::Search { provider: "duckduckgo".into(), query: "tokio cancellation".into(), results: 10 }, lo.clone(), None, 1);
224        t.push(StepKind::Fetch { url: "https://Tokio.rs/tokio/topics/shutdown/".into(), status: Some(200), bytes: 9000 }, lo.clone(), None, 2);
225        t.push(StepKind::Extract { url: "https://tokio.rs/tokio/topics/shutdown".into(), chars: 610 }, lo.clone(), None, 3);
226        t.push(
227            StepKind::Tool {
228                source: "mouser-tools".into(),
229                tool: "search_issues".into(),
230                args_summary: "q=cancel".into(),
231                result_bytes: 300,
232                is_error: false,
233            },
234            lo,
235            Some("alien-blue".into()),
236            4,
237        );
238        t.push(
239            StepKind::Fetch { url: "https://docs.rs/tokio".into(), status: Some(200), bytes: 1 },
240            SessionMark::SignedIn { profile: "default".into() },
241            None,
242            5,
243        );
244        t
245    }
246
247    fn url(n: u32, u: &str, steps: &[u32]) -> Citation {
248        Citation { n, target: CitationTarget::Url { url: u.into(), quote: None }, steps: steps.iter().map(|s| StepId(*s)).collect() }
249    }
250
251    #[test]
252    fn valid_citations_pass() {
253        let t = sample();
254        let cites = vec![
255            url(1, "https://tokio.rs/tokio/topics/shutdown#graceful", &[2, 3]),
256            Citation {
257                n: 2,
258                target: CitationTarget::ToolResult { source: "mouser-tools".into(), tool: "search_issues".into() },
259                steps: vec![StepId(4)],
260            },
261            url(3, "https://docs.rs/tokio/", &[5]),
262        ];
263        assert_eq!(validate_citations(&t, &cites), Ok(()));
264    }
265
266    #[test]
267    fn invalid_citations_are_reported_and_dropped() {
268        let t = sample();
269        let cites = vec![
270            url(1, "https://tokio.rs/tokio/topics/shutdown", &[3]), // extract only, no fetch
271            url(2, "https://evil.example/", &[2]),
272            url(3, "https://docs.rs/tokio", &[]),
273            url(4, "https://docs.rs/tokio", &[99]),
274            Citation { n: 5, target: CitationTarget::ToolResult { source: "x".into(), tool: "y".into() }, steps: vec![StepId(4)] },
275            url(6, "https://docs.rs/tokio", &[5]),
276        ];
277        let errs = validate_citations(&t, &cites).unwrap_err();
278        assert_eq!(errs.len(), 5);
279        assert!(matches!(errs[0], CitationError::UrlNotFetched { n: 1, .. }));
280        assert!(matches!(errs[1], CitationError::UrlNotFetched { n: 2, .. }));
281        assert_eq!(errs[2], CitationError::NoSteps { n: 3 });
282        assert_eq!(errs[3], CitationError::UnknownStep { n: 4, step: StepId(99) });
283        assert!(matches!(errs[4], CitationError::ToolNotCalled { n: 5, .. }));
284        let kept = retain_valid(&t, cites);
285        assert_eq!(kept.len(), 1);
286        assert_eq!(kept[0].n, 6);
287    }
288
289    #[test]
290    fn step_lookup_summary_and_fetched_urls() {
291        let t = sample();
292        assert!(t.step(StepId(0)).is_none());
293        assert_eq!(t.step(StepId(4)).unwrap().node.as_deref(), Some("alien-blue"));
294        let s = t.summary();
295        assert_eq!((s.steps, s.searches, s.pages, s.tool_calls), (5, 1, 2, 1));
296        let urls = t.fetched_urls();
297        assert_eq!(urls["https://tokio.rs/tokio/topics/shutdown"], vec![StepId(2)]);
298    }
299
300    #[test]
301    fn serde_roundtrip_keeps_session_marks() {
302        let t = sample();
303        let json = serde_json::to_string(&t).unwrap();
304        assert!(json.contains("\"kind\":\"fetch\""));
305        assert!(json.contains("\"session\":\"signed_in\""));
306        let back: Trace = serde_json::from_str(&json).unwrap();
307        assert_eq!(back, t);
308    }
309}