invariant-firewall 0.0.3

Invariant — a cryptographic command-validation firewall for AI-controlled physical systems (robotics, biosynthesis). Installs the `invariant` binary. Part of the unified workspace at https://github.com/clay-good/invariant.
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
//! `invariant adversarial` — run the adversarial test suite against a robot profile.
//!
//! Exercises boundary probing (PA1–PA2), numeric injection (PA3–PA4), and
//! authority chain attacks (AA1–AA10) using the `invariant-fuzz` crate.
//! Results are printed as a summary and optionally written to a JSON report
//! file.

use clap::Args;
use std::collections::HashMap;
use std::path::PathBuf;

use invariant_fuzz::robotics::protocol::authority::{
    encode_chain, escalate_operations, forge_signature, truncate_chain,
};
use invariant_fuzz::robotics::protocol::boundary::BoundaryProber;
use invariant_fuzz::robotics::protocol::numeric::NumericInjector;
use invariant_fuzz::robotics::report::AdversarialReport;

use invariant_robotics::authority::crypto::sign_pca;
use invariant_robotics::models::authority::{Operation, Pca, SignedPca};
use invariant_robotics::validator::ValidatorConfig;

#[derive(Args)]
pub struct AdversarialArgs {
    /// Path to the robot profile JSON file.
    #[arg(long, value_name = "PROFILE_FILE")]
    pub profile: PathBuf,
    /// Path to the key file (secret key required).
    #[arg(long, value_name = "KEY_FILE")]
    pub key: PathBuf,
    /// Attack suite to run: "protocol", "authority", or "all".
    #[arg(long, default_value = "protocol")]
    pub suite: String,
    /// Optional path to write the JSON report.
    #[arg(long, value_name = "REPORT_FILE")]
    pub report: Option<PathBuf>,
    /// Export structured training data for cognitive layer improvement (Section 11.5).
    #[arg(long, value_name = "TRAINING_FILE")]
    pub export_training: Option<PathBuf>,
    /// Run mutation-based fuzzing for N iterations instead of structured suites.
    #[arg(long)]
    pub fuzz: bool,
    /// Number of fuzz iterations (default 10000). Only used with --fuzz.
    #[arg(long, default_value = "10000")]
    pub iterations: u64,
}

pub fn run(args: &AdversarialArgs) -> i32 {
    // Load profile.
    let profile_json = match std::fs::read_to_string(&args.profile) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: failed to read profile {:?}: {e}", args.profile);
            return 2;
        }
    };
    let profile = match invariant_robotics::profiles::load_from_json(&profile_json) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("error: invalid profile: {e}");
            return 2;
        }
    };

    // Load key.
    let kf = match crate::key_file::load_key_file(&args.key) {
        Ok(kf) => kf,
        Err(e) => {
            eprintln!("error: {e}");
            return 2;
        }
    };
    let (signing_key, verifying_key, kid) = match crate::key_file::load_signing_key(&kf) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("error: {e}");
            return 2;
        }
    };

    // Build validator config.
    let raw_key_bytes = signing_key.to_bytes();
    let mut trusted_keys = HashMap::new();
    trusted_keys.insert(kid.clone(), verifying_key);

    let config = match ValidatorConfig::new(profile.clone(), trusted_keys, signing_key, kid.clone())
    {
        Ok(c) => c,
        Err(e) => {
            eprintln!("error: failed to build validator config: {e}");
            return 2;
        }
    };

    // -----------------------------------------------------------------------
    // Fuzz mode: mutation-based fuzzing for N iterations
    // -----------------------------------------------------------------------
    if args.fuzz {
        return run_fuzz_mode(&config, &profile, &kid, &raw_key_bytes, args);
    }

    let suite = args.suite.as_str();
    let mut aggregate = AdversarialReport::new(suite);

    // -----------------------------------------------------------------------
    // Protocol suite: boundary probing + numeric injection
    // -----------------------------------------------------------------------
    if suite == "protocol" || suite == "all" {
        run_protocol_suite(&config, &profile, &kid, &raw_key_bytes, &mut aggregate);
    }

    // -----------------------------------------------------------------------
    // Authority suite: chain forgery / escalation / truncation
    // -----------------------------------------------------------------------
    if suite == "authority" || suite == "all" {
        run_authority_suite(&config, &profile, &kid, &raw_key_bytes, &mut aggregate);
    }

    // -----------------------------------------------------------------------
    // Environment suite: P21-P25 environmental hazard injection
    // -----------------------------------------------------------------------
    if suite == "environment" || suite == "all" {
        run_environment_suite(&config, &profile, &kid, &raw_key_bytes, &mut aggregate);
    }

    if !matches!(suite, "protocol" | "authority" | "environment" | "all") {
        eprintln!(
            "error: unknown suite {:?}; must be 'protocol', 'authority', 'environment', or 'all'",
            args.suite
        );
        return 2;
    }

    // Print summary.
    println!(
        "Adversarial suite '{}': {} attacks, {} escapes",
        aggregate.attack_class, aggregate.total_attacks, aggregate.escapes
    );

    if aggregate.all_detected() {
        println!("PASS: all attacks detected");
    } else {
        eprintln!("FAIL: {} attack(s) escaped detection", aggregate.escapes);
        for f in aggregate.findings.iter().filter(|f| f.escaped) {
            eprintln!(
                "  [{}] {} -> {}",
                f.attack_id, f.description, f.validator_outcome
            );
        }
    }

    // Optionally write JSON report.
    if let Some(ref report_path) = args.report {
        match serde_json::to_string_pretty(&aggregate) {
            Ok(json) => {
                if let Err(e) = std::fs::write(report_path, json) {
                    eprintln!("error: failed to write report {:?}: {e}", report_path);
                    return 2;
                }
            }
            Err(e) => {
                eprintln!("error: failed to serialize report: {e}");
                return 2;
            }
        }
    }

    // Optionally export training data (Section 11.5).
    if let Some(ref training_path) = args.export_training {
        let training_entries: Vec<serde_json::Value> = aggregate
            .findings
            .iter()
            .filter(|f| !f.escaped)
            .map(|f| {
                serde_json::json!({
                    "attack_id": f.attack_id,
                    "verdict": "rejected",
                    "violation_type": f.description,
                    "validator_outcome": f.validator_outcome,
                    "attack_class": f.attack_id.split('-').next().unwrap_or("unknown"),
                    "severity": if f.escaped { "critical" } else { "info" },
                })
            })
            .collect();
        let jsonl: String = training_entries
            .iter()
            .map(|e| serde_json::to_string(e).unwrap())
            .collect::<Vec<_>>()
            .join("\n");
        if let Err(e) = std::fs::write(training_path, jsonl) {
            eprintln!(
                "error: failed to write training data {:?}: {e}",
                training_path
            );
            return 2;
        }
        println!(
            "Training data exported: {} entries to {:?}",
            training_entries.len(),
            training_path
        );
    }

    if aggregate.all_detected() {
        0
    } else {
        1
    }
}

// ---------------------------------------------------------------------------
// Protocol suite helpers
// ---------------------------------------------------------------------------

fn run_protocol_suite(
    config: &ValidatorConfig,
    profile: &invariant_robotics::models::profile::RobotProfile,
    kid: &str,
    raw_key_bytes: &[u8; 32],
    report: &mut AdversarialReport,
) {
    let now = chrono::Utc::now();

    // Build a valid signing key for attaching a chain to boundary/numeric cmds.
    let attach_sk = ed25519_dalek::SigningKey::from_bytes(raw_key_bytes);

    // --- Boundary probing (PA1–PA2) ---
    let boundary_probes = BoundaryProber::probe_all_joints(profile);
    for (i, (mut cmd, expected_pass)) in boundary_probes.into_iter().enumerate() {
        attach_valid_chain(&mut cmd, &attach_sk, kid, profile);
        let attack_id = if expected_pass {
            format!("PA1-boundary-{i}")
        } else {
            format!("PA2-boundary-{i}")
        };

        match config.validate(&cmd, now, None) {
            Ok(result) => {
                let approved = result.signed_verdict.verdict.approved;
                // An escape occurs when the validator approves a command we
                // expected to be rejected (or vice versa — though approving a
                // boundary-exactly-at-limit command is correct behaviour).
                let escaped = approved != expected_pass;
                let outcome = if approved {
                    "approved".to_string()
                } else {
                    let failed: Vec<&str> = result
                        .signed_verdict
                        .verdict
                        .checks
                        .iter()
                        .filter(|c| !c.passed)
                        .map(|c| c.name.as_str())
                        .collect();
                    format!("rejected [{}]", failed.join(", "))
                };
                report.record(
                    &attack_id,
                    format!("boundary probe (expected_pass={expected_pass})"),
                    outcome,
                    escaped,
                );
            }
            Err(e) => {
                // A ValidatorError is a processing failure, not an escape.
                report.record(
                    &attack_id,
                    format!("boundary probe (expected_pass={expected_pass})"),
                    format!("error: {e}"),
                    false,
                );
            }
        }
    }

    // --- Numeric injection (PA3–PA4) ---
    if let Some(base_cmd) = build_valid_base_command(profile, kid, raw_key_bytes) {
        let injected = NumericInjector::inject_all(&base_cmd);
        for (i, cmd) in injected.into_iter().enumerate() {
            let attack_id = format!("PA3-numeric-{i}");
            match config.validate(&cmd, now, None) {
                Ok(result) => {
                    let approved = result.signed_verdict.verdict.approved;
                    // NaN/Inf injections should always be rejected.
                    let escaped = approved;
                    report.record(
                        &attack_id,
                        "numeric injection (NaN/Inf/subnormal)",
                        if approved { "approved" } else { "rejected" },
                        escaped,
                    );
                }
                Err(e) => {
                    report.record(
                        &attack_id,
                        "numeric injection (NaN/Inf/subnormal)",
                        format!("error: {e}"),
                        false,
                    );
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Authority suite helpers
// ---------------------------------------------------------------------------

fn run_authority_suite(
    config: &ValidatorConfig,
    profile: &invariant_robotics::models::profile::RobotProfile,
    kid: &str,
    raw_key_bytes: &[u8; 32],
    report: &mut AdversarialReport,
) {
    let now = chrono::Utc::now();
    let attack_sk = ed25519_dalek::SigningKey::from_bytes(raw_key_bytes);

    // AA1: Forge signature
    {
        let forged = forge_signature(&attack_sk, kid);
        let chain_b64 = encode_chain(&[forged]);
        let mut cmd = build_base_command_with_chain(profile, chain_b64, kid);
        cmd.authority.required_ops = vec![dummy_op(profile)];
        match config.validate(&cmd, now, None) {
            Ok(result) => {
                let approved = result.signed_verdict.verdict.approved;
                report.record(
                    "AA1",
                    "forged signature (payload tampered after signing)",
                    if approved { "approved" } else { "rejected" },
                    approved, // escape = approved
                );
            }
            Err(e) => {
                report.record("AA1", "forged signature", format!("error: {e}"), false);
            }
        }
    }

    // AA2: Operation escalation
    {
        let chain = escalate_operations(&attack_sk, kid);
        let chain_b64 = encode_chain(&chain);
        let mut cmd = build_base_command_with_chain(profile, chain_b64, kid);
        cmd.authority.required_ops =
            vec![Operation::new("actuate:*").unwrap_or_else(|_| dummy_op(profile))];
        match config.validate(&cmd, now, None) {
            Ok(result) => {
                let approved = result.signed_verdict.verdict.approved;
                report.record(
                    "AA2",
                    "operation escalation in child hop",
                    if approved { "approved" } else { "rejected" },
                    approved,
                );
            }
            Err(e) => {
                report.record("AA2", "operation escalation", format!("error: {e}"), false);
            }
        }
    }

    // AA3: Truncated chain
    {
        let chain = truncate_chain(&attack_sk, kid);
        let chain_b64 = encode_chain(&chain);
        let mut cmd = build_base_command_with_chain(profile, chain_b64, kid);
        cmd.authority.required_ops = vec![dummy_op(profile)];
        match config.validate(&cmd, now, None) {
            Ok(result) => {
                let approved = result.signed_verdict.verdict.approved;
                report.record(
                    "AA3",
                    "truncated chain (intermediate hop removed)",
                    if approved { "approved" } else { "rejected" },
                    approved,
                );
            }
            Err(e) => {
                report.record("AA3", "truncated chain", format!("error: {e}"), false);
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Private helpers
// ---------------------------------------------------------------------------

/// Attach a valid self-signed PCA chain to `cmd` using the given key.
fn attach_valid_chain(
    cmd: &mut invariant_robotics::models::command::Command,
    signing_key: &ed25519_dalek::SigningKey,
    kid: &str,
    profile: &invariant_robotics::models::profile::RobotProfile,
) {
    use std::collections::BTreeSet;
    let op = dummy_op(profile);
    cmd.authority.required_ops = vec![op.clone()];

    let pca = Pca {
        p_0: "invariant-adversarial".into(),
        ops: BTreeSet::from([op]),
        kid: kid.to_string(),
        exp: None,
        nbf: None,
        predecessor_digest: [0u8; 32],
    };
    let signed: SignedPca = sign_pca(&pca, signing_key).expect("sign_pca must not fail");
    let chain = vec![signed];
    let chain_json = serde_json::to_vec(&chain).expect("serialize chain");
    use base64::{engine::general_purpose::STANDARD, Engine};
    cmd.authority.pca_chain = STANDARD.encode(&chain_json);
}

/// Build a valid command with all joints at midpoints and a fresh self-signed chain.
fn build_valid_base_command(
    profile: &invariant_robotics::models::profile::RobotProfile,
    kid: &str,
    raw_key_bytes: &[u8; 32],
) -> Option<invariant_robotics::models::command::Command> {
    use invariant_robotics::models::command::{Command, CommandAuthority, JointState};
    use std::collections::HashMap;

    let signing_key = ed25519_dalek::SigningKey::from_bytes(raw_key_bytes);
    let joint_states: Vec<JointState> = profile
        .joints
        .iter()
        .map(|j| JointState {
            name: j.name.clone(),
            position: (j.min + j.max) / 2.0,
            velocity: 0.0,
            effort: 0.0,
        })
        .collect();

    let op = dummy_op(profile);
    let mut cmd = Command {
        timestamp: chrono::Utc::now(),
        source: "adversarial".into(),
        sequence: 1,
        joint_states,
        delta_time: 0.01,
        end_effector_positions: vec![],
        center_of_mass: None,
        authority: CommandAuthority {
            pca_chain: String::new(),
            required_ops: vec![op],
        },
        metadata: HashMap::new(),
        locomotion_state: None,
        end_effector_forces: vec![],
        estimated_payload_kg: None,
        signed_sensor_readings: vec![],
        zone_overrides: HashMap::new(),
        environment_state: None,
    };
    attach_valid_chain(&mut cmd, &signing_key, kid, profile);
    Some(cmd)
}

/// Build a minimal command with a specific chain encoding.
fn build_base_command_with_chain(
    profile: &invariant_robotics::models::profile::RobotProfile,
    chain_b64: String,
    kid: &str,
) -> invariant_robotics::models::command::Command {
    use invariant_robotics::models::command::{Command, CommandAuthority, JointState};
    use std::collections::HashMap;

    let joint_states: Vec<JointState> = profile
        .joints
        .iter()
        .map(|j| JointState {
            name: j.name.clone(),
            position: (j.min + j.max) / 2.0,
            velocity: 0.0,
            effort: 0.0,
        })
        .collect();

    Command {
        timestamp: chrono::Utc::now(),
        source: "adversarial".into(),
        sequence: 1,
        joint_states,
        delta_time: 0.01,
        end_effector_positions: vec![],
        center_of_mass: None,
        authority: CommandAuthority {
            pca_chain: chain_b64,
            required_ops: vec![dummy_op(profile)],
        },
        metadata: HashMap::new(),
        locomotion_state: None,
        end_effector_forces: vec![],
        estimated_payload_kg: None,
        signed_sensor_readings: vec![],
        zone_overrides: HashMap::new(),
        environment_state: None,
    }
    .tap_kid(kid)
}

// ---------------------------------------------------------------------------
// Environment suite: P21-P25 environmental hazard injection
// ---------------------------------------------------------------------------

fn run_environment_suite(
    config: &ValidatorConfig,
    profile: &invariant_robotics::models::profile::RobotProfile,
    kid: &str,
    raw_key_bytes: &[u8; 32],
    report: &mut AdversarialReport,
) {
    use invariant_sim::robotics::injector::{inject, InjectionType};

    let now = chrono::Utc::now();

    let env_attacks: &[(&str, InjectionType)] = &[
        ("ENV-P21-terrain-incline", InjectionType::TerrainIncline),
        ("ENV-P22-temperature-spike", InjectionType::TemperatureSpike),
        ("ENV-P23-battery-drain", InjectionType::BatteryDrain),
        ("ENV-P24-latency-spike", InjectionType::LatencySpike),
        ("ENV-P25-estop-engage", InjectionType::EStopEngage),
    ];

    // For P21-P24: also test with an explicit safe environment_state on the
    // base command so the profile's environment config thresholds are exercised.
    // For P25 (e-stop): always works regardless of profile config.
    for &(attack_id, inj_type) in env_attacks {
        let Some(mut cmd) = build_valid_base_command(profile, kid, raw_key_bytes) else {
            report.record(
                attack_id,
                format!("{inj_type:?} (skipped — no base command)"),
                "skipped",
                false,
            );
            continue;
        };

        inject(&mut cmd, inj_type, profile);

        match config.validate(&cmd, now, None) {
            Ok(result) => {
                let approved = result.signed_verdict.verdict.approved;
                // P25 (e-stop) must always be rejected.
                // P21-P24 are only rejected if the profile has environment config.
                let needs_config = !matches!(inj_type, InjectionType::EStopEngage);
                let profile_has_env = profile.environment.is_some();

                let escaped = if needs_config && !profile_has_env {
                    // No environment config → injection is a no-op, approval is correct
                    false
                } else {
                    // Should be rejected
                    approved
                };

                let outcome = if approved {
                    "approved".to_string()
                } else {
                    let failed: Vec<&str> = result
                        .signed_verdict
                        .verdict
                        .checks
                        .iter()
                        .filter(|c| !c.passed)
                        .map(|c| c.name.as_str())
                        .collect();
                    format!("rejected [{}]", failed.join(", "))
                };
                report.record(attack_id, format!("{inj_type:?}"), outcome, escaped);
            }
            Err(e) => {
                report.record(
                    attack_id,
                    format!("{inj_type:?}"),
                    format!("error: {e}"),
                    false,
                );
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Fuzz mode: mutation-based fuzzing for N iterations
// ---------------------------------------------------------------------------

fn run_fuzz_mode(
    config: &ValidatorConfig,
    profile: &invariant_robotics::models::profile::RobotProfile,
    kid: &str,
    raw_key_bytes: &[u8; 32],
    args: &AdversarialArgs,
) -> i32 {
    use invariant_fuzz::robotics::generators::command_gen::CommandGenerator;
    use invariant_fuzz::robotics::generators::mutation::MutationEngine;
    use rand::rngs::StdRng;
    use rand::SeedableRng;

    let now = chrono::Utc::now();
    let mut report = AdversarialReport::new("fuzz");
    let mut escapes = 0u64;
    let mut total = 0u64;

    let mut rng = StdRng::seed_from_u64(0xDEADBEEF);

    for i in 0..args.iterations {
        // Generate a random valid command.
        let mut base = CommandGenerator::generate(profile, &mut rng);

        // Attach a valid authority chain.
        let sk = ed25519_dalek::SigningKey::from_bytes(raw_key_bytes);
        attach_valid_chain(&mut base, &sk, kid, profile);

        // Apply all mutations to the base command.
        let mutations = MutationEngine::mutate_all(&base);
        for m in &mutations {
            total += 1;
            match config.validate(&m.command, now, None) {
                Ok(result) => {
                    if result.signed_verdict.verdict.approved {
                        // A mutated command was approved — potential escape.
                        // The "authority-strip" and "empty-joints" mutations are expected
                        // to be rejected; others depend on the mutation.
                        escapes += 1;
                        report.record(
                            format!("FUZZ-{i}-{}", m.id),
                            format!("mutation targeting {}", m.target_check),
                            "approved (ESCAPE)",
                            true,
                        );
                    }
                }
                Err(_) => {
                    // Validation error = rejection, which is correct for mutations.
                }
            }
        }
    }

    println!(
        "Fuzz mode: {total} mutated commands across {} iterations, {escapes} escapes",
        args.iterations
    );

    if escapes == 0 {
        println!("PASS: no mutations escaped validation");
    } else {
        eprintln!("FAIL: {escapes} mutation(s) escaped validation");
        for f in report.findings.iter().filter(|f| f.escaped) {
            eprintln!("  [{}] {}", f.attack_id, f.description);
        }
    }

    // Write report if requested.
    if let Some(ref report_path) = args.report {
        let json = serde_json::to_string_pretty(&report).unwrap();
        if let Err(e) = std::fs::write(report_path, json) {
            eprintln!("error: failed to write report: {e}");
            return 2;
        }
    }

    if escapes == 0 {
        0
    } else {
        1
    }
}

fn dummy_op(_profile: &invariant_robotics::models::profile::RobotProfile) -> Operation {
    // Use a wildcard operation so that boundary/numeric probes touching any
    // joint in the profile pass the authority check — we want to isolate
    // physics failures, not authority failures, in the protocol suite.
    Operation::new("actuate:*").expect("wildcard op must be valid")
}

trait TapKid {
    fn tap_kid(self, _kid: &str) -> Self;
}

impl TapKid for invariant_robotics::models::command::Command {
    fn tap_kid(self, _kid: &str) -> Self {
        self
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use base64::{engine::general_purpose::STANDARD, Engine};
    use invariant_robotics::authority::crypto::generate_keypair;
    use rand::rngs::OsRng;
    use std::io::Write;
    use tempfile::{NamedTempFile, TempDir};

    fn write_profile() -> NamedTempFile {
        let name = invariant_robotics::profiles::list_builtins()[0];
        let profile = invariant_robotics::profiles::load_builtin(name).unwrap();
        let json = serde_json::to_string_pretty(&profile).unwrap();
        let mut tmp = NamedTempFile::new().unwrap();
        tmp.write_all(json.as_bytes()).unwrap();
        tmp.flush().unwrap();
        tmp
    }

    fn write_key_file() -> (NamedTempFile, ed25519_dalek::SigningKey) {
        let sk = generate_keypair(&mut OsRng);
        let vk = sk.verifying_key();
        let kf = crate::key_file::KeyFile {
            kid: "test-kid".into(),
            public_key: STANDARD.encode(vk.as_bytes()),
            secret_key: Some(STANDARD.encode(sk.to_bytes())),
        };
        let mut tmp = NamedTempFile::new().unwrap();
        tmp.write_all(serde_json::to_string_pretty(&kf).unwrap().as_bytes())
            .unwrap();
        tmp.flush().unwrap();
        (tmp, sk)
    }

    fn make_args(
        profile: &std::path::Path,
        key: &std::path::Path,
        suite: &str,
        report: Option<PathBuf>,
    ) -> AdversarialArgs {
        AdversarialArgs {
            profile: profile.to_path_buf(),
            key: key.to_path_buf(),
            suite: suite.to_string(),
            report,
            export_training: None,
            fuzz: false,
            iterations: 10000,
        }
    }

    #[test]
    fn protocol_suite_returns_0_when_all_detected() {
        let profile_tmp = write_profile();
        let (key_tmp, _sk) = write_key_file();
        let args = make_args(profile_tmp.path(), key_tmp.path(), "protocol", None);
        let code = run(&args);
        assert_eq!(
            code, 0,
            "protocol suite must return 0 (all attacks detected)"
        );
    }

    #[test]
    fn authority_suite_returns_0_when_all_detected() {
        let profile_tmp = write_profile();
        let (key_tmp, _sk) = write_key_file();
        let args = make_args(profile_tmp.path(), key_tmp.path(), "authority", None);
        let code = run(&args);
        assert_eq!(
            code, 0,
            "authority suite must return 0 (all attacks detected)"
        );
    }

    #[test]
    fn all_suite_returns_0_when_all_detected() {
        let profile_tmp = write_profile();
        let (key_tmp, _sk) = write_key_file();
        let args = make_args(profile_tmp.path(), key_tmp.path(), "all", None);
        let code = run(&args);
        assert_eq!(code, 0, "all suite must return 0 (all attacks detected)");
    }

    #[test]
    fn environment_suite_returns_0_when_all_detected() {
        let profile_tmp = write_profile();
        let (key_tmp, _sk) = write_key_file();
        let args = make_args(profile_tmp.path(), key_tmp.path(), "environment", None);
        let code = run(&args);
        assert_eq!(
            code, 0,
            "environment suite must return 0 (all attacks detected)"
        );
    }

    #[test]
    fn unknown_suite_returns_2() {
        let profile_tmp = write_profile();
        let (key_tmp, _sk) = write_key_file();
        let args = make_args(profile_tmp.path(), key_tmp.path(), "bogus", None);
        assert_eq!(run(&args), 2);
    }

    #[test]
    fn missing_profile_returns_2() {
        let (key_tmp, _sk) = write_key_file();
        let args = AdversarialArgs {
            profile: PathBuf::from("/nonexistent/profile.json"),
            key: key_tmp.path().to_path_buf(),
            suite: "protocol".into(),
            report: None,
            export_training: None,
            fuzz: false,
            iterations: 10000,
        };
        assert_eq!(run(&args), 2);
    }

    #[test]
    fn missing_key_returns_2() {
        let profile_tmp = write_profile();
        let args = AdversarialArgs {
            profile: profile_tmp.path().to_path_buf(),
            key: PathBuf::from("/nonexistent/key.json"),
            suite: "protocol".into(),
            report: None,
            export_training: None,
            fuzz: false,
            iterations: 10000,
        };
        assert_eq!(run(&args), 2);
    }

    #[test]
    fn report_written_to_file() {
        let profile_tmp = write_profile();
        let (key_tmp, _sk) = write_key_file();
        let dir = TempDir::new().unwrap();
        let report_path = dir.path().join("report.json");

        let args = make_args(
            profile_tmp.path(),
            key_tmp.path(),
            "protocol",
            Some(report_path.clone()),
        );
        let _code = run(&args);

        assert!(report_path.exists(), "report file must be created");
        let content = std::fs::read_to_string(&report_path).unwrap();
        let _parsed: AdversarialReport =
            serde_json::from_str(&content).expect("report must be valid JSON");
    }
}