axon-lang 1.38.5

AXON v1.5.1 — first crates.io publication of the AXON language full-stack runtime. Lexer/parser/type-checker/IR generator (re-exported from axon-frontend) plus the native Rust runtime: typed channels (TypedEventBus with QoS×5, π-calculus mobility, capability extrusion via shield D8 — Fase 13.f.2), Free Monad CPS handlers (Fase 2), lease kernel + reconcile loop (Fase 3+5), Epistemic Security Kernel (ESK Fase 6), Trust Types + ReplayLog (Fase 11.a+11.c), Stateful PEM over WebSocket (Fase 11.d), Ontological Tool Synthesis (Fase 11.e), Mobile Typed Channels (Fase 13). Crate publishes as `axon-lang` to mirror the Python PyPI package; library import remains `use axon::*` so existing call sites keep working unchanged.
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
//! Execution Replay — reconstruct and analyze recorded traces.
//!
//! Reads `.trace.json` files (produced by `axon run --trace`) and provides:
//!   - Structured timeline reconstruction
//!   - Per-step result extraction
//!   - Anchor pass/breach summary
//!   - Regression comparison between two traces
//!
//! Usage:
//!   axon replay trace.json                   — replay a single trace
//!   axon replay trace.json --json            — structured JSON output
//!   axon replay old.trace.json new.trace.json — regression comparison
//!
//! Exit codes:
//!   0 — replay successful (or traces match for regression)
//!   1 — regression differences detected
//!   2 — I/O or parse error

use std::collections::HashMap;
use std::io::IsTerminal;

// ── Replay structures ────────────────────────────────────────────────────

/// A reconstructed execution from a trace file.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ReplayTrace {
    pub meta: TraceMeta,
    pub units: Vec<ReplayUnit>,
    pub summary: ReplaySummary,
}

/// Trace metadata from the _meta header.
#[derive(Debug, Clone, serde::Serialize)]
pub struct TraceMeta {
    pub source: String,
    pub backend: String,
    pub tool_mode: String,
    pub axon_version: String,
    pub mode: String,
}

/// A reconstructed execution unit.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ReplayUnit {
    pub flow_name: String,
    pub steps: Vec<ReplayStep>,
    pub duration_ms: u64,
    pub total_input_tokens: u64,
    pub total_output_tokens: u64,
    pub anchor_breaches: u32,
}

/// A reconstructed step from trace events.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ReplayStep {
    pub name: String,
    pub event_type: String,
    pub output: String,
    pub success: bool,
    pub anchor_results: Vec<AnchorEvent>,
    pub was_retried: bool,
}

/// Anchor pass/breach event.
#[derive(Debug, Clone, serde::Serialize)]
pub struct AnchorEvent {
    pub anchor_name: String,
    pub passed: bool,
    pub detail: String,
}

/// Summary of a replayed trace.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ReplaySummary {
    pub total_units: usize,
    pub total_steps: usize,
    pub total_anchor_passes: usize,
    pub total_anchor_breaches: usize,
    pub total_retries: usize,
    pub total_errors: usize,
    pub total_input_tokens: u64,
    pub total_output_tokens: u64,
}

/// Regression diff between two replayed traces.
#[derive(Debug, Clone, serde::Serialize)]
pub struct RegressionDiff {
    pub identical: bool,
    pub step_diffs: Vec<StepRegression>,
    pub summary: RegressionSummary,
}

/// Regression diff for a single step.
#[derive(Debug, Clone, serde::Serialize)]
pub struct StepRegression {
    pub unit: String,
    pub step: String,
    pub status: RegressionStatus,
    pub old_output: String,
    pub new_output: String,
}

/// Regression status for a step.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum RegressionStatus {
    /// Output matches.
    Match,
    /// Output differs.
    Changed,
    /// Step only in old trace.
    Removed,
    /// Step only in new trace.
    Added,
}

/// Summary of regression comparison.
#[derive(Debug, Clone, serde::Serialize)]
pub struct RegressionSummary {
    pub total_steps: usize,
    pub matched: usize,
    pub changed: usize,
    pub added: usize,
    pub removed: usize,
}

// ── Trace parsing ────────────────────────────────────────────────────────

/// Parse a trace JSON value into a structured ReplayTrace.
pub fn parse_trace(data: &serde_json::Value) -> ReplayTrace {
    let meta = parse_meta(data);
    let events = data["events"]
        .as_array()
        .cloned()
        .unwrap_or_default();

    let units = reconstruct_units(&events);

    let mut summary = ReplaySummary {
        total_units: units.len(),
        total_steps: 0,
        total_anchor_passes: 0,
        total_anchor_breaches: 0,
        total_retries: 0,
        total_errors: 0,
        total_input_tokens: 0,
        total_output_tokens: 0,
    };

    for u in &units {
        summary.total_steps += u.steps.len();
        summary.total_input_tokens += u.total_input_tokens;
        summary.total_output_tokens += u.total_output_tokens;
        summary.total_anchor_breaches += u.anchor_breaches as usize;
        for s in &u.steps {
            summary.total_anchor_passes += s.anchor_results.iter().filter(|a| a.passed).count();
            summary.total_anchor_breaches += s.anchor_results.iter().filter(|a| !a.passed).count();
            if s.was_retried {
                summary.total_retries += 1;
            }
            if !s.success {
                summary.total_errors += 1;
            }
        }
    }

    ReplayTrace {
        meta,
        units,
        summary,
    }
}

fn parse_meta(data: &serde_json::Value) -> TraceMeta {
    let meta = &data["_meta"];
    TraceMeta {
        source: meta["source"].as_str().unwrap_or("").to_string(),
        backend: meta["backend"].as_str().unwrap_or("").to_string(),
        tool_mode: meta["tool_mode"].as_str().unwrap_or("").to_string(),
        axon_version: meta["axon_version"].as_str().unwrap_or("").to_string(),
        mode: meta["mode"].as_str().unwrap_or("").to_string(),
    }
}

fn reconstruct_units(events: &[serde_json::Value]) -> Vec<ReplayUnit> {
    let mut units: Vec<ReplayUnit> = Vec::new();
    let mut current_unit: Option<ReplayUnit> = None;
    let mut current_step_anchors: Vec<AnchorEvent> = Vec::new();
    let mut current_step_retried = false;

    for event in events {
        let etype = event["event"]
            .as_str()
            .or_else(|| event["type"].as_str())
            .unwrap_or("");
        let unit_name = event["unit"].as_str().unwrap_or("");
        let step_name = event["step"].as_str().unwrap_or("");
        let detail = event["detail"].as_str().unwrap_or("");

        match etype {
            "unit_start" => {
                if let Some(u) = current_unit.take() {
                    units.push(u);
                }
                current_unit = Some(ReplayUnit {
                    flow_name: unit_name.to_string(),
                    steps: Vec::new(),
                    duration_ms: 0,
                    total_input_tokens: 0,
                    total_output_tokens: 0,
                    anchor_breaches: 0,
                });
                current_step_anchors.clear();
                current_step_retried = false;
            }
            "unit_complete" => {
                if let Some(u) = current_unit.take() {
                    units.push(u);
                }
            }
            "step_complete" | "step_stub" | "tool_native" | "step_parallel" => {
                if let Some(ref mut u) = current_unit {
                    let success = etype != "step_error";
                    u.steps.push(ReplayStep {
                        name: step_name.to_string(),
                        event_type: etype.to_string(),
                        output: detail.to_string(),
                        success,
                        anchor_results: std::mem::take(&mut current_step_anchors),
                        was_retried: current_step_retried,
                    });
                    current_step_retried = false;
                }
            }
            "step_error" => {
                if let Some(ref mut u) = current_unit {
                    u.steps.push(ReplayStep {
                        name: step_name.to_string(),
                        event_type: etype.to_string(),
                        output: detail.to_string(),
                        success: false,
                        anchor_results: std::mem::take(&mut current_step_anchors),
                        was_retried: current_step_retried,
                    });
                    current_step_retried = false;
                }
            }
            "anchor_pass" => {
                current_step_anchors.push(AnchorEvent {
                    anchor_name: extract_anchor_name(detail),
                    passed: true,
                    detail: detail.to_string(),
                });
            }
            "anchor_breach" => {
                current_step_anchors.push(AnchorEvent {
                    anchor_name: extract_anchor_name(detail),
                    passed: false,
                    detail: detail.to_string(),
                });
                if let Some(ref mut u) = current_unit {
                    u.anchor_breaches += 1;
                }
            }
            "retry_attempt" => {
                current_step_retried = true;
            }
            "hook_unit_metrics" => {
                if let Some(ref mut u) = current_unit.as_mut().or_else(|| units.last_mut()) {
                    // Parse: "duration=123ms, steps=2, tokens_in=500, tokens_out=200, ..."
                    for part in detail.split(", ") {
                        if let Some(val) = part.strip_prefix("duration=").and_then(|s| s.strip_suffix("ms")) {
                            u.duration_ms = val.parse().unwrap_or(0);
                        } else if let Some(val) = part.strip_prefix("tokens_in=") {
                            u.total_input_tokens = val.parse().unwrap_or(0);
                        } else if let Some(val) = part.strip_prefix("tokens_out=") {
                            u.total_output_tokens = val.parse().unwrap_or(0);
                        }
                    }
                }
            }
            // Session events create synthetic steps
            e if e.starts_with("session_") => {
                if let Some(ref mut u) = current_unit {
                    u.steps.push(ReplayStep {
                        name: step_name.to_string(),
                        event_type: etype.to_string(),
                        output: detail.to_string(),
                        success: true,
                        anchor_results: Vec::new(),
                        was_retried: false,
                    });
                }
            }
            _ => {} // wave_start, step_deps, schedule, etc. — metadata only
        }
    }

    // Push final unit if still open
    if let Some(u) = current_unit {
        units.push(u);
    }

    units
}

fn extract_anchor_name(detail: &str) -> String {
    // Format: "AnchorName: 0.95" or "AnchorName: 0.50, reason=..."
    detail.split(':').next().unwrap_or("").trim().to_string()
}

// ── Regression comparison ────────────────────────────────────────────────

/// Compare two replayed traces for regression testing.
pub fn compare_traces(old: &ReplayTrace, new: &ReplayTrace) -> RegressionDiff {
    let mut step_diffs = Vec::new();

    // Build step output maps: (unit, step) → output
    let old_map = build_step_map(old);
    let new_map = build_step_map(new);

    let mut all_keys: Vec<(String, String)> = old_map
        .keys()
        .chain(new_map.keys())
        .cloned()
        .collect::<std::collections::HashSet<_>>()
        .into_iter()
        .collect();
    all_keys.sort();

    for key in &all_keys {
        let old_val = old_map.get(key);
        let new_val = new_map.get(key);

        let (status, old_output, new_output) = match (old_val, new_val) {
            (Some(o), Some(n)) => {
                if o == n {
                    (RegressionStatus::Match, o.clone(), n.clone())
                } else {
                    (RegressionStatus::Changed, o.clone(), n.clone())
                }
            }
            (Some(o), None) => (RegressionStatus::Removed, o.clone(), String::new()),
            (None, Some(n)) => (RegressionStatus::Added, String::new(), n.clone()),
            (None, None) => continue,
        };

        step_diffs.push(StepRegression {
            unit: key.0.clone(),
            step: key.1.clone(),
            status,
            old_output,
            new_output,
        });
    }

    let matched = step_diffs.iter().filter(|d| d.status == RegressionStatus::Match).count();
    let changed = step_diffs.iter().filter(|d| d.status == RegressionStatus::Changed).count();
    let added = step_diffs.iter().filter(|d| d.status == RegressionStatus::Added).count();
    let removed = step_diffs.iter().filter(|d| d.status == RegressionStatus::Removed).count();
    let identical = changed == 0 && added == 0 && removed == 0;
    let total_steps = step_diffs.len();

    RegressionDiff {
        identical,
        step_diffs,
        summary: RegressionSummary {
            total_steps,
            matched,
            changed,
            added,
            removed,
        },
    }
}

fn build_step_map(trace: &ReplayTrace) -> HashMap<(String, String), String> {
    let mut map = HashMap::new();
    for u in &trace.units {
        for s in &u.steps {
            map.insert(
                (u.flow_name.clone(), s.name.clone()),
                s.output.clone(),
            );
        }
    }
    map
}

// ── CLI entry point ──────────────────────────────────────────────────────

/// Run the replay command. Returns exit code.
pub fn run_replay(file: &str, compare_file: Option<&str>, json_output: bool) -> i32 {
    let use_color = !json_output && std::io::stdout().is_terminal();

    // Read primary trace
    let content = match std::fs::read_to_string(file) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("Cannot read '{}': {e}", file);
            return 2;
        }
    };
    let data: serde_json::Value = match serde_json::from_str(&content) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("Invalid JSON in '{}': {e}", file);
            return 2;
        }
    };

    let trace = parse_trace(&data);

    // If comparison file provided, do regression
    if let Some(cmp_file) = compare_file {
        let cmp_content = match std::fs::read_to_string(cmp_file) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("Cannot read '{}': {e}", cmp_file);
                return 2;
            }
        };
        let cmp_data: serde_json::Value = match serde_json::from_str(&cmp_content) {
            Ok(v) => v,
            Err(e) => {
                eprintln!("Invalid JSON in '{}': {e}", cmp_file);
                return 2;
            }
        };

        let cmp_trace = parse_trace(&cmp_data);
        let regression = compare_traces(&trace, &cmp_trace);

        if json_output {
            println!("{}", serde_json::to_string_pretty(&regression).unwrap());
        } else {
            print_regression(&regression, file, cmp_file, use_color);
        }

        return if regression.identical { 0 } else { 1 };
    }

    // Single trace replay
    if json_output {
        println!("{}", serde_json::to_string_pretty(&trace).unwrap());
    } else {
        print_replay(&trace, file, use_color);
    }

    0
}

// ── Human-readable output ────────────────────────────────────────────────

fn print_replay(trace: &ReplayTrace, file: &str, use_color: bool) {
    let bold = |s: &str| if use_color { format!("\x1b[1m{s}\x1b[0m") } else { s.to_string() };
    let dim = |s: &str| if use_color { format!("\x1b[2m{s}\x1b[0m") } else { s.to_string() };
    let green = |s: &str| if use_color { format!("\x1b[32m{s}\x1b[0m") } else { s.to_string() };
    let red = |s: &str| if use_color { format!("\x1b[31m{s}\x1b[0m") } else { s.to_string() };
    let cyan = |s: &str| if use_color { format!("\x1b[36m{s}\x1b[0m") } else { s.to_string() };
    let yellow = |s: &str| if use_color { format!("\x1b[33m{s}\x1b[0m") } else { s.to_string() };

    println!("{} {}", bold("Replay:"), dim(file));
    println!(
        "  {} source={}, backend={}, mode={}",
        dim("meta:"),
        trace.meta.source,
        trace.meta.backend,
        trace.meta.mode,
    );

    for u in &trace.units {
        println!(
            "\n  {} {} ({} steps, {}ms)",
            cyan(""),
            bold(&u.flow_name),
            u.steps.len(),
            u.duration_ms,
        );

        for (i, s) in u.steps.iter().enumerate() {
            let icon = if s.success { green("") } else { red("") };
            let truncated = truncate_line(&s.output, 80);
            println!(
                "    {} {}.{} [{}] → {}",
                icon,
                i + 1,
                bold(&s.name),
                s.event_type,
                truncated,
            );

            for a in &s.anchor_results {
                let a_icon = if a.passed { green("") } else { red("") };
                println!("      {} {}", a_icon, a.detail);
            }

            if s.was_retried {
                println!("      {} retried", yellow(""));
            }
        }
    }

    // Summary
    let s = &trace.summary;
    println!(
        "\n  {} {} units, {} steps, {} passes, {} breaches, {} retries, {} errors",
        bold("Summary:"),
        s.total_units,
        s.total_steps,
        s.total_anchor_passes,
        s.total_anchor_breaches,
        s.total_retries,
        s.total_errors,
    );
    if s.total_input_tokens > 0 || s.total_output_tokens > 0 {
        println!(
            "  {} {} input + {} output tokens",
            dim("Tokens:"),
            s.total_input_tokens,
            s.total_output_tokens,
        );
    }
}

fn print_regression(diff: &RegressionDiff, file_a: &str, file_b: &str, use_color: bool) {
    let bold = |s: &str| if use_color { format!("\x1b[1m{s}\x1b[0m") } else { s.to_string() };
    let dim = |s: &str| if use_color { format!("\x1b[2m{s}\x1b[0m") } else { s.to_string() };
    let green = |s: &str| if use_color { format!("\x1b[1;32m{s}\x1b[0m") } else { s.to_string() };
    let red = |s: &str| if use_color { format!("\x1b[1;31m{s}\x1b[0m") } else { s.to_string() };
    let yellow = |s: &str| if use_color { format!("\x1b[1;33m{s}\x1b[0m") } else { s.to_string() };

    println!(
        "{} {}{}",
        bold("Regression:"),
        dim(file_a),
        dim(file_b),
    );

    if diff.identical {
        println!("  {} Traces match — no regressions.", green(""));
        return;
    }

    let s = &diff.summary;
    println!(
        "  {} {}/{} steps match, {} changed, {} added, {} removed",
        yellow("!"),
        s.matched,
        s.total_steps,
        s.changed,
        s.added,
        s.removed,
    );

    for d in &diff.step_diffs {
        match d.status {
            RegressionStatus::Match => {} // skip
            RegressionStatus::Changed => {
                println!(
                    "\n  {} {}.{} — output changed",
                    yellow("~"),
                    d.unit,
                    bold(&d.step),
                );
                println!("    {} {}", red("-"), truncate_line(&d.old_output, 80));
                println!("    {} {}", green("+"), truncate_line(&d.new_output, 80));
            }
            RegressionStatus::Added => {
                println!(
                    "  {} {}.{} — new step",
                    green("+"),
                    d.unit,
                    bold(&d.step),
                );
            }
            RegressionStatus::Removed => {
                println!(
                    "  {} {}.{} — step removed",
                    red("-"),
                    d.unit,
                    bold(&d.step),
                );
            }
        }
    }
}

fn truncate_line(s: &str, max: usize) -> String {
    let line = s.lines().next().unwrap_or(s);
    if line.len() > max {
        format!("{}...", &line[..max])
    } else {
        line.to_string()
    }
}

// ── Tests ────────────────────────────────────────────────────────────────

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

    fn sample_trace() -> serde_json::Value {
        json!({
            "_meta": {
                "source": "test.axon",
                "backend": "anthropic",
                "tool_mode": "stub",
                "axon_version": "1.0.0",
                "mode": "stub",
            },
            "events": [
                { "event": "unit_start", "unit": "Flow1", "step": "", "detail": "persona=P1, context=default" },
                { "event": "anchor_pass", "unit": "Flow1", "step": "S1", "detail": "NoHallucination: 0.95" },
                { "event": "step_complete", "unit": "Flow1", "step": "S1", "detail": "result of S1" },
                { "event": "anchor_breach", "unit": "Flow1", "step": "S2", "detail": "FactualOnly: 0.30, reason=opinion detected" },
                { "event": "step_complete", "unit": "Flow1", "step": "S2", "detail": "result of S2" },
                { "event": "unit_complete", "unit": "Flow1", "step": "", "detail": "2 steps, 4 conversation turns" },
            ]
        })
    }

    #[test]
    fn parse_meta() {
        let data = sample_trace();
        let trace = parse_trace(&data);
        assert_eq!(trace.meta.source, "test.axon");
        assert_eq!(trace.meta.backend, "anthropic");
        assert_eq!(trace.meta.mode, "stub");
    }

    #[test]
    fn parse_units_and_steps() {
        let data = sample_trace();
        let trace = parse_trace(&data);
        assert_eq!(trace.units.len(), 1);
        assert_eq!(trace.units[0].flow_name, "Flow1");
        assert_eq!(trace.units[0].steps.len(), 2);
        assert_eq!(trace.units[0].steps[0].name, "S1");
        assert_eq!(trace.units[0].steps[0].output, "result of S1");
        assert!(trace.units[0].steps[0].success);
        assert_eq!(trace.units[0].steps[1].name, "S2");
    }

    #[test]
    fn parse_anchor_events() {
        let data = sample_trace();
        let trace = parse_trace(&data);

        // S1 has an anchor pass
        assert_eq!(trace.units[0].steps[0].anchor_results.len(), 1);
        assert!(trace.units[0].steps[0].anchor_results[0].passed);
        assert_eq!(trace.units[0].steps[0].anchor_results[0].anchor_name, "NoHallucination");

        // S2 has an anchor breach
        assert_eq!(trace.units[0].steps[1].anchor_results.len(), 1);
        assert!(!trace.units[0].steps[1].anchor_results[0].passed);
        assert_eq!(trace.units[0].steps[1].anchor_results[0].anchor_name, "FactualOnly");
    }

    #[test]
    fn parse_summary() {
        let data = sample_trace();
        let trace = parse_trace(&data);
        assert_eq!(trace.summary.total_units, 1);
        assert_eq!(trace.summary.total_steps, 2);
        assert_eq!(trace.summary.total_anchor_passes, 1);
        // Breaches counted from both unit level and step level
        assert!(trace.summary.total_anchor_breaches >= 1);
    }

    #[test]
    fn parse_tool_events() {
        let data = json!({
            "_meta": { "source": "t.axon", "backend": "anthropic", "tool_mode": "stub", "axon_version": "1.0.0", "mode": "stub" },
            "events": [
                { "event": "unit_start", "unit": "F", "step": "", "detail": "" },
                { "event": "tool_native", "unit": "F", "step": "CalcStep", "detail": "tool=Calculator, success=true, output=42" },
                { "event": "unit_complete", "unit": "F", "step": "", "detail": "" },
            ]
        });

        let trace = parse_trace(&data);
        assert_eq!(trace.units[0].steps.len(), 1);
        assert_eq!(trace.units[0].steps[0].name, "CalcStep");
        assert_eq!(trace.units[0].steps[0].event_type, "tool_native");
        assert!(trace.units[0].steps[0].success);
    }

    #[test]
    fn parse_retry_events() {
        let data = json!({
            "_meta": { "source": "t.axon", "backend": "anthropic", "tool_mode": "real", "axon_version": "1.0.0", "mode": "real" },
            "events": [
                { "event": "unit_start", "unit": "F", "step": "", "detail": "" },
                { "event": "retry_attempt", "unit": "F", "step": "S1", "detail": "attempt=1/2" },
                { "event": "step_complete", "unit": "F", "step": "S1", "detail": "retry succeeded" },
                { "event": "unit_complete", "unit": "F", "step": "", "detail": "" },
            ]
        });

        let trace = parse_trace(&data);
        assert!(trace.units[0].steps[0].was_retried);
        assert_eq!(trace.summary.total_retries, 1);
    }

    #[test]
    fn parse_error_step() {
        let data = json!({
            "_meta": { "source": "t.axon", "backend": "anthropic", "tool_mode": "real", "axon_version": "1.0.0", "mode": "real" },
            "events": [
                { "event": "unit_start", "unit": "F", "step": "", "detail": "" },
                { "event": "step_error", "unit": "F", "step": "Bad", "detail": "connection failed" },
                { "event": "unit_complete", "unit": "F", "step": "", "detail": "" },
            ]
        });

        let trace = parse_trace(&data);
        assert!(!trace.units[0].steps[0].success);
        assert_eq!(trace.summary.total_errors, 1);
    }

    #[test]
    fn parse_hook_metrics() {
        let data = json!({
            "_meta": { "source": "t.axon", "backend": "anthropic", "tool_mode": "real", "axon_version": "1.0.0", "mode": "real" },
            "events": [
                { "event": "unit_start", "unit": "F", "step": "", "detail": "" },
                { "event": "step_complete", "unit": "F", "step": "S", "detail": "ok" },
                { "event": "unit_complete", "unit": "F", "step": "", "detail": "" },
                { "event": "hook_unit_metrics", "unit": "F", "step": "", "detail": "duration=250ms, steps=1, tokens_in=100, tokens_out=50, breaches=0, chains=0" },
            ]
        });

        let trace = parse_trace(&data);
        assert_eq!(trace.units[0].duration_ms, 250);
        assert_eq!(trace.units[0].total_input_tokens, 100);
        assert_eq!(trace.units[0].total_output_tokens, 50);
    }

    #[test]
    fn regression_identical() {
        let data = sample_trace();
        let trace = parse_trace(&data);
        let diff = compare_traces(&trace, &trace);
        assert!(diff.identical);
        assert_eq!(diff.summary.matched, 2);
        assert_eq!(diff.summary.changed, 0);
    }

    #[test]
    fn regression_changed_output() {
        let data_old = sample_trace();
        let mut data_new = sample_trace();
        // events[2] is step_complete for S1
        data_new["events"][2]["detail"] = json!("different result");

        let old = parse_trace(&data_old);
        let new = parse_trace(&data_new);
        let diff = compare_traces(&old, &new);

        assert!(!diff.identical);
        assert_eq!(diff.summary.changed, 1);
        assert_eq!(diff.summary.matched, 1);
    }

    #[test]
    fn regression_added_step() {
        let data_old = sample_trace();
        let mut data_new = sample_trace();
        // Add a new step
        data_new["events"].as_array_mut().unwrap().insert(3, json!(
            { "event": "step_complete", "unit": "Flow1", "step": "S3", "detail": "new step" }
        ));

        let old = parse_trace(&data_old);
        let new = parse_trace(&data_new);
        let diff = compare_traces(&old, &new);

        assert!(!diff.identical);
        assert_eq!(diff.summary.added, 1);
    }

    #[test]
    fn run_replay_file_not_found() {
        assert_eq!(run_replay("nonexistent.trace.json", None, false), 2);
    }

    #[test]
    fn run_replay_single_trace() {
        let tmp = std::env::temp_dir().join("axon_replay_test.trace.json");
        let data = sample_trace();
        std::fs::write(&tmp, serde_json::to_string(&data).unwrap()).unwrap();

        assert_eq!(run_replay(tmp.to_str().unwrap(), None, true), 0);
        let _ = std::fs::remove_file(tmp);
    }

    #[test]
    fn run_replay_regression_identical() {
        let tmp = std::env::temp_dir().join("axon_replay_reg.trace.json");
        let data = sample_trace();
        std::fs::write(&tmp, serde_json::to_string(&data).unwrap()).unwrap();

        let path = tmp.to_str().unwrap();
        assert_eq!(run_replay(path, Some(path), true), 0);
        let _ = std::fs::remove_file(tmp);
    }

    #[test]
    fn run_replay_regression_different() {
        let tmp_a = std::env::temp_dir().join("axon_replay_a.trace.json");
        let tmp_b = std::env::temp_dir().join("axon_replay_b.trace.json");

        let data_a = sample_trace();
        let mut data_b = sample_trace();
        // events[2] is step_complete for S1
        data_b["events"][2]["detail"] = json!("changed output");

        std::fs::write(&tmp_a, serde_json::to_string(&data_a).unwrap()).unwrap();
        std::fs::write(&tmp_b, serde_json::to_string(&data_b).unwrap()).unwrap();

        assert_eq!(
            run_replay(tmp_a.to_str().unwrap(), Some(tmp_b.to_str().unwrap()), true),
            1,
        );

        let _ = std::fs::remove_file(tmp_a);
        let _ = std::fs::remove_file(tmp_b);
    }

    #[test]
    fn regression_status_serializes() {
        assert_eq!(serde_json::to_string(&RegressionStatus::Match).unwrap(), "\"match\"");
        assert_eq!(serde_json::to_string(&RegressionStatus::Changed).unwrap(), "\"changed\"");
        assert_eq!(serde_json::to_string(&RegressionStatus::Added).unwrap(), "\"added\"");
    }

    #[test]
    fn empty_trace() {
        let data = json!({ "_meta": {}, "events": [] });
        let trace = parse_trace(&data);
        assert_eq!(trace.units.len(), 0);
        assert_eq!(trace.summary.total_steps, 0);
    }
}