use anyhow::Result; use serde::Serialize; use std::collections::{BTreeSet, HashMap, HashSet}; use crate::agent::AgentTraceEntry; use crate::canonical_json; use crate::model::{RunMetadata, TraceEvent, WitnessedMetadata}; use crate::tooling::{PhantomEntry, ToolCall, ToolOutcome, ToolRequest, TranscriptFault}; use crate::witness; #[allow(dead_code)] pub fn encode_metadata(metadata: &RunMetadata) -> Result> { to_canonical_json(metadata) } pub fn encode_witnessed_metadata(metadata: &WitnessedMetadata) -> Result> { to_canonical_json(metadata) } pub fn encode_event(event: &TraceEvent) -> Result> { to_canonical_json(event) } pub fn encode_agent_trace_entry(entry: &AgentTraceEntry) -> Result> { let witness_entry = AgentTraceEntryWitness::from(entry); to_canonical_json(&witness_entry) } pub fn encode_tool_call_witness(call: &ToolCallWitnessView) -> Result> { to_canonical_json(call) } pub fn encode_phantom_entry_witness(entry: &PhantomEntryWitnessView) -> Result> { to_canonical_json(entry) } #[allow(dead_code)] pub fn tool_call_witness_value_canonical(call: &ToolCall) -> Result { canonical_json::to_value(&ToolCallWitnessView::from(call)) } fn to_canonical_json(value: &T) -> Result> { canonical_json::to_vec(value) } /// Normalise a tool name for the witness view. /// /// Tool names are committed lowercased so the agent trace and the transcript /// agree even when the agent emitted mixed case. This mirrors the lowercasing /// the dispatch gate applies in `ToolTranscript::execute`; without it, a /// capitalised tool name in the trace would never match its (already /// lowercased) transcript entry and witness recompute would fail closed on an /// otherwise valid run. fn normalize_tool_name_for_witness(tool_name: &str) -> String { tool_name.to_lowercase() } #[derive(Serialize)] struct AgentTraceEntryWitness { step: u32, role: String, thought: String, action: String, tool_requests: Vec, is_final: bool, } impl From<&AgentTraceEntry> for AgentTraceEntryWitness { fn from(entry: &AgentTraceEntry) -> Self { let thought = entry.thought.clone(); let action = entry.action.clone(); let tool_requests = entry .tool_requests .iter() .map(|req| ToolRequest { tool_name: normalize_tool_name_for_witness(&req.tool_name), arguments: req.arguments.clone(), }) .collect(); Self { step: entry.step, role: entry.role.clone(), thought, action, tool_requests, is_final: entry.is_final, } } } #[derive(Debug, Clone, Serialize)] pub struct ToolCallOutcomeWitnessView { #[serde(skip_serializing_if = "Option::is_none")] output: Option, #[serde(skip_serializing_if = "Option::is_none")] error: Option, } impl From<&ToolOutcome> for ToolCallOutcomeWitnessView { fn from(outcome: &ToolOutcome) -> Self { match outcome { ToolOutcome::Ok { output, .. } => Self { output: Some(output.clone()), error: None, }, ToolOutcome::Err { error, .. } => Self { output: None, error: Some(error.clone()), }, } } } #[derive(Debug, Clone, Serialize)] pub struct ToolCallWitnessView { step: u32, tool_call_idx: u32, tool_name: String, request: serde_json::Value, outcome: ToolCallOutcomeWitnessView, #[serde(skip_serializing_if = "Option::is_none")] fault: Option, } impl ToolCallWitnessView { pub fn tool_call_idx(&self) -> u32 { self.tool_call_idx } } pub fn tool_call_witness_view(call: &ToolCall) -> ToolCallWitnessView { ToolCallWitnessView::from(call) } #[derive(Debug, Clone, Serialize)] pub struct PhantomEntryWitnessView { step: u32, tool_call_idx: u32, tool_name: String, request: serde_json::Value, disposition: crate::policy::PhantomDisposition, #[serde(skip_serializing_if = "Option::is_none")] rule_id: Option, reason: String, } impl PhantomEntryWitnessView { pub fn tool_call_idx(&self) -> u32 { self.tool_call_idx } } impl From<&PhantomEntry> for PhantomEntryWitnessView { fn from(entry: &PhantomEntry) -> Self { Self { step: entry.step, tool_call_idx: entry.tool_call_idx, tool_name: normalize_tool_name_for_witness(&entry.tool_name), request: entry.request.clone(), disposition: entry.disposition.clone(), rule_id: entry.rule_id.clone(), reason: entry.reason.clone(), } } } #[derive(Debug, Clone, Serialize)] #[serde(tag = "kind", rename_all = "snake_case")] enum TranscriptFaultWitnessView { Timeout { domain: String }, Drop { domain: String }, Corrupt { domain: String }, LatencySim { domain: String }, } impl From<&TranscriptFault> for TranscriptFaultWitnessView { fn from(value: &TranscriptFault) -> Self { match value { TranscriptFault::Timeout { domain, .. } => Self::Timeout { domain: domain.clone(), }, TranscriptFault::Drop { domain } => Self::Drop { domain: domain.clone(), }, TranscriptFault::Corrupt { domain, .. } => Self::Corrupt { domain: domain.clone(), }, TranscriptFault::LatencySim { domain, .. } => Self::LatencySim { domain: domain.clone(), }, } } } impl From<&ToolCall> for ToolCallWitnessView { fn from(call: &ToolCall) -> Self { Self { step: call.step, tool_call_idx: call.tool_call_idx, tool_name: normalize_tool_name_for_witness(&call.tool_name), request: call.request.clone(), outcome: ToolCallOutcomeWitnessView::from(&call.outcome), fault: call.fault.as_ref().map(TranscriptFaultWitnessView::from), } } } pub fn compute_agent_witness_root( metadata: &WitnessedMetadata, agent_trace: &[AgentTraceEntry], tool_calls: &[ToolCall], phantom_entries: &[PhantomEntry], ) -> Result { validate_agent_witness_inputs(agent_trace, tool_calls, phantom_entries)?; let metadata_bytes = encode_witnessed_metadata(metadata)?; let mut witness = witness::Witness::new(&metadata_bytes)?; let mut ops_by_step = index_tool_ops_by_step(tool_calls, phantom_entries); for ops in ops_by_step.values_mut() { ops.sort_by_key(|op| op.tool_call_idx()); } for entry in agent_trace { let entry_bytes = encode_agent_trace_entry(entry)?; witness.update(&entry_bytes)?; if let Some(ops) = ops_by_step.get(&entry.step) { for op in ops { match op { ToolOpWitnessView::Executed(call) => { let call_bytes = encode_tool_call_witness(call)?; witness.update(&call_bytes)?; } ToolOpWitnessView::Intercepted(phantom) => { let phantom_bytes = encode_phantom_entry_witness(phantom)?; witness.update(&phantom_bytes)?; } } } } } Ok(witness.finalize_hex()) } fn validate_agent_witness_inputs( agent_trace: &[AgentTraceEntry], tool_calls: &[ToolCall], phantom_entries: &[PhantomEntry], ) -> Result<()> { let mut seen_steps = BTreeSet::new(); let mut prev_step: Option = None; for entry in agent_trace { if let Some(prev) = prev_step { if entry.step <= prev { anyhow::bail!("agent_trace steps must be strictly increasing"); } } if !seen_steps.insert(entry.step) { anyhow::bail!("duplicate agent_trace step {}", entry.step); } prev_step = Some(entry.step); } let mut seen_idx = HashSet::new(); for call in tool_calls { if !seen_steps.contains(&call.step) { anyhow::bail!("orphan tool call at absent step {}", call.step); } if !seen_idx.insert(call.tool_call_idx) { anyhow::bail!("duplicate tool_call_idx {}", call.tool_call_idx); } } for phantom in phantom_entries { if !seen_steps.contains(&phantom.step) { anyhow::bail!("orphan phantom entry at absent step {}", phantom.step); } if !seen_idx.insert(phantom.tool_call_idx) { anyhow::bail!( "executed/phantom tool_call_idx collision {}", phantom.tool_call_idx ); } } let total = tool_calls.len() + phantom_entries.len(); for idx in 0..total as u32 { if !seen_idx.contains(&idx) { anyhow::bail!("non-contiguous tool_call_idx; missing {}", idx); } } let mut ops_by_step = index_tool_ops_by_step(tool_calls, phantom_entries); for entry in agent_trace { let mut ops = ops_by_step.remove(&entry.step).unwrap_or_default(); ops.sort_by_key(|op| op.tool_call_idx()); if entry.tool_requests.len() != ops.len() { anyhow::bail!( "tool request/op count mismatch at step {}: trace={} transcript={}", entry.step, entry.tool_requests.len(), ops.len() ); } for (request, op) in entry.tool_requests.iter().zip(ops.iter()) { let (tool_name, arguments) = match op { ToolOpWitnessView::Executed(call) => (&call.tool_name, &call.request), ToolOpWitnessView::Intercepted(phantom) => (&phantom.tool_name, &phantom.request), }; // Compare against the normalised name so a mixed-case trace request // still matches its lowercased transcript op. if normalize_tool_name_for_witness(&request.tool_name) != *tool_name || request.arguments != *arguments { anyhow::bail!( "tool request/op mismatch at step {} for tool_call_idx {}", entry.step, op.tool_call_idx() ); } } } Ok(()) } pub fn index_tool_calls_by_step(tool_calls: &[ToolCall]) -> HashMap> { let mut map: HashMap> = HashMap::new(); for call in tool_calls { map.entry(call.step) .or_default() .push(tool_call_witness_view(call)); } map } pub enum ToolOpWitnessView { Executed(ToolCallWitnessView), Intercepted(PhantomEntryWitnessView), } impl ToolOpWitnessView { pub fn tool_call_idx(&self) -> u32 { match self { ToolOpWitnessView::Executed(call) => call.tool_call_idx(), ToolOpWitnessView::Intercepted(entry) => entry.tool_call_idx(), } } } pub fn index_tool_ops_by_step( tool_calls: &[ToolCall], phantom_entries: &[PhantomEntry], ) -> HashMap> { let mut map: HashMap> = HashMap::new(); for call in tool_calls { map.entry(call.step) .or_default() .push(ToolOpWitnessView::Executed(tool_call_witness_view(call))); } for entry in phantom_entries { map.entry(entry.step) .or_default() .push(ToolOpWitnessView::Intercepted( PhantomEntryWitnessView::from(entry), )); } map } #[cfg(test)] mod tests { use super::compute_agent_witness_root; use crate::agent::AgentTraceEntry; use crate::model::WitnessedMetadata; use crate::tooling::{ToolCall, ToolOutcome, ToolRequest}; use anyhow::Result; fn agent_root(trace_tool_name: &str) -> Result { let metadata = WitnessedMetadata::default(); let agent_trace = vec![AgentTraceEntry { step: 0, role: "assistant".to_string(), thought: "t".to_string(), action: "a".to_string(), tool_requests: vec![ToolRequest { tool_name: trace_tool_name.to_string(), arguments: serde_json::json!({ "k": "v" }), }], is_final: true, }]; // The transcript side is always lowercased by the dispatch gate. let tool_calls = vec![ToolCall { step: 0, tool_call_idx: 0, tool_name: "clawdbot.lookup".to_string(), request: serde_json::json!({ "k": "v" }), outcome: ToolOutcome::Ok { output: serde_json::json!({ "ok": true }), simulated_latency_ms: None, }, fault: None, }]; compute_agent_witness_root(&metadata, &agent_trace, &tool_calls, &[]) } #[test] fn mixed_case_trace_name_validates_and_matches_lowercase() { // A capitalised tool name in the agent trace must not break recompute, // and must produce the same root as the all-lowercase equivalent. let mixed = agent_root("Clawdbot.Lookup").expect("mixed-case trace name must validate"); let lower = agent_root("clawdbot.lookup").expect("lowercase trace name must validate"); assert_eq!(mixed, lower); } }