treeship-core 0.11.2

Portable trust receipts for agent workflows - core library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! Agent collaboration graph built from session events.
//!
//! Captures the full topology of agent relationships: parent-child spawning,
//! handoffs, and collaboration edges.

use std::collections::{BTreeMap, BTreeSet};

use serde::{Deserialize, Serialize};

use super::event::{EventType, SessionEvent};

/// Type of relationship between two agents.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AgentEdgeType {
    /// Parent spawned a child agent.
    ParentChild,
    /// Work was handed off from one agent to another.
    Handoff,
    /// Agents collaborated on a shared task.
    Collaboration,
    /// Agent returned control to a parent.
    Return,
}

/// A node in the agent graph representing one agent instance.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentNode {
    pub agent_id: String,
    pub agent_instance_id: String,
    pub agent_name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub agent_role: Option<String>,
    pub host_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub started_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub completed_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    #[serde(default)]
    pub depth: u32,
    /// Number of tool calls made by this agent.
    #[serde(default)]
    pub tool_calls: u32,
    /// Model identifier (e.g. "claude-opus-4-6"). Populated from decision events.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// Cumulative input tokens across all decisions by this agent.
    #[serde(default)]
    pub tokens_in: u64,
    /// Cumulative output tokens across all decisions by this agent.
    #[serde(default)]
    pub tokens_out: u64,
    /// Provider e.g. "anthropic", "openrouter", "bedrock"
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
}

/// A directed edge in the agent graph.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentEdge {
    pub from_instance_id: String,
    pub to_instance_id: String,
    pub edge_type: AgentEdgeType,
    pub timestamp: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub artifacts: Vec<String>,
}

/// The complete agent collaboration graph for a session.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AgentGraph {
    pub nodes: Vec<AgentNode>,
    pub edges: Vec<AgentEdge>,
}

impl AgentGraph {
    /// Build an agent graph from a sequence of session events.
    pub fn from_events(events: &[SessionEvent]) -> Self {
        let mut nodes_map: BTreeMap<String, AgentNode> = BTreeMap::new();
        let mut edges: Vec<AgentEdge> = Vec::new();
        let mut parent_map: BTreeMap<String, String> = BTreeMap::new(); // child -> parent instance

        for event in events {
            let instance_id = &event.agent_instance_id;

            // Ensure node exists
            let node = nodes_map.entry(instance_id.clone()).or_insert_with(|| AgentNode {
                agent_id: event.agent_id.clone(),
                agent_instance_id: instance_id.clone(),
                agent_name: event.agent_name.clone(),
                agent_role: event.agent_role.clone(),
                host_id: event.host_id.clone(),
                started_at: None,
                completed_at: None,
                status: None,
                depth: 0,
                tool_calls: 0,
                model: None,
                tokens_in: 0,
                tokens_out: 0,
                provider: None,
            });

            match &event.event_type {
                EventType::AgentStarted { parent_agent_instance_id } => {
                    node.started_at = Some(event.timestamp.clone());
                    if let Some(parent_id) = parent_agent_instance_id {
                        parent_map.insert(instance_id.clone(), parent_id.clone());
                    }
                }

                EventType::AgentSpawned { spawned_by_agent_instance_id, .. } => {
                    node.started_at = Some(event.timestamp.clone());
                    parent_map.insert(instance_id.clone(), spawned_by_agent_instance_id.clone());
                    edges.push(AgentEdge {
                        from_instance_id: spawned_by_agent_instance_id.clone(),
                        to_instance_id: instance_id.clone(),
                        edge_type: AgentEdgeType::ParentChild,
                        timestamp: event.timestamp.clone(),
                        artifacts: Vec::new(),
                    });
                }

                EventType::AgentHandoff { from_agent_instance_id, to_agent_instance_id, artifacts } => {
                    edges.push(AgentEdge {
                        from_instance_id: from_agent_instance_id.clone(),
                        to_instance_id: to_agent_instance_id.clone(),
                        edge_type: AgentEdgeType::Handoff,
                        timestamp: event.timestamp.clone(),
                        artifacts: artifacts.clone(),
                    });
                    // Ensure the target node exists
                    nodes_map.entry(to_agent_instance_id.clone()).or_insert_with(|| AgentNode {
                        agent_id: String::new(),
                        agent_instance_id: to_agent_instance_id.clone(),
                        agent_name: String::new(),
                        agent_role: None,
                        host_id: event.host_id.clone(),
                        started_at: None,
                        completed_at: None,
                        status: None,
                        depth: 0,
                        tool_calls: 0,
                        model: None,
                        tokens_in: 0,
                        tokens_out: 0,
                        provider: None,
                    });
                }

                EventType::AgentCollaborated { collaborator_agent_instance_ids } => {
                    for collab_id in collaborator_agent_instance_ids {
                        edges.push(AgentEdge {
                            from_instance_id: instance_id.clone(),
                            to_instance_id: collab_id.clone(),
                            edge_type: AgentEdgeType::Collaboration,
                            timestamp: event.timestamp.clone(),
                            artifacts: Vec::new(),
                        });
                    }
                }

                EventType::AgentReturned { returned_to_agent_instance_id } => {
                    edges.push(AgentEdge {
                        from_instance_id: instance_id.clone(),
                        to_instance_id: returned_to_agent_instance_id.clone(),
                        edge_type: AgentEdgeType::Return,
                        timestamp: event.timestamp.clone(),
                        artifacts: Vec::new(),
                    });
                }

                EventType::AgentCompleted { .. } => {
                    node.completed_at = Some(event.timestamp.clone());
                    node.status = Some("completed".into());
                }

                EventType::AgentFailed { .. } => {
                    node.completed_at = Some(event.timestamp.clone());
                    node.status = Some("failed".into());
                }

                // node.tool_calls counts every action the agent took. The
                // side-effects ledger then groups those actions by category
                // (files_read, files_written, processes, network_connections,
                // ports_opened, tool_invocations) -- but the per-agent total
                // here is the cardinal count.
                //
                // History note: prior to v0.9.5 only AgentCalledTool and
                // AgentCompletedProcess were counted, which made the per-agent
                // count drop to near-zero when the Claude Code plugin started
                // emitting specialized event types (agent.read_file, etc.).
                // The sum of node.tool_calls across all agents (used as
                // "Actions" in the local preview and as the headline tool
                // count on treeship.dev/receipt/<id>) was undercounting the
                // agent's actual activity. Adding the four file/network/port
                // event types here fixes the counter for all consumers in
                // one place; renderers don't need to compute the total
                // themselves.
                EventType::AgentCalledTool { .. } => {
                    node.tool_calls += 1;
                }

                EventType::AgentCompletedProcess { .. } => {
                    node.tool_calls += 1;
                }

                EventType::AgentReadFile { .. } => {
                    node.tool_calls += 1;
                }

                EventType::AgentWroteFile { .. } => {
                    node.tool_calls += 1;
                }

                EventType::AgentConnectedNetwork { .. } => {
                    node.tool_calls += 1;
                }

                EventType::AgentOpenedPort { .. } => {
                    node.tool_calls += 1;
                }

                EventType::AgentDecision { ref model, tokens_in, tokens_out, ref provider, .. } => {
                    if let Some(ref m) = model {
                        node.model = Some(m.clone());
                    }
                    if let Some(ref p) = provider {
                        node.provider = Some(p.clone());
                    }
                    if let Some(t) = tokens_in { node.tokens_in += t; }
                    if let Some(t) = tokens_out { node.tokens_out += t; }
                }

                _ => {}
            }
        }

        // Compute depths from parent map
        let mut depth_cache: BTreeMap<String, u32> = BTreeMap::new();
        let instances: Vec<String> = nodes_map.keys().cloned().collect();
        for inst in &instances {
            let depth = compute_depth(inst, &parent_map, &mut depth_cache);
            if let Some(node) = nodes_map.get_mut(inst) {
                node.depth = depth;
            }
        }

        let nodes: Vec<AgentNode> = nodes_map.into_values().collect();

        AgentGraph { nodes, edges }
    }

    /// Return the maximum depth in the graph.
    pub fn max_depth(&self) -> u32 {
        self.nodes.iter().map(|n| n.depth).max().unwrap_or(0)
    }

    /// Return the set of unique host IDs across all agents.
    pub fn host_ids(&self) -> BTreeSet<String> {
        self.nodes.iter().map(|n| n.host_id.clone()).collect()
    }

    /// Total number of handoff edges.
    pub fn handoff_count(&self) -> u32 {
        self.edges.iter()
            .filter(|e| e.edge_type == AgentEdgeType::Handoff)
            .count() as u32
    }

    /// Total number of spawn (parent-child) edges.
    pub fn spawn_count(&self) -> u32 {
        self.edges.iter()
            .filter(|e| e.edge_type == AgentEdgeType::ParentChild)
            .count() as u32
    }
}

fn compute_depth(
    instance_id: &str,
    parent_map: &BTreeMap<String, String>,
    cache: &mut BTreeMap<String, u32>,
) -> u32 {
    if let Some(&d) = cache.get(instance_id) {
        return d;
    }
    let depth = match parent_map.get(instance_id) {
        Some(parent) => 1 + compute_depth(parent, parent_map, cache),
        None => 0,
    };
    cache.insert(instance_id.to_string(), depth);
    depth
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::session::event::*;

    fn evt(instance_id: &str, host: &str, event_type: EventType) -> SessionEvent {
        SessionEvent {
            session_id: "ssn_001".into(),
            event_id: generate_event_id(),
            timestamp: "2026-04-05T08:00:00Z".into(),
            sequence_no: 0,
            trace_id: "trace_1".into(),
            span_id: generate_span_id(),
            parent_span_id: None,
            agent_id: format!("agent://{instance_id}"),
            agent_instance_id: instance_id.into(),
            agent_name: instance_id.into(),
            agent_role: None,
            host_id: host.into(),
            tool_runtime_id: None,
            event_type,
            artifact_ref: None,
            meta: None,
        }
    }

    #[test]
    fn builds_graph_from_spawn_and_handoff() {
        let events = vec![
            evt("root", "host_a", EventType::AgentStarted {
                parent_agent_instance_id: None,
            }),
            evt("child1", "host_a", EventType::AgentSpawned {
                spawned_by_agent_instance_id: "root".into(),
                reason: Some("review code".into()),
            }),
            evt("child2", "host_b", EventType::AgentSpawned {
                spawned_by_agent_instance_id: "root".into(),
                reason: None,
            }),
            evt("root", "host_a", EventType::AgentHandoff {
                from_agent_instance_id: "root".into(),
                to_agent_instance_id: "child1".into(),
                artifacts: vec!["art_001".into()],
            }),
            evt("child1", "host_a", EventType::AgentCompleted {
                termination_reason: None,
            }),
        ];

        let graph = AgentGraph::from_events(&events);
        assert_eq!(graph.nodes.len(), 3);
        assert_eq!(graph.max_depth(), 1);
        assert_eq!(graph.handoff_count(), 1);
        assert_eq!(graph.spawn_count(), 2);
        assert_eq!(graph.host_ids().len(), 2);
    }

    #[test]
    fn nested_depth() {
        let events = vec![
            evt("root", "h", EventType::AgentStarted { parent_agent_instance_id: None }),
            evt("l1", "h", EventType::AgentSpawned { spawned_by_agent_instance_id: "root".into(), reason: None }),
            evt("l2", "h", EventType::AgentSpawned { spawned_by_agent_instance_id: "l1".into(), reason: None }),
            evt("l3", "h", EventType::AgentSpawned { spawned_by_agent_instance_id: "l2".into(), reason: None }),
        ];

        let graph = AgentGraph::from_events(&events);
        assert_eq!(graph.max_depth(), 3);
        let l3 = graph.nodes.iter().find(|n| n.agent_instance_id == "l3").unwrap();
        assert_eq!(l3.depth, 3);
    }

    /// Regression test: per-agent `tool_calls` must count every action event
    /// type the agent emits, not just `AgentCalledTool` and `AgentCompletedProcess`.
    ///
    /// Pre-v0.9.5, this counter ignored AgentReadFile, AgentWroteFile,
    /// AgentConnectedNetwork, and AgentOpenedPort. As soon as the Claude Code
    /// plugin started emitting those specialized event types (also v0.9.5),
    /// the per-agent count -- and the `nodes.reduce(...)` total used by the
    /// receipt renderer -- collapsed to near-zero even when the agent had
    /// done substantial work. The fix lives in the EventType match arm above.
    #[test]
    fn tool_calls_counts_every_action_event_type() {
        let events = vec![
            evt("a", "h", EventType::AgentStarted { parent_agent_instance_id: None }),
            evt("a", "h", EventType::AgentCalledTool {
                tool_name: "Glob".into(),
                tool_input_digest: None,
                tool_output_digest: None,
                duration_ms: None,
            }),
            evt("a", "h", EventType::AgentReadFile {
                file_path: "src/foo.rs".into(),
                digest: None,
            }),
            evt("a", "h", EventType::AgentWroteFile {
                file_path: "src/bar.rs".into(),
                digest: None,
                operation: None,
                additions: None,
                deletions: None,
            }),
            evt("a", "h", EventType::AgentCompletedProcess {
                process_name: "npm test".into(),
                exit_code: Some(0),
                duration_ms: Some(2_500),
                command: None,
            }),
            evt("a", "h", EventType::AgentConnectedNetwork {
                destination: "api.github.com".into(),
                port: None,
            }),
            evt("a", "h", EventType::AgentOpenedPort {
                port: 3000,
                protocol: Some("tcp".into()),
            }),
        ];

        let graph = AgentGraph::from_events(&events);
        let agent_a = graph.nodes.iter().find(|n| n.agent_instance_id == "a").unwrap();

        // 6 action events (Glob, ReadFile, WroteFile, CompletedProcess,
        // ConnectedNetwork, OpenedPort). AgentStarted is not an action.
        assert_eq!(
            agent_a.tool_calls, 6,
            "tool_calls must count all action event types (was {}, expected 6)",
            agent_a.tool_calls
        );
    }
}