phi-telemetry 0.7.1

Observability layer for phi-agent — collects and persists structured metrics
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
//! Structured metrics types for Agent observability.
//!
//! These types were moved from agent-base to phi-telemetry so that agent-base
//! remains a pure runtime kernel with no knowledge of metrics.

use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

// ── Outcome enums ──

/// Outcome of a single turn (one LLM interaction).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TurnOutcome {
    /// Turn completed successfully (text response, no tool calls).
    Completed,
    /// Turn ended with tool calls (agent will loop back for another turn).
    ToolCalls,
    /// Turn ended with an error.
    Error,
    /// Turn hit the max-turns safety limit.
    MaxTurns,
    /// User cancelled this turn.
    Cancelled,
}

/// Outcome of a session (the entire conversation).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SessionOutcome {
    /// Session completed normally.
    Completed,
    /// Session ended with an unrecoverable error.
    Failed,
    /// User cancelled the session.
    Cancelled,
    /// Max turns exceeded (safety limit).
    MaxTurns,
}

// ── TurnMetrics ──

/// Per-turn metrics — one per LLM interaction.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TurnMetrics {
    // Timing
    pub turn_number: u32,
    pub started_at: String, // ISO8601
    pub duration_ms: u64,

    // Latency breakdown
    pub time_to_first_token_ms: u64,
    pub llm_duration_ms: u64,
    pub tool_duration_ms: u64,

    // LLM
    pub llm_calls: u32,
    pub input_tokens: u64,
    pub output_tokens: u64,
    #[serde(default)]
    pub thinking_tokens: u64,
    /// Byte length of reasoning/thinking content (always available, even when
    /// the provider does not report reasoning token counts).
    #[serde(default)]
    pub thinking_bytes: u64,
    pub model: String,

    // Tool
    pub tool_call_count: u32,
    pub tools_used: Vec<String>,
    pub tool_success: u32,
    pub tool_failed: u32,

    // Result
    pub outcome: TurnOutcome,
    pub text_length: u64,
    pub error_message: Option<String>,
    pub has_thinking: bool,

    // Meta events
    #[serde(default)]
    pub plan_updates: u32,
    #[serde(default)]
    pub approval_count: u32,

    // User input (truncated to 80 chars)
    pub user_input: String,

    // Business extension
    #[serde(default)]
    pub custom: Value,
}

impl TurnMetrics {
    /// Create a new TurnMetrics with defaults (custom = {}).
    pub fn new(
        turn_number: u32,
        started_at: String,
        duration_ms: u64,
        model: String,
        user_input: String,
        outcome: TurnOutcome,
    ) -> Self {
        Self {
            turn_number,
            started_at,
            duration_ms,
            time_to_first_token_ms: 0,
            llm_duration_ms: 0,
            tool_duration_ms: 0,
            llm_calls: 1,
            input_tokens: 0,
            output_tokens: 0,
            thinking_tokens: 0,
            thinking_bytes: 0,
            model,
            tool_call_count: 0,
            tools_used: Vec::new(),
            tool_success: 0,
            tool_failed: 0,
            outcome,
            text_length: 0,
            error_message: None,
            has_thinking: false,
            plan_updates: 0,
            approval_count: 0,
            user_input: truncate_str(&user_input, 80),
            custom: Value::Object(serde_json::Map::new()),
        }
    }
}

// ── SessionMetrics ──

/// Accumulated session metrics. Written incrementally to `session_metrics.json`
/// at the end of each turn.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SessionMetrics {
    // Identity
    pub session_id: String,
    #[serde(default)]
    pub node_id: String,
    pub created_at: String,

    // LLM summary
    pub model: String,
    pub total_input_tokens: u64,
    pub total_output_tokens: u64,
    #[serde(default)]
    pub total_thinking_tokens: u64,
    /// Total byte length of reasoning/thinking content across all turns.
    #[serde(default)]
    pub total_thinking_bytes: u64,
    pub estimated_cost: f64,

    // Characters (always available, even without API token support)
    #[serde(default)]
    pub total_chars: u64,

    // Tool summary
    pub total_tool_calls: u32,
    pub tool_breakdown: HashMap<String, u32>,
    pub tool_fail_rate: f64,
    /// Running total of failed tool calls.
    #[serde(default)]
    pub total_failed: u32,

    // Timing
    pub total_duration_ms: u64,
    pub total_llm_ms: u64,
    pub total_tool_ms: u64,
    pub total_turns: u32,
    pub avg_turn_ms: u64,
    pub p50_turn_ms: u64,
    pub p95_turn_ms: u64,
    pub p99_turn_ms: u64,

    // Outcome
    pub outcome: SessionOutcome,
    pub error_count: u32,

    // Meta events
    #[serde(default)]
    pub total_plan_updates: u32,
    #[serde(default)]
    pub total_approvals: u32,

    // Business extension
    #[serde(default)]
    pub custom: Value,

    // Multi-agent reservation (Phase 1: always None / "default")
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent_session_id: Option<String>,
    #[serde(default = "default_session_type")]
    pub session_type: String,

    // Per-turn details
    pub turns: Vec<TurnMetrics>,
}

fn default_session_type() -> String {
    "default".to_string()
}

impl SessionMetrics {
    /// Create a new session metrics accumulator (empty turns).
    pub fn new(session_id: String, node_id: String, model: String) -> Self {
        Self {
            session_id,
            node_id,
            created_at: chrono::Utc::now().to_rfc3339(),
            model,
            total_input_tokens: 0,
            total_output_tokens: 0,
            total_thinking_tokens: 0,
            total_thinking_bytes: 0,
            estimated_cost: 0.0,
            total_chars: 0,
            total_tool_calls: 0,
            tool_breakdown: HashMap::new(),
            tool_fail_rate: 0.0,
            total_failed: 0,
            total_duration_ms: 0,
            total_llm_ms: 0,
            total_tool_ms: 0,
            total_turns: 0,
            avg_turn_ms: 0,
            p50_turn_ms: 0,
            p95_turn_ms: 0,
            p99_turn_ms: 0,
            outcome: SessionOutcome::Completed,
            error_count: 0,
            total_plan_updates: 0,
            total_approvals: 0,
            custom: Value::Object(serde_json::Map::new()),
            parent_session_id: None,
            session_type: "default".to_string(),
            turns: Vec::new(),
        }
    }

    /// Append a turn and recompute session-level aggregates.
    pub fn append_turn(&mut self, turn: TurnMetrics) {
        self.total_turns += 1;
        self.total_input_tokens += turn.input_tokens;
        self.total_output_tokens += turn.output_tokens;
        self.total_thinking_tokens += turn.thinking_tokens;
        self.total_thinking_bytes += turn.thinking_bytes;
        self.total_chars += turn.text_length;
        self.total_duration_ms += turn.duration_ms;
        self.total_llm_ms += turn.llm_duration_ms;
        self.total_tool_ms += turn.tool_duration_ms;
        self.total_tool_calls += turn.tool_call_count;

        // Tool breakdown
        for tool_name in &turn.tools_used {
            *self.tool_breakdown.entry(tool_name.clone()).or_insert(0) += 1;
        }

        // Tool fail rate (incremental — O(1) per turn)
        self.total_failed += turn.tool_failed;
        if self.total_tool_calls > 0 {
            self.tool_fail_rate = self.total_failed as f64 / self.total_tool_calls as f64;
        }

        // Error count
        if matches!(turn.outcome, TurnOutcome::Error) {
            self.error_count += 1;
        }

        // Meta events
        self.total_plan_updates += turn.plan_updates;
        self.total_approvals += turn.approval_count;

        // Average turn duration
        self.avg_turn_ms = self.total_duration_ms / self.total_turns as u64;

        // Update model to the most frequently used one
        {
            let mut model_counts: HashMap<String, u32> = HashMap::new();
            for t in &self.turns {
                if !t.model.is_empty() {
                    *model_counts.entry(t.model.clone()).or_insert(0) += 1;
                }
            }
            if !turn.model.is_empty() {
                *model_counts.entry(turn.model.clone()).or_insert(0) += 1;
            }
            if let Some(top_model) = model_counts
                .into_iter()
                .max_by_key(|(_, count)| *count)
                .map(|(m, _)| m)
            {
                self.model = top_model;
            }
        }

        // Percentiles
        self.turns.push(turn);
        self.recompute_percentiles();
    }

    /// Recompute P50/P95/P99 from stored turn durations.
    fn recompute_percentiles(&mut self) {
        if self.turns.is_empty() {
            self.p50_turn_ms = 0;
            self.p95_turn_ms = 0;
            self.p99_turn_ms = 0;
            return;
        }

        let mut durations: Vec<u64> = self.turns.iter().map(|t| t.duration_ms).collect();
        durations.sort_unstable();

        self.p50_turn_ms = percentile_from_sorted(&durations, 50.0);
        self.p95_turn_ms = percentile_from_sorted(&durations, 95.0);
        self.p99_turn_ms = percentile_from_sorted(&durations, 99.0);
    }

    /// Finalize the session — recompute percentiles and set outcome.
    pub fn finalize(&mut self, outcome: SessionOutcome) {
        self.outcome = outcome;
        self.recompute_percentiles();
    }

    /// Merge another accumulator's per-turn records into this one and rebuild
    /// every session-level aggregate from the merged list.
    ///
    /// Turns are deduplicated on `(turn_number, started_at)`, so the union is
    /// idempotent: re-saving the same turns from the same process changes
    /// nothing, while turns recorded by another writer over the same session
    /// (a TUI session switch, a new process resuming it) are folded in instead
    /// of clobbering the history. Identity/custom fields and `outcome` keep
    /// `self`'s values — the caller decides whose identity and final state win.
    pub fn merge_turns(&mut self, other: &SessionMetrics) {
        let known: std::collections::HashSet<(u32, String)> = self
            .turns
            .iter()
            .map(|t| (t.turn_number, t.started_at.clone()))
            .collect();
        for t in &other.turns {
            if known.contains(&(t.turn_number, t.started_at.clone())) {
                continue;
            }
            self.turns.push(t.clone());
        }
        self.turns.sort_by(|a, b| {
            a.started_at
                .cmp(&b.started_at)
                .then(a.turn_number.cmp(&b.turn_number))
        });
        self.rebuild_aggregates();
    }

    /// Recompute all incremental aggregates from scratch by replaying
    /// `append_turn` over the stored turns (every total it maintains is a
    /// function of the turn list).
    fn rebuild_aggregates(&mut self) {
        self.total_input_tokens = 0;
        self.total_output_tokens = 0;
        self.total_thinking_tokens = 0;
        self.total_thinking_bytes = 0;
        self.total_chars = 0;
        self.total_duration_ms = 0;
        self.total_llm_ms = 0;
        self.total_tool_ms = 0;
        self.total_tool_calls = 0;
        self.tool_breakdown.clear();
        self.total_failed = 0;
        self.tool_fail_rate = 0.0;
        self.error_count = 0;
        self.total_plan_updates = 0;
        self.total_approvals = 0;
        self.total_turns = 0;
        self.avg_turn_ms = 0;
        self.model = String::new();

        let turns = std::mem::take(&mut self.turns);
        for t in turns {
            self.append_turn(t);
        }
    }
}

// ── Summary for CLI listing ──

/// Lightweight summary returned by `list_all()`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SessionSummary {
    pub session_id: String,
    pub node_id: String,
    pub created_at: String,
    pub model: String,
    pub total_turns: u32,
    pub total_chars: u64,
    pub outcome: SessionOutcome,
    /// Product name from custom field, if set (e.g. "phi-bard").
    pub product: Option<String>,
}

// ── Helpers ──

/// Compute the `p`-th percentile from an already-sorted slice of values.
pub(crate) fn percentile_from_sorted(sorted: &[u64], p: f64) -> u64 {
    if sorted.is_empty() {
        return 0;
    }
    let n = sorted.len() as f64;
    let idx = ((p / 100.0) * (n - 1.0)).round() as usize;
    sorted[idx.min(sorted.len() - 1)]
}

/// Truncate a string to `max_chars` characters, appending "..." if truncated.
pub(crate) fn truncate_str(s: &str, max_chars: usize) -> String {
    if s.chars().count() > max_chars {
        let truncated: String = s.chars().take(max_chars).collect();
        format!("{}...", truncated)
    } else {
        s.to_string()
    }
}

// ── Conversion from agent-base ──

/// Convert an agent-base `RunOutcome` to a turn-level `TurnOutcome`.
/// Checks `tools_used` to distinguish `ToolCalls` from `Completed`.
pub fn run_outcome_to_turn_outcome(
    outcome: &agent_base::RunOutcome,
    tools_used: &[String],
) -> TurnOutcome {
    match outcome {
        agent_base::RunOutcome::Completed => {
            if tools_used.is_empty() {
                TurnOutcome::Completed
            } else {
                TurnOutcome::ToolCalls
            }
        }
        // Continuing means the guard nudged — treat as a completed turn
        // (the run will loop, but this turn is done).
        agent_base::RunOutcome::Continuing => TurnOutcome::Completed,
        agent_base::RunOutcome::Failed { .. } => TurnOutcome::Error,
        agent_base::RunOutcome::Cancelled => TurnOutcome::Cancelled,
        agent_base::RunOutcome::MaxTurnsExceeded { .. } => TurnOutcome::MaxTurns,
    }
}

/// Convert agent-base `RunOutcome` to `SessionOutcome`.
pub fn run_outcome_to_session_outcome(outcome: &agent_base::RunOutcome) -> SessionOutcome {
    match outcome {
        agent_base::RunOutcome::Completed => SessionOutcome::Completed,
        agent_base::RunOutcome::Continuing => SessionOutcome::Completed,
        agent_base::RunOutcome::Failed { .. } => SessionOutcome::Failed,
        agent_base::RunOutcome::Cancelled => SessionOutcome::Cancelled,
        agent_base::RunOutcome::MaxTurnsExceeded { .. } => SessionOutcome::MaxTurns,
    }
}

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

    #[test]
    fn test_truncate_str() {
        assert_eq!(truncate_str("hello", 10), "hello");
        assert_eq!(
            truncate_str("hello world this is long", 10),
            "hello worl..."
        );
        assert_eq!(truncate_str("你好世界测试文本", 4), "你好世界...");
    }

    #[test]
    fn test_percentile_from_sorted() {
        let data = vec![10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
        assert_eq!(percentile_from_sorted(&data, 50.0), 60);
        assert_eq!(percentile_from_sorted(&data, 95.0), 100);
        assert_eq!(percentile_from_sorted(&data, 0.0), 10);
        assert_eq!(percentile_from_sorted(&data, 100.0), 100);
    }

    #[test]
    fn test_percentile_empty() {
        assert_eq!(percentile_from_sorted(&[], 50.0), 0);
    }

    /// Helper: one turn with the given number/timestamp/duration/model.
    fn turn(n: u32, at: &str, dur: u64, model: &str) -> TurnMetrics {
        let mut t = TurnMetrics::new(
            n,
            at.to_string(),
            dur,
            model.to_string(),
            "input".to_string(),
            TurnOutcome::Completed,
        );
        t.input_tokens = 100;
        t.output_tokens = 10;
        t
    }

    #[test]
    fn merge_turns_unions_disjoint_writers_and_rebuilds_totals() {
        let mut base = SessionMetrics::new("s".into(), "".into(), "m1".into());
        base.append_turn(turn(1, "2026-08-01T12:00:00Z", 1000, "m1"));
        // A second writer recorded two different turns (e.g. after a resume).
        let mut other = SessionMetrics::new("s".into(), "".into(), "m2".into());
        other.append_turn(turn(2, "2026-08-01T12:01:00Z", 2000, "m2"));
        other.append_turn(turn(3, "2026-08-01T12:02:00Z", 3000, "m2"));

        base.merge_turns(&other);

        assert_eq!(base.total_turns, 3);
        assert_eq!(base.turns.len(), 3);
        // Turns are ordered by time regardless of which writer recorded them.
        assert_eq!(
            base.turns.iter().map(|t| t.turn_number).collect::<Vec<_>>(),
            vec![1, 2, 3]
        );
        // Aggregates rebuilt over the union.
        assert_eq!(base.total_input_tokens, 300);
        assert_eq!(base.total_output_tokens, 30);
        assert_eq!(base.total_duration_ms, 6000);
        assert_eq!(base.avg_turn_ms, 2000);
        // Model = most frequent across merged turns (2×m2 beats 1×m1).
        assert_eq!(base.model, "m2");
    }

    #[test]
    fn merge_turns_dedupes_on_turn_number_and_started_at() {
        let mut base = SessionMetrics::new("s".into(), "".into(), "m1".into());
        base.append_turn(turn(1, "2026-08-01T12:00:00Z", 1000, "m1"));
        let before = base.clone();

        // Re-merging the same turns (same process re-saving) must be a no-op.
        base.merge_turns(&before);
        assert_eq!(base.total_turns, 1);
        assert_eq!(base.total_input_tokens, 100);

        // Same turn_number but a different timestamp is a different turn —
        // two processes can both record "turn 1" of the same session.
        let mut fresh = SessionMetrics::new("s".into(), "".into(), "m1".into());
        fresh.append_turn(turn(1, "2026-08-02T09:00:00Z", 500, "m1"));
        base.merge_turns(&fresh);
        assert_eq!(base.total_turns, 2);
        assert_eq!(base.total_duration_ms, 1500);
    }

    #[test]
    fn merge_turns_preserves_identity_and_outcome() {
        let mut base = SessionMetrics::new("s-old".into(), "node-9".into(), "m1".into());
        base.custom = serde_json::json!({"product": "phimint"});
        base.outcome = SessionOutcome::Failed;
        base.append_turn(turn(1, "2026-08-01T12:00:00Z", 1000, "m1"));

        let mut other = SessionMetrics::new("s-new".into(), "node-x".into(), "m2".into());
        other.outcome = SessionOutcome::Completed;
        other.append_turn(turn(2, "2026-08-01T12:01:00Z", 2000, "m2"));

        base.merge_turns(&other);

        // Identity/custom/outcome keep `self`'s values — save_metrics grants
        // the writer's outcome explicitly after merging.
        assert_eq!(base.session_id, "s-old");
        assert_eq!(base.node_id, "node-9");
        assert_eq!(base.custom, serde_json::json!({"product": "phimint"}));
        assert_eq!(base.outcome, SessionOutcome::Failed);
    }

    #[test]
    fn test_session_metrics_new() {
        let m = SessionMetrics::new(
            "20260729_test".to_string(),
            "".to_string(),
            "claude-sonnet".to_string(),
        );
        assert_eq!(m.session_id, "20260729_test");
        assert_eq!(m.node_id, "");
        assert_eq!(m.model, "claude-sonnet");
        assert_eq!(m.total_turns, 0);
        assert_eq!(m.parent_session_id, None);
        assert_eq!(m.session_type, "default");
        assert!(m.turns.is_empty());
    }

    #[test]
    fn test_session_metrics_append_turn() {
        let mut m = SessionMetrics::new(
            "test".to_string(),
            "".to_string(),
            "claude-sonnet".to_string(),
        );
        let turn = TurnMetrics {
            turn_number: 1,
            started_at: "2026-07-29T00:00:00Z".to_string(),
            duration_ms: 1000,
            time_to_first_token_ms: 200,
            llm_duration_ms: 800,
            tool_duration_ms: 100,
            llm_calls: 1,
            input_tokens: 500,
            output_tokens: 300,
            thinking_tokens: 0,
            thinking_bytes: 0,
            model: "claude-sonnet".to_string(),
            tool_call_count: 1,
            tools_used: vec!["shell".to_string()],
            tool_success: 1,
            tool_failed: 0,
            outcome: TurnOutcome::ToolCalls,
            text_length: 200,
            error_message: None,
            has_thinking: true,
            plan_updates: 0,
            approval_count: 0,
            user_input: "test input".to_string(),
            custom: Value::Object(serde_json::Map::new()),
        };
        m.append_turn(turn);
        assert_eq!(m.total_turns, 1);
        assert_eq!(m.total_input_tokens, 500);
        assert_eq!(m.total_output_tokens, 300);
        assert_eq!(m.total_duration_ms, 1000);
        assert_eq!(m.total_tool_calls, 1);
        assert_eq!(m.tool_breakdown.get("shell"), Some(&1));
        assert_eq!(m.tool_fail_rate, 0.0);
        assert_eq!(m.avg_turn_ms, 1000);
        assert_eq!(m.p50_turn_ms, 1000);
    }

    #[test]
    fn test_session_metrics_append_multiple_turns() {
        let mut m = SessionMetrics::new(
            "test".to_string(),
            "".to_string(),
            "claude-sonnet".to_string(),
        );
        for i in 1..=5 {
            let turn = TurnMetrics {
                turn_number: i,
                started_at: "2026-07-29T00:00:00Z".to_string(),
                duration_ms: i as u64 * 1000,
                time_to_first_token_ms: 200,
                llm_duration_ms: 800,
                tool_duration_ms: 100,
                llm_calls: 1,
                input_tokens: 500,
                output_tokens: 300,
                thinking_tokens: 0,
                thinking_bytes: 0,
                model: "claude-sonnet".to_string(),
                tool_call_count: 1,
                tools_used: vec!["shell".to_string()],
                tool_success: 1,
                tool_failed: 0,
                outcome: TurnOutcome::ToolCalls,
                text_length: 200,
                error_message: None,
                has_thinking: true,
                plan_updates: 0,
                approval_count: 0,
                user_input: "test".to_string(),
                custom: Value::Object(serde_json::Map::new()),
            };
            m.append_turn(turn);
        }
        assert_eq!(m.total_turns, 5);
        assert_eq!(m.total_duration_ms, 15000);
        assert_eq!(m.avg_turn_ms, 3000);
        assert_eq!(m.p50_turn_ms, 3000);
    }

    #[test]
    fn test_session_metrics_thinking_bytes_accumulation() {
        let mut m = SessionMetrics::new(
            "test".to_string(),
            "".to_string(),
            "mimo-v2.5-pro".to_string(),
        );

        // Turn 1: has thinking content (43 bytes), provider reports 0 tokens
        let turn1 = TurnMetrics {
            turn_number: 1,
            started_at: "2026-07-29T00:00:00Z".to_string(),
            duration_ms: 1000,
            time_to_first_token_ms: 200,
            llm_duration_ms: 800,
            tool_duration_ms: 0,
            llm_calls: 1,
            input_tokens: 5000,
            output_tokens: 80,
            thinking_tokens: 0,
            thinking_bytes: 43,
            model: "mimo-v2.5-pro".to_string(),
            tool_call_count: 0,
            tools_used: vec![],
            tool_success: 0,
            tool_failed: 0,
            outcome: TurnOutcome::Completed,
            text_length: 100,
            error_message: None,
            has_thinking: true,
            plan_updates: 0,
            approval_count: 0,
            user_input: "test".to_string(),
            custom: Value::Object(serde_json::Map::new()),
        };
        m.append_turn(turn1);

        // Turn 2: more thinking content (86 bytes)
        let turn2 = TurnMetrics {
            turn_number: 2,
            started_at: "2026-07-29T00:00:01Z".to_string(),
            duration_ms: 1200,
            time_to_first_token_ms: 150,
            llm_duration_ms: 900,
            tool_duration_ms: 0,
            llm_calls: 1,
            input_tokens: 7000,
            output_tokens: 131,
            thinking_tokens: 0,
            thinking_bytes: 86,
            model: "mimo-v2.5-pro".to_string(),
            tool_call_count: 0,
            tools_used: vec![],
            tool_success: 0,
            tool_failed: 0,
            outcome: TurnOutcome::Completed,
            text_length: 200,
            error_message: None,
            has_thinking: true,
            plan_updates: 0,
            approval_count: 0,
            user_input: "test".to_string(),
            custom: Value::Object(serde_json::Map::new()),
        };
        m.append_turn(turn2);

        // thinking_tokens stays 0 (provider never reported), but bytes accumulate
        assert_eq!(m.total_thinking_tokens, 0);
        assert_eq!(m.total_thinking_bytes, 129); // 43 + 86
        assert_eq!(m.total_turns, 2);
    }

    #[test]
    fn test_turn_metrics_thinking_bytes_default() {
        let turn = TurnMetrics::new(
            1,
            "2026-07-29T00:00:00Z".to_string(),
            1000,
            "mimo-v2.5-pro".to_string(),
            "test".to_string(),
            TurnOutcome::Completed,
        );
        assert_eq!(turn.thinking_bytes, 0);
        assert_eq!(turn.thinking_tokens, 0);
    }

    #[test]
    fn test_session_metrics_backward_compat_thinking_bytes() {
        // Old JSON without thinking_bytes should deserialize with default 0
        let old_json = r#"{
            "session_id": "test",
            "node_id": "",
            "created_at": "2026-07-29T00:00:00Z",
            "model": "mimo-v2.5-pro",
            "total_input_tokens": 100,
            "total_output_tokens": 50,
            "total_thinking_tokens": 0,
            "estimated_cost": 0.0,
            "total_chars": 100,
            "total_tool_calls": 0,
            "tool_breakdown": {},
            "tool_fail_rate": 0.0,
            "total_duration_ms": 1000,
            "total_llm_ms": 800,
            "total_tool_ms": 0,
            "total_turns": 1,
            "avg_turn_ms": 1000,
            "p50_turn_ms": 1000,
            "p95_turn_ms": 1000,
            "p99_turn_ms": 1000,
            "outcome": "completed",
            "error_count": 0,
            "custom": {},
            "turns": []
        }"#;
        let m: SessionMetrics = serde_json::from_str(old_json).unwrap();
        assert_eq!(m.total_thinking_bytes, 0);
        assert_eq!(m.total_thinking_tokens, 0);
    }

    #[test]
    fn test_session_metrics_finalize() {
        let mut m = SessionMetrics::new(
            "test".to_string(),
            "".to_string(),
            "claude-sonnet".to_string(),
        );
        m.finalize(SessionOutcome::Completed);
        assert_eq!(m.outcome, SessionOutcome::Completed);
    }

    #[test]
    fn test_session_metrics_json_roundtrip() {
        let m = SessionMetrics::new(
            "20260729_test".to_string(),
            "node-1".to_string(),
            "claude-sonnet".to_string(),
        );
        let json = serde_json::to_string(&m).unwrap();
        let m2: SessionMetrics = serde_json::from_str(&json).unwrap();
        assert_eq!(m2.session_id, "20260729_test");
        assert_eq!(m2.node_id, "node-1");
        assert_eq!(m2.parent_session_id, None);
        assert_eq!(m2.session_type, "default");
    }

    #[test]
    fn test_session_metrics_backward_compat() {
        let old_json = r#"{
            "session_id": "test",
            "node_id": "",
            "created_at": "2026-07-29T00:00:00Z",
            "model": "claude-sonnet",
            "total_input_tokens": 0,
            "total_output_tokens": 0,
            "estimated_cost": 0.0,
            "total_chars": 0,
            "total_tool_calls": 0,
            "tool_breakdown": {},
            "tool_fail_rate": 0.0,
            "total_duration_ms": 0,
            "total_llm_ms": 0,
            "total_tool_ms": 0,
            "total_turns": 0,
            "avg_turn_ms": 0,
            "p50_turn_ms": 0,
            "p95_turn_ms": 0,
            "p99_turn_ms": 0,
            "outcome": "completed",
            "error_count": 0,
            "custom": {},
            "turns": []
        }"#;
        let m: SessionMetrics = serde_json::from_str(old_json).unwrap();
        assert_eq!(m.parent_session_id, None);
        assert_eq!(m.session_type, "default");
    }

    #[test]
    fn test_turn_metrics_custom_default() {
        let turn = TurnMetrics::new(
            1,
            "2026-07-29T00:00:00Z".to_string(),
            1000,
            "claude-sonnet".to_string(),
            "hello world".to_string(),
            TurnOutcome::Completed,
        );
        assert_eq!(turn.custom, Value::Object(serde_json::Map::new()));
        assert_eq!(turn.user_input, "hello world");
        let turn_long = TurnMetrics::new(
            1,
            "2026-07-29T00:00:00Z".to_string(),
            1000,
            "claude-sonnet".to_string(),
            "this is a very long user input that should definitely be truncated at eighty characters because that's the max we allow for storage".to_string(),
            TurnOutcome::Completed,
        );
        assert!(turn_long.user_input.chars().count() <= 83);
        assert!(turn_long.user_input.ends_with("..."));
    }

    #[test]
    fn test_run_outcome_conversion() {
        use agent_base::RunOutcome;

        // Completed with no tools → TurnOutcome::Completed
        assert_eq!(
            run_outcome_to_turn_outcome(&RunOutcome::Completed, &[]),
            TurnOutcome::Completed
        );

        // Completed with tools → TurnOutcome::ToolCalls
        assert_eq!(
            run_outcome_to_turn_outcome(&RunOutcome::Completed, &["shell".to_string()]),
            TurnOutcome::ToolCalls
        );

        // Failed → Error
        assert_eq!(
            run_outcome_to_turn_outcome(
                &RunOutcome::Failed {
                    error: "oops".to_string()
                },
                &[]
            ),
            TurnOutcome::Error
        );

        // Cancelled → Cancelled
        assert_eq!(
            run_outcome_to_turn_outcome(&RunOutcome::Cancelled, &[]),
            TurnOutcome::Cancelled
        );
    }
}