agent-shield 0.8.7

Security scanner for AI agent extensions — offline-first, multi-framework, SARIF output
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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
#[cfg(feature = "runtime-guard")]
use std::io::Read;
use std::path::PathBuf;
use std::process;

use clap::{Parser, Subcommand};

use agentshield::baseline::{BaselineEntry, BaselineFile};
use agentshield::config::{Config, ScanPathFilter, ScanPathFilterSummary};
use agentshield::doctor::DoctorReport;
use agentshield::egress::policy::EgressPolicy;
#[cfg(feature = "runtime")]
use agentshield::egress::proxy::EgressProxy;
use agentshield::output::OutputFormat;
use agentshield::rules::{RuleEngine, Severity};
#[cfg(feature = "runtime-guard")]
use agentshield::runtime::{
    evaluate_runtime_event, invalid_runtime_guard_input, RuntimeEvent, RuntimeVerdict,
};
use agentshield::ux::{CiInstallOptions, ExplainOptions};
use agentshield::ScanOptions;

#[cfg(feature = "runtime-guard")]
const GUARD_STDIN_MAX_BYTES: usize = 1024 * 1024;

#[derive(Parser)]
#[command(
    name = "agentshield",
    about = "Security scanner for AI agent extensions (MCP, OpenClaw, Hermes Agent, CrewAI, LangChain, GPT Actions, Cursor Rules)",
    long_about = "AgentShield scans AI agent extensions for security vulnerabilities.\n\n\
                  It detects command injection, credential exfiltration, SSRF, arbitrary \
                  file access, supply chain issues, and more. Results can be output as \
                  console text, JSON, SARIF (GitHub Code Scanning), or HTML reports.",
    version,
    author
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Scan an agent extension for security issues
    Scan {
        /// Path to the extension directory
        #[arg(default_value = ".")]
        path: PathBuf,

        /// Config file path
        #[arg(long, short = 'c')]
        config: Option<PathBuf>,

        /// Output format (console, json, sarif, html)
        #[arg(long, short = 'f', default_value = "console")]
        format: String,

        /// Minimum severity to fail (info, low, medium, high, critical)
        #[arg(long)]
        fail_on: Option<String>,

        /// Write output to file instead of stdout
        #[arg(long, short = 'o')]
        output: Option<PathBuf>,

        /// Skip test files (test/, tests/, __tests__/, *.test.ts, *.spec.ts, etc.)
        #[arg(long)]
        ignore_tests: bool,

        /// Filter out findings that match a previously written baseline file
        #[arg(long, value_name = "PATH")]
        baseline: Option<PathBuf>,

        /// Write all current findings as a baseline file
        #[arg(long, value_name = "PATH")]
        write_baseline: Option<PathBuf>,

        /// Analyze scan results and emit a starter egress policy to the given path
        #[arg(long, value_name = "PATH")]
        emit_egress_policy: Option<PathBuf>,

        /// Explain the gate, coverage, confidence, grouped findings, and next actions.
        ///
        /// This is console-only so JSON, SARIF, and HTML output contracts stay stable.
        #[arg(long)]
        explain: bool,
    },

    /// First-run setup: create config, inspect coverage, and run an explained scan
    Quickstart {
        /// Project directory to initialize and scan
        #[arg(default_value = ".")]
        path: PathBuf,

        /// Overwrite an existing .agentshield.toml
        #[arg(long)]
        force: bool,

        /// Minimum severity to fail (info, low, medium, high, critical)
        #[arg(long, default_value = "high")]
        fail_on: String,

        /// Include test files in the first scan and generated config
        #[arg(long)]
        include_tests: bool,
    },

    /// Install CI integration helpers
    Ci {
        #[command(subcommand)]
        command: CiCommand,
    },

    /// List all available detection rules
    ListRules {
        /// Output format (table, json)
        #[arg(long, short = 'f', default_value = "table")]
        format: String,
    },

    /// Generate a starter .agentshield.toml config file
    Init {
        /// Overwrite existing config file
        #[arg(long)]
        force: bool,
    },

    /// Add a suppression entry to .agentshield.toml for a specific finding
    Suppress {
        /// SHA-256 fingerprint of the finding to suppress (from --format json output)
        fingerprint: String,

        /// Mandatory reason explaining why this finding is suppressed
        #[arg(long, short = 'r')]
        reason: String,

        /// Optional expiry date in YYYY-MM-DD format
        #[arg(long, short = 'e')]
        expires: Option<String>,

        /// Config file path (defaults to .agentshield.toml in the current directory)
        #[arg(long, short = 'c')]
        config: Option<PathBuf>,
    },

    /// List all suppressions in .agentshield.toml
    ListSuppressions {
        /// Config file path (defaults to .agentshield.toml in the current directory)
        #[arg(long, short = 'c')]
        config: Option<PathBuf>,
    },

    /// Print environment and configuration diagnostics
    Doctor {
        /// Path to inspect
        #[arg(default_value = ".")]
        path: PathBuf,

        /// Config file path
        #[arg(long, short = 'c')]
        config: Option<PathBuf>,

        /// Emit diagnostics as JSON
        #[arg(long)]
        json: bool,

        /// Skip test files in effective scan settings
        #[arg(long)]
        ignore_tests: bool,
    },

    /// Evaluate one runtime event from stdin as JSON
    #[cfg(feature = "runtime-guard")]
    Guard {
        /// Read a RuntimeEvent JSON document from stdin
        #[arg(long)]
        stdin: bool,

        /// EXPERIMENTAL: run an MCP JSON-RPC proxy guard. Reads JSON-RPC
        /// messages (one per line) on stdin, evaluates `tools/call` against
        /// runtime policy, and emits a forward marker or a block error.
        #[arg(long)]
        mcp_proxy: bool,

        /// Path to .agentshield.toml for the `[runtime.proxy]` policy
        /// (defaults to ./.agentshield.toml).
        #[arg(long)]
        config: Option<std::path::PathBuf>,

        /// EXPERIMENTAL: with --mcp-proxy, the command after `--` is spawned as
        /// the downstream MCP server and stdio is bridged both ways. Forwarded
        /// `tools/call` requests reach the server and its real response is
        /// returned; blocked ones are not forwarded. With no command, the proxy
        /// runs in line mode (emits `{"forward": ...}` envelopes).
        #[arg(last = true)]
        server: Vec<String>,
    },

    /// Generate a DSSE attestation envelope for scan results
    Certify {
        /// Path to the extension directory
        #[arg(default_value = ".")]
        path: PathBuf,

        /// Path to Ed25519 private key file (32 bytes, raw binary)
        #[arg(long)]
        sign_key: Option<PathBuf>,

        /// Write output to file instead of stdout
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Config file path
        #[arg(long, short = 'c')]
        config: Option<PathBuf>,

        /// Skip test files
        #[arg(long)]
        ignore_tests: bool,
    },

    /// Enforce egress policy on a command via a local HTTP proxy
    #[cfg(feature = "runtime")]
    Wrap {
        /// Path to egress policy file (agentshield.egress.toml)
        #[arg(long, value_name = "PATH")]
        policy: PathBuf,

        /// Path to an operator override policy (same format). Can only restrict, never expand.
        #[arg(long = "override-policy", value_name = "PATH")]
        override_policy: Option<PathBuf>,

        /// Audit log output path (overrides policy config)
        #[arg(long, value_name = "PATH")]
        audit_log: Option<PathBuf>,

        /// The command to wrap (use -- before the command)
        #[arg(last = true, required = true)]
        command: Vec<String>,
    },
}

#[derive(Subcommand)]
enum CiCommand {
    /// Generate a GitHub Actions workflow for AgentShield
    Install {
        /// Workflow output path
        #[arg(long, short = 'o', default_value = ".github/workflows/agentshield.yml")]
        output: PathBuf,

        /// Overwrite an existing workflow file
        #[arg(long)]
        force: bool,

        /// Repository path to scan in CI
        #[arg(long, default_value = ".")]
        scan_path: String,

        /// Minimum severity to fail (info, low, medium, high, critical)
        #[arg(long, default_value = "high")]
        fail_on: String,

        /// Include test files in CI scans
        #[arg(long)]
        include_tests: bool,

        /// Baseline file to filter existing findings in CI
        #[arg(long, value_name = "PATH")]
        baseline: Option<String>,

        /// Disable SARIF upload in the generated workflow
        #[arg(long)]
        no_sarif: bool,
    },
}

fn main() {
    let cli = Cli::parse();

    let result = match cli.command {
        Commands::Scan {
            path,
            config,
            format,
            fail_on,
            output,
            ignore_tests,
            baseline,
            write_baseline,
            emit_egress_policy,
            explain,
        } => cmd_scan(ScanArgs {
            path,
            config,
            format_str: format,
            fail_on_str: fail_on,
            output_path: output,
            ignore_tests,
            baseline_path: baseline,
            write_baseline_path: write_baseline,
            emit_egress_policy_path: emit_egress_policy,
            explain,
        }),
        Commands::Quickstart {
            path,
            force,
            fail_on,
            include_tests,
        } => cmd_quickstart(path, force, fail_on, include_tests),
        Commands::Ci { command } => match command {
            CiCommand::Install {
                output,
                force,
                scan_path,
                fail_on,
                include_tests,
                baseline,
                no_sarif,
            } => cmd_ci_install(
                output,
                force,
                scan_path,
                fail_on,
                include_tests,
                baseline,
                no_sarif,
            ),
        },
        Commands::ListRules { format } => cmd_list_rules(format),
        Commands::Init { force } => cmd_init(force),
        Commands::Suppress {
            fingerprint,
            reason,
            expires,
            config,
        } => cmd_suppress(fingerprint, reason, expires, config),
        Commands::ListSuppressions { config } => cmd_list_suppressions(config),
        Commands::Doctor {
            path,
            config,
            json,
            ignore_tests,
        } => cmd_doctor(path, config, json, ignore_tests),
        #[cfg(feature = "runtime-guard")]
        Commands::Guard {
            stdin,
            mcp_proxy,
            config,
            server,
        } => {
            if mcp_proxy {
                if server.is_empty() {
                    cmd_mcp_proxy(config)
                } else {
                    cmd_mcp_proxy_transport(config, server)
                }
            } else {
                cmd_guard(stdin)
            }
        }
        Commands::Certify {
            path,
            sign_key,
            output,
            config,
            ignore_tests,
        } => cmd_certify(path, sign_key, output, config, ignore_tests),
        #[cfg(feature = "runtime")]
        Commands::Wrap {
            policy,
            override_policy,
            audit_log,
            command,
        } => cmd_wrap(policy, override_policy, audit_log, command),
    };

    match result {
        Ok(exit_code) => process::exit(exit_code),
        Err(e) => {
            eprintln!("Error: {}", e);
            process::exit(e.exit_code());
        }
    }
}

#[cfg(feature = "runtime-guard")]
fn cmd_guard(read_stdin: bool) -> agentshield::error::Result<i32> {
    if !read_stdin {
        return emit_invalid_guard_input("unsupported runtime guard invocation", false);
    }

    let mut input = Vec::new();
    let read_result = std::io::stdin()
        .lock()
        .take((GUARD_STDIN_MAX_BYTES + 1) as u64)
        .read_to_end(&mut input);

    if read_result.is_err() {
        return emit_invalid_guard_input("runtime guard stdin read failed", true);
    }

    if input.len() > GUARD_STDIN_MAX_BYTES {
        return emit_invalid_guard_input("runtime guard stdin exceeds 1048576 byte limit", true);
    }

    let input = match String::from_utf8(input) {
        Ok(input) => input,
        Err(_) => return emit_invalid_guard_input("non-UTF-8 runtime guard input", true),
    };

    let event: RuntimeEvent = match serde_json::from_str(&input) {
        Ok(event) => event,
        Err(err) => {
            let reason = match err.classify() {
                serde_json::error::Category::Eof => "truncated JSON runtime guard input",
                serde_json::error::Category::Syntax | serde_json::error::Category::Data => {
                    "malformed JSON runtime guard input"
                }
                serde_json::error::Category::Io => "runtime guard JSON read failed",
            };
            return emit_invalid_guard_input(reason, true);
        }
    };

    let result = evaluate_runtime_event(event);
    let verdict = result.verdict;
    // Emit without `?`: a serialization or broken-pipe error must not propagate
    // to the generic exit code (2) and read as "not blocked". The guard fails
    // closed — any output failure maps to the block code.
    if emit_guard_result(&result).is_err() {
        return Ok(GUARD_BLOCK_EXIT);
    }

    match verdict {
        RuntimeVerdict::Allow | RuntimeVerdict::Warn => Ok(0),
        RuntimeVerdict::Block => Ok(GUARD_BLOCK_EXIT),
    }
}

/// Exit code signalling a fail-closed block from the runtime guard.
#[cfg(feature = "runtime-guard")]
const GUARD_BLOCK_EXIT: i32 = 3;

/// Run the experimental MCP JSON-RPC proxy guard.
///
/// Reads JSON-RPC messages one per line from stdin. Each is evaluated by the
/// shared decision core: `tools/call` requests are checked against
/// `[runtime.proxy]` policy and either forwarded or blocked; everything else
/// passes through. For a forwarded message the proxy emits a `{"forward": ...}`
/// envelope carrying the original request (a downstream MCP server transport
/// would consume this); for a blocked message it emits the JSON-RPC error.
/// Fails closed: a line that is not valid JSON is blocked.
#[cfg(feature = "runtime-guard")]
fn cmd_mcp_proxy(config_path: Option<std::path::PathBuf>) -> agentshield::error::Result<i32> {
    let policy = load_proxy_policy(config_path);
    agentshield::runtime::mcp_proxy_stdio::run_line_mode(
        &policy,
        GUARD_STDIN_MAX_BYTES,
        GUARD_BLOCK_EXIT,
    )
    .map_err(agentshield::error::ShieldError::Io)
}

/// Build a `ProxyPolicy` from the `[runtime.proxy]` config section.
#[cfg(feature = "runtime-guard")]
fn load_proxy_policy(config_path: Option<std::path::PathBuf>) -> agentshield::runtime::ProxyPolicy {
    use agentshield::config::{Config, ProxyFailOn};
    use agentshield::runtime::{FailOn, ProxyPolicy};

    fn map_fail_on(value: ProxyFailOn) -> FailOn {
        match value {
            ProxyFailOn::Block => FailOn::Block,
            ProxyFailOn::Warn => FailOn::Warn,
            ProxyFailOn::Never => FailOn::Never,
        }
    }

    let path = config_path.unwrap_or_else(|| std::path::PathBuf::from(".agentshield.toml"));
    // A missing/invalid config falls back to defaults (block-on-block).
    let config = Config::load(&path).unwrap_or_default();

    ProxyPolicy {
        fail_on: map_fail_on(config.runtime.proxy.fail_on),
        tool_overrides: config
            .runtime
            .proxy
            .tool_overrides
            .into_iter()
            .map(|override_entry| (override_entry.name, map_fail_on(override_entry.fail_on)))
            .collect(),
    }
}

/// Run the MCP proxy with a real bidirectional stdio bridge to a downstream
/// server. Spawns `server` (argv), forwards pass-through / allowed `tools/call`
/// requests to it and streams its responses back to the client, and answers a
/// blocked `tools/call` itself (the server never sees it).
///
/// Fails closed: if the server cannot be spawned, every call is blocked. A
/// malformed or oversized client line is blocked without forwarding.
#[cfg(feature = "runtime-guard")]
fn cmd_mcp_proxy_transport(
    config_path: Option<std::path::PathBuf>,
    server: Vec<String>,
) -> agentshield::error::Result<i32> {
    let policy = load_proxy_policy(config_path);
    agentshield::runtime::mcp_proxy_stdio::run_transport(
        &policy,
        &server,
        GUARD_STDIN_MAX_BYTES,
        GUARD_BLOCK_EXIT,
    )
    .map_err(agentshield::error::ShieldError::Io)
}

/// Serialize and print a guard result. Returns Err only on a serialization or
/// stdout-write failure, which the caller maps to a fail-closed block.
#[cfg(feature = "runtime-guard")]
fn emit_guard_result(
    result: &agentshield::runtime::RuntimeGuardResult,
) -> Result<(), Box<dyn std::error::Error>> {
    let rendered = serde_json::to_string_pretty(result)?;
    use std::io::Write;
    writeln!(std::io::stdout(), "{rendered}")?;
    Ok(())
}

#[cfg(feature = "runtime-guard")]
fn emit_invalid_guard_input(reason: &str, redacted: bool) -> agentshield::error::Result<i32> {
    let result = invalid_runtime_guard_input(reason, redacted);
    // Ignore output errors: the verdict is already block, and a write failure
    // must not downgrade the exit code away from the fail-closed block.
    let _ = emit_guard_result(&result);
    Ok(GUARD_BLOCK_EXIT)
}

/// Arguments for the scan subcommand, extracted to avoid too-many-arguments.
struct ScanArgs {
    path: PathBuf,
    config: Option<PathBuf>,
    format_str: String,
    fail_on_str: Option<String>,
    output_path: Option<PathBuf>,
    ignore_tests: bool,
    baseline_path: Option<PathBuf>,
    write_baseline_path: Option<PathBuf>,
    emit_egress_policy_path: Option<PathBuf>,
    explain: bool,
}

fn cmd_scan(args: ScanArgs) -> Result<i32, agentshield::error::ShieldError> {
    let ScanArgs {
        path,
        config,
        format_str,
        fail_on_str,
        output_path,
        ignore_tests,
        baseline_path,
        write_baseline_path,
        emit_egress_policy_path,
        explain,
    } = args;
    let format = OutputFormat::from_str_lenient(&format_str).unwrap_or_else(|| {
        eprintln!("Warning: unknown format '{}', using console", format_str);
        OutputFormat::Console
    });

    if explain && format != OutputFormat::Console {
        return Err(agentshield::error::ShieldError::Config(
            "`scan --explain` is console-only; remove --format or use --format console".into(),
        ));
    }

    let fail_on = parse_optional_severity(fail_on_str.as_deref());
    let effective_ignore_tests = effective_ignore_tests(&path, config.as_ref(), ignore_tests)?;
    let effective_path_filter =
        effective_path_filter(&path, config.as_ref(), effective_ignore_tests)?;
    let path_filter_summary = effective_path_filter.summary();

    let options = ScanOptions {
        config_path: config.clone(),
        format,
        fail_on_override: fail_on,
        ignore_tests,
    };

    let mut report = match agentshield::scan(&path, &options) {
        Ok(report) => report,
        Err(err) if explain && agentshield::ux::is_no_adapter(&err) => {
            let rendered = agentshield::ux::render_no_adapter_explain(
                &path,
                effective_ignore_tests,
                &path_filter_summary,
            );
            write_rendered(output_path.as_ref(), &rendered)?;
            return Ok(2);
        }
        Err(err) => return Err(err),
    };

    // Filter out baseline findings if --baseline is provided
    if let Some(ref bl_path) = baseline_path {
        let baseline = BaselineFile::load(bl_path)?;
        report.findings.retain(|f| {
            let fp = f.fingerprint(&report.scan_root);
            !baseline.contains(&fp)
        });
        // Re-evaluate verdict with filtered findings
        let config_path = options
            .config_path
            .clone()
            .unwrap_or_else(|| path.join(".agentshield.toml"));
        let mut cfg = agentshield::config::Config::load(&config_path)?;
        if let Some(fail_on_sev) = fail_on {
            cfg.policy.fail_on = fail_on_sev;
        }
        report.verdict = cfg.policy.evaluate(&report.findings);
    }

    // Write baseline if --write-baseline is provided
    if let Some(ref wb_path) = write_baseline_path {
        let now = chrono::Utc::now().to_rfc3339();
        let entries: Vec<BaselineEntry> = report
            .findings
            .iter()
            .map(|f| BaselineEntry {
                fingerprint: f.fingerprint(&report.scan_root),
                rule_id: f.rule_id.clone(),
                first_seen: now.clone(),
            })
            .collect();
        let baseline = BaselineFile::new(entries);
        baseline.save(wb_path)?;
        eprintln!(
            "Wrote {} findings to baseline: {}",
            report.findings.len(),
            wb_path.display()
        );
    }

    // Emit egress policy if --emit-egress-policy is provided
    if let Some(ref egress_path) = emit_egress_policy_path {
        let policy = EgressPolicy::from_scan_targets(&report.targets);
        policy.save(egress_path)?;
        eprintln!(
            "Wrote egress policy with {} allowed domain(s) to {}",
            policy.domains.allow.len(),
            egress_path.display()
        );
    }

    let rendered = if explain {
        agentshield::ux::render_explain(
            &report,
            &ExplainOptions {
                ignore_tests: effective_ignore_tests,
            },
        )
    } else {
        agentshield::render_report(&report, format)?
    };

    write_rendered(output_path.as_ref(), &rendered)?;

    // Exit code: 0 = pass, 1 = findings above threshold
    Ok(if report.verdict.pass { 0 } else { 1 })
}

fn cmd_quickstart(
    path: PathBuf,
    force: bool,
    fail_on_str: String,
    include_tests: bool,
) -> Result<i32, agentshield::error::ShieldError> {
    let fail_on = require_severity(&fail_on_str)?;
    let ignore_tests = !include_tests;
    let config_path = path.join(".agentshield.toml");

    println!("AgentShield quickstart");
    println!("Project: {}", path.display());

    if config_path.exists() && !force {
        println!(
            "Config: {} already exists; left unchanged",
            config_path.display()
        );
    } else {
        if let Some(parent) = non_empty_parent(&config_path) {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(
            &config_path,
            agentshield::ux::quickstart_config_toml(fail_on, ignore_tests),
        )?;
        println!("Config: created {}", config_path.display());
    }

    println!(
        "CI: run `agentshield ci install --scan-path {}` to add GitHub Actions",
        shell_display_path(&path)
    );
    println!();

    let options = ScanOptions {
        config_path: Some(config_path),
        format: OutputFormat::Console,
        fail_on_override: Some(fail_on),
        ignore_tests,
    };

    match agentshield::scan(&path, &options) {
        Ok(report) => {
            let rendered =
                agentshield::ux::render_explain(&report, &ExplainOptions { ignore_tests });
            print!("{rendered}");
            Ok(if report.verdict.pass { 0 } else { 1 })
        }
        Err(err) if agentshield::ux::is_no_adapter(&err) => {
            print!(
                "{}",
                agentshield::ux::render_no_adapter_explain(
                    &path,
                    ignore_tests,
                    &ScanPathFilterSummary::default(),
                )
            );
            Ok(0)
        }
        Err(err) => Err(err),
    }
}

fn cmd_ci_install(
    output: PathBuf,
    force: bool,
    scan_path: String,
    fail_on_str: String,
    include_tests: bool,
    baseline: Option<String>,
    no_sarif: bool,
) -> Result<i32, agentshield::error::ShieldError> {
    let fail_on = require_severity(&fail_on_str)?;
    let fail_on = fail_on.to_string();

    if output.exists() && !force {
        eprintln!(
            "{} already exists. Use --force to overwrite.",
            output.display()
        );
        return Ok(1);
    }

    if let Some(parent) = non_empty_parent(&output) {
        std::fs::create_dir_all(parent)?;
    }

    let workflow = agentshield::ux::github_actions_workflow(&CiInstallOptions {
        fail_on: &fail_on,
        ignore_tests: !include_tests,
        scan_path: &scan_path,
        baseline_path: baseline.as_deref(),
        upload_sarif: !no_sarif,
    });
    std::fs::write(&output, workflow)?;
    println!("Created {}", output.display());
    println!("CI gate: scans `{scan_path}` and fails on `{fail_on}` findings or higher.");
    if !no_sarif {
        println!("SARIF upload: enabled for GitHub Code Scanning.");
    }
    if let Some(baseline) = baseline {
        println!("Baseline: filters known findings from `{baseline}`.");
    }
    Ok(0)
}

fn parse_optional_severity(value: Option<&str>) -> Option<Severity> {
    value.and_then(|s| {
        let sev = Severity::from_str_lenient(s);
        if sev.is_none() {
            eprintln!("Warning: unknown severity '{}', using config default", s);
        }
        sev
    })
}

fn require_severity(value: &str) -> Result<Severity, agentshield::error::ShieldError> {
    Severity::from_str_lenient(value).ok_or_else(|| {
        agentshield::error::ShieldError::Config(format!(
            "unknown severity '{value}' (expected info, low, medium, high, or critical)"
        ))
    })
}

fn effective_ignore_tests(
    path: &std::path::Path,
    config_path: Option<&PathBuf>,
    cli_ignore_tests: bool,
) -> Result<bool, agentshield::error::ShieldError> {
    let resolved_config_path = config_path
        .cloned()
        .unwrap_or_else(|| path.join(".agentshield.toml"));
    let config = Config::load(&resolved_config_path)?;
    Ok(cli_ignore_tests || config.scan.ignore_tests)
}

fn effective_path_filter(
    path: &std::path::Path,
    config_path: Option<&PathBuf>,
    ignore_tests: bool,
) -> Result<ScanPathFilter, agentshield::error::ShieldError> {
    let resolved_config_path = config_path
        .cloned()
        .unwrap_or_else(|| path.join(".agentshield.toml"));
    let config = Config::load(&resolved_config_path)?;
    ScanPathFilter::from_scan_config(&config.scan, ignore_tests)
}

fn write_rendered(
    output_path: Option<&PathBuf>,
    rendered: &str,
) -> Result<(), agentshield::error::ShieldError> {
    match output_path {
        Some(out) => std::fs::write(out, rendered)?,
        None => print!("{rendered}"),
    }
    Ok(())
}

fn non_empty_parent(path: &std::path::Path) -> Option<&std::path::Path> {
    path.parent()
        .filter(|parent| !parent.as_os_str().is_empty())
}

fn shell_display_path(path: &std::path::Path) -> String {
    let text = path.display().to_string();
    if text.contains(' ') {
        format!("'{}'", text.replace('\'', "'\\''"))
    } else {
        text
    }
}

fn cmd_doctor(
    path: PathBuf,
    config: Option<PathBuf>,
    json: bool,
    ignore_tests: bool,
) -> Result<i32, agentshield::error::ShieldError> {
    let report = agentshield::doctor::run_doctor(&path, config, ignore_tests)?;

    if json {
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else {
        print_doctor_console(&report);
    }

    Ok(0)
}

fn print_doctor_console(report: &DoctorReport) {
    println!("AgentShield doctor");
    println!("Version: {}", report.version);
    println!("Target: {}", report.target.display());
    println!(
        "Config: {} ({})",
        report.config_path.display(),
        if report.config_found {
            "found"
        } else {
            "not found, using defaults"
        }
    );
    println!("Fail on: {}", report.fail_on);
    println!("Ignore tests: {}", report.ignore_tests);
    println!(
        "Features: python={}, typescript={}, runtime={}",
        report.enabled_features.python,
        report.enabled_features.typescript,
        report.enabled_features.runtime
    );
    println!(
        "Adapters: detected [{}], available [{}]",
        report.detected_adapters.join(", "),
        report.available_adapters.join(", ")
    );
    println!(
        "Runtime wrap: {}",
        if report.runtime_wrap_available {
            "available"
        } else {
            "not available"
        }
    );
}

fn cmd_list_rules(format_str: String) -> Result<i32, agentshield::error::ShieldError> {
    let engine = RuleEngine::new();
    let rules = engine.list_rules();

    match format_str.as_str() {
        "json" => {
            let json = serde_json::to_string_pretty(&rules)?;
            println!("{}", json);
        }
        _ => {
            println!(
                "{:<12} {:<28} {:<10} {:<8} CATEGORY",
                "ID", "NAME", "SEVERITY", "CWE"
            );
            println!("{}", "-".repeat(80));
            for rule in &rules {
                println!(
                    "{:<12} {:<28} {:<10} {:<8} {}",
                    rule.id,
                    rule.name,
                    rule.default_severity.to_string(),
                    rule.cwe_id.as_deref().unwrap_or("-"),
                    rule.attack_category,
                );
            }
        }
    }

    Ok(0)
}

fn cmd_init(force: bool) -> Result<i32, agentshield::error::ShieldError> {
    let path = PathBuf::from(".agentshield.toml");

    if path.exists() && !force {
        eprintln!(".agentshield.toml already exists. Use --force to overwrite.");
        return Ok(1);
    }

    std::fs::write(&path, Config::starter_toml())?;
    println!("Created .agentshield.toml");

    Ok(0)
}

fn cmd_suppress(
    fingerprint: String,
    reason: String,
    expires: Option<String>,
    config: Option<PathBuf>,
) -> Result<i32, agentshield::error::ShieldError> {
    use agentshield::rules::policy::Suppression;

    if reason.trim().is_empty() {
        eprintln!("Error: --reason must be a non-empty string");
        return Ok(2);
    }

    // Validate the expires date format if provided
    if let Some(ref date_str) = expires {
        if chrono::NaiveDate::parse_from_str(date_str, "%Y-%m-%d").is_err() {
            eprintln!(
                "Error: --expires '{}' is not a valid date (expected YYYY-MM-DD)",
                date_str
            );
            return Ok(2);
        }
    }

    let config_path = config.unwrap_or_else(|| PathBuf::from(".agentshield.toml"));

    // Load existing config (or default if file doesn't exist)
    let mut cfg = Config::load(&config_path)?;

    let created_at = chrono::Utc::now().format("%Y-%m-%d").to_string();
    let suppression = Suppression {
        fingerprint: fingerprint.clone(),
        reason: reason.clone(),
        expires: expires.clone(),
        created_at: Some(created_at),
    };

    cfg.policy.suppressions.push(suppression);

    // Serialize and write back
    let toml_str = toml::to_string_pretty(&cfg)?;
    std::fs::write(&config_path, &toml_str)?;

    let expires_display = expires
        .as_deref()
        .map(|d| format!(" (expires: {})", d))
        .unwrap_or_default();
    println!(
        "Suppressed finding {} : {}{}",
        &fingerprint[..fingerprint.len().min(12)],
        reason,
        expires_display
    );

    Ok(0)
}

fn cmd_list_suppressions(config: Option<PathBuf>) -> Result<i32, agentshield::error::ShieldError> {
    let config_path = config.unwrap_or_else(|| PathBuf::from(".agentshield.toml"));
    let cfg = Config::load(&config_path)?;
    let suppressions = &cfg.policy.suppressions;

    if suppressions.is_empty() {
        println!("No suppressions configured.");
        return Ok(0);
    }

    println!(
        "{:<16}  {:<40}  {:<10}  STATUS",
        "FINGERPRINT", "REASON", "EXPIRES"
    );
    println!("{}", "-".repeat(80));

    for s in suppressions {
        let fp_short = &s.fingerprint[..s.fingerprint.len().min(16)];
        let reason_truncated = if s.reason.len() > 40 {
            format!("{}...", &s.reason[..37])
        } else {
            s.reason.clone()
        };
        let expires_display = s.expires.as_deref().unwrap_or("-");
        let status = if s.is_expired() { "expired" } else { "active" };

        println!(
            "{:<16}  {:<40}  {:<10}  {}",
            fp_short, reason_truncated, expires_display, status
        );
    }

    Ok(0)
}

fn cmd_certify(
    path: PathBuf,
    sign_key: Option<PathBuf>,
    output: Option<PathBuf>,
    config: Option<PathBuf>,
    ignore_tests: bool,
) -> Result<i32, agentshield::error::ShieldError> {
    use agentshield::certify::envelope::{build_attestation, DsseEnvelope};

    let options = ScanOptions {
        config_path: config.clone(),
        format: OutputFormat::Console,
        fail_on_override: None,
        ignore_tests,
    };

    let report = agentshield::scan(&path, &options)?;

    // Load suppressions from config
    let config_path = config.unwrap_or_else(|| path.join(".agentshield.toml"));
    let cfg = Config::load(&config_path)?;
    let suppressions = &cfg.policy.suppressions;

    let payload = build_attestation(
        &report.scan_root,
        &report.findings,
        suppressions,
        &report.targets,
        None,
    );

    let mut envelope = DsseEnvelope::new(&payload)?;

    // Optionally sign with Ed25519 key
    if let Some(key_path) = sign_key {
        let key_bytes = std::fs::read(&key_path).map_err(|e| {
            agentshield::error::ShieldError::Internal(format!(
                "Failed to read signing key '{}': {}",
                key_path.display(),
                e
            ))
        })?;
        envelope.sign(&key_bytes)?;
        eprintln!("Signed attestation with key: {}", key_path.display());
    }

    let json = serde_json::to_string_pretty(&envelope)?;

    match output {
        Some(out) => {
            std::fs::write(&out, &json)?;
            eprintln!(
                "Wrote attestation to: {} ({} findings)",
                out.display(),
                report.findings.len()
            );
        }
        None => print!("{}", json),
    }

    Ok(0)
}

#[cfg(feature = "runtime")]
fn cmd_wrap(
    policy_path: PathBuf,
    override_policy_path: Option<PathBuf>,
    audit_log: Option<PathBuf>,
    command: Vec<String>,
) -> Result<i32, agentshield::error::ShieldError> {
    use std::sync::Arc;

    if command.is_empty() {
        return Err(agentshield::error::ShieldError::Internal(
            "No command provided to wrap".to_string(),
        ));
    }

    let base = EgressPolicy::load(&policy_path)?;

    // Apply operator override (restricts, never expands)
    let mut policy = if let Some(ref override_path) = override_policy_path {
        let operator = EgressPolicy::load(override_path).map_err(|e| {
            agentshield::error::ShieldError::Internal(format!(
                "Failed to load override policy '{}': {}",
                override_path.display(),
                e
            ))
        })?;
        eprintln!(
            "agentshield: applying operator override policy: {}",
            override_path.display()
        );
        base.merge_override(&operator)
    } else {
        base
    };

    if let Some(log_path) = audit_log {
        policy.audit.log_path = Some(log_path);
    }

    let proxy = Arc::new(EgressProxy::new(policy)?);

    // Build a tokio runtime to run the proxy
    let rt = tokio::runtime::Runtime::new()
        .map_err(|e| agentshield::error::ShieldError::Internal(format!("tokio runtime: {}", e)))?;

    let exit_code = rt.block_on(async {
        let (listener, addr) = proxy.bind().await?;

        // Spawn proxy loop in background
        let proxy_clone = Arc::clone(&proxy);
        let proxy_handle = tokio::spawn(async move {
            proxy_clone.run(listener).await;
        });

        let proxy_url = format!("http://{}", addr);

        eprintln!("agentshield: proxy listening on {}", addr);
        eprintln!("agentshield: wrapping command: {}", command.join(" "));

        // Launch child process with proxy env vars
        let mut child = std::process::Command::new(&command[0])
            .args(&command[1..])
            .env("HTTP_PROXY", &proxy_url)
            .env("HTTPS_PROXY", &proxy_url)
            .env("http_proxy", &proxy_url)
            .env("https_proxy", &proxy_url)
            .spawn()
            .map_err(|e| {
                agentshield::error::ShieldError::Internal(format!(
                    "Failed to start command '{}': {}",
                    command[0], e
                ))
            })?;

        let status = child.wait().map_err(|e| {
            agentshield::error::ShieldError::Internal(format!("Failed to wait for command: {}", e))
        })?;

        // Shutdown proxy
        proxy_handle.abort();

        Ok::<i32, agentshield::error::ShieldError>(status.code().unwrap_or(1))
    })?;

    process::exit(exit_code);
}