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