aaai-cli 0.10.7

Command-line interface for aaai — audit for asset integrity
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
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
//! Integration tests for the aaai CLI binary.
//!
//! These tests build and invoke the actual binary to verify end-to-end
//! behaviour — argument parsing, exit codes, and output format.

use std::fs;
use std::path::Path;
use std::process::Command;

// ── helpers ──────────────────────────────────────────────────────────────

fn aaai() -> Command {
    // Find the binary relative to the workspace target directory.
    let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    path.pop(); // crates/aaai-cli -> crates
    path.pop(); // crates -> workspace root
    path.push("target");
    path.push("debug");
    path.push("aaai");
    Command::new(path)
}

fn setup_dirs(before: &Path, after: &Path) {
    fs::create_dir_all(before).unwrap();
    fs::create_dir_all(after).unwrap();
}

fn write(dir: &Path, name: &str, content: &str) {
    fs::write(dir.join(name), content).unwrap();
}

fn write_audit(path: &Path, yaml: &str) {
    fs::write(path, yaml).unwrap();
}

// ── audit subcommand ──────────────────────────────────────────────────────

#[test]
fn audit_exits_0_when_all_ok() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&b, "f.txt", "hello\n");
    write(&a, "f.txt", "hello world\n");

    let audit_yaml = tmp.path().join("audit.yaml");
    write_audit(&audit_yaml, r#"version: "1"
entries:
  - path: f.txt
    diff_type: Modified
    reason: "Intentional change"
    strategy:
      type: None
    enabled: true
"#);

    let status = aaai()
        .args(["audit", "--left", b.to_str().unwrap(),
               "--right", a.to_str().unwrap(),
               "--config", audit_yaml.to_str().unwrap(),
               "--no-history"])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
}

#[test]
fn audit_exits_1_on_failed_entry() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&b, "cfg.toml", "port = 80\n");
    write(&a, "cfg.toml", "port = 9999\n");

    let audit_yaml = tmp.path().join("audit.yaml");
    write_audit(&audit_yaml, r#"version: "1"
entries:
  - path: cfg.toml
    diff_type: Modified
    reason: "Port change"
    strategy:
      type: LineMatch
      rules:
        - action: Removed
          line: "port = 80"
        - action: Added
          line: "port = 8080"
    enabled: true
"#);

    let status = aaai()
        .args(["audit", "--left", b.to_str().unwrap(),
               "--right", a.to_str().unwrap(),
               "--config", audit_yaml.to_str().unwrap(),
               "--no-history"])
        .status().unwrap();
    assert_eq!(status.code(), Some(1), "Failed audit should exit 1");
}

#[test]
fn audit_exits_2_on_pending_entry() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&a, "new.txt", "content\n");

    // Empty audit definition → new.txt will be Pending.
    let audit_yaml = tmp.path().join("audit.yaml");
    write_audit(&audit_yaml, "version: \"1\"\n");

    let status = aaai()
        .args(["audit", "--left", b.to_str().unwrap(),
               "--right", a.to_str().unwrap(),
               "--config", audit_yaml.to_str().unwrap(),
               "--no-history"])
        .status().unwrap();
    assert_eq!(status.code(), Some(2), "Pending should exit 2");
}

#[test]
fn audit_exit_0_with_allow_pending() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&a, "new.txt", "content\n");
    let audit_yaml = tmp.path().join("audit.yaml");
    write_audit(&audit_yaml, "version: \"1\"\n");

    let status = aaai()
        .args(["audit", "--left", b.to_str().unwrap(),
               "--right", a.to_str().unwrap(),
               "--config", audit_yaml.to_str().unwrap(),
               "--allow-pending", "--no-history"])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
}

#[test]
fn audit_json_output_is_valid_json() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&b, "f.txt", "a\n");
    write(&a, "f.txt", "b\n");

    let audit_yaml = tmp.path().join("audit.yaml");
    write_audit(&audit_yaml, r#"version: "1"
entries:
  - path: f.txt
    diff_type: Modified
    reason: "test"
    strategy:
      type: None
    enabled: true
"#);

    let out = aaai()
        .args(["audit", "--left", b.to_str().unwrap(),
               "--right", a.to_str().unwrap(),
               "--config", audit_yaml.to_str().unwrap(),
               "--json-output", "--no-history"])
        .output().unwrap();
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(serde_json::from_str::<serde_json::Value>(&stdout).is_ok(),
        "JSON output must be valid JSON; got: {stdout}");
}

// ── snap subcommand ───────────────────────────────────────────────────────

#[test]
fn snap_generates_definition_file() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&a, "added.txt", "new\n");
    write(&b, "removed.txt", "old\n");

    let out_path = tmp.path().join("audit.yaml");
    let status = aaai()
        .args(["snap", "--left", b.to_str().unwrap(),
               "--right", a.to_str().unwrap(),
               "--out", out_path.to_str().unwrap()])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
    assert!(out_path.exists(), "snap should create the output file");
    let content = fs::read_to_string(&out_path).unwrap();
    assert!(content.contains("added.txt") || content.contains("removed.txt"),
        "snap output should list diffed files");
}

#[test]
fn snap_dry_run_does_not_write_file() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&a, "new.txt", "hi\n");

    let out_path = tmp.path().join("audit.yaml");
    let status = aaai()
        .args(["snap", "--left", b.to_str().unwrap(),
               "--right", a.to_str().unwrap(),
               "--out", out_path.to_str().unwrap(),
               "--dry-run"])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
    assert!(!out_path.exists(), "--dry-run must NOT write the file");
}

// ── check subcommand ──────────────────────────────────────────────────────

#[test]
fn check_exits_0_for_valid_definition() {
    let tmp = tempfile::tempdir().unwrap();
    let yaml = tmp.path().join("audit.yaml");
    write_audit(&yaml, r#"version: "1"
entries:
  - path: f.txt
    diff_type: Modified
    reason: "test"
    strategy:
      type: None
    enabled: true
"#);
    let status = aaai()
        .args(["check", yaml.to_str().unwrap()])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
}

#[test]
fn check_exits_nonzero_for_invalid_yaml() {
    let tmp = tempfile::tempdir().unwrap();
    let yaml = tmp.path().join("bad.yaml");
    write_audit(&yaml, "not: valid: yaml: [[[");
    let status = aaai()
        .args(["check", yaml.to_str().unwrap()])
        .status().unwrap();
    assert_ne!(status.code(), Some(0), "invalid YAML must fail check");
}

// ── report subcommand ─────────────────────────────────────────────────────

#[test]
fn report_markdown_creates_file() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    let yaml = tmp.path().join("audit.yaml");
    write_audit(&yaml, "version: \"1\"\n");
    let out = tmp.path().join("report.md");

    let status = aaai()
        .args(["report", "--left", b.to_str().unwrap(),
               "--right", a.to_str().unwrap(),
               "--config", yaml.to_str().unwrap(),
               "--out", out.to_str().unwrap()])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
    assert!(out.exists());
    let content = fs::read_to_string(&out).unwrap();
    assert!(content.contains("aaai Audit Report"));
}

#[test]
fn report_html_creates_valid_file() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&b, "f.txt", "old\n");
    write(&a, "f.txt", "new\n");
    let yaml = tmp.path().join("audit.yaml");
    write_audit(&yaml, r#"version: "1"
entries:
  - path: f.txt
    diff_type: Modified
    reason: "html test"
    strategy:
      type: None
    enabled: true
"#);
    let out = tmp.path().join("report.html");

    let status = aaai()
        .args(["report", "--left", b.to_str().unwrap(),
               "--right", a.to_str().unwrap(),
               "--config", yaml.to_str().unwrap(),
               "--format", "html",
               "--out", out.to_str().unwrap()])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
    assert!(out.exists());
    let content = fs::read_to_string(&out).unwrap();
    assert!(content.contains("<!DOCTYPE html>"), "HTML report should start with DOCTYPE");
    assert!(content.contains("aaai Audit Report"));
}

// ── glob rule ─────────────────────────────────────────────────────────────

#[test]
fn glob_rule_matches_multiple_files() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    fs::create_dir_all(b.join("logs")).unwrap();
    fs::create_dir_all(a.join("logs")).unwrap();
    write(&b.join("logs"), "app.log", "old\n");
    write(&a.join("logs"), "app.log", "new\n");
    write(&b.join("logs"), "db.log", "old\n");
    write(&a.join("logs"), "db.log", "new\n");

    let yaml = tmp.path().join("audit.yaml");
    write_audit(&yaml, r#"version: "1"
entries:
  - path: "logs/*.log"
    diff_type: Modified
    reason: "Log rotation"
    strategy:
      type: None
    enabled: true
"#);

    let status = aaai()
        .args(["audit", "--left", b.to_str().unwrap(),
               "--right", a.to_str().unwrap(),
               "--config", yaml.to_str().unwrap(),
               "--no-history"])
        .status().unwrap();
    assert_eq!(status.code(), Some(0), "glob rule should match both log files");
}

// ── Phase 7: new commands ────────────────────────────────────────────────

#[test]
fn diff_exits_0_and_shows_changes() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&b, "old.txt", "line1\n");
    write(&a, "new.txt", "line2\n");
    write(&b, "same.txt", "same\n");
    write(&a, "same.txt", "same\n");

    let out = aaai()
        .args(["diff", "--left", b.to_str().unwrap(),
               "--right", a.to_str().unwrap()])
        .output().unwrap();
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(stdout.contains("old.txt") || stdout.contains("new.txt"),
        "diff should mention changed files");
}

#[test]
fn diff_json_output_is_valid() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&a, "added.txt", "content\n");

    let out = aaai()
        .args(["diff", "--left", b.to_str().unwrap(),
               "--right", a.to_str().unwrap(),
               "--json-output"])
        .output().unwrap();
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&stdout)
        .expect("diff --json-output must produce valid JSON");
    assert!(parsed.is_array(), "diff JSON output should be an array");
}

#[test]
fn export_csv_produces_header_row() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&b, "f.txt", "old\n");
    write(&a, "f.txt", "new\n");
    let yaml = tmp.path().join("audit.yaml");
    write_audit(&yaml, r#"version: "1"
entries:
  - path: f.txt
    diff_type: Modified
    reason: "test export"
    strategy:
      type: None
    enabled: true
"#);
    let out_csv = tmp.path().join("out.csv");

    let status = aaai()
        .args(["export", "--left", b.to_str().unwrap(),
               "--right", a.to_str().unwrap(),
               "--config", yaml.to_str().unwrap(),
               "--out", out_csv.to_str().unwrap()])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
    assert!(out_csv.exists());
    let content = fs::read_to_string(&out_csv).unwrap();
    let first_line = content.lines().next().unwrap_or("");
    assert!(first_line.contains("path"), "CSV header should contain 'path'");
    assert!(first_line.contains("reason"), "CSV header should contain 'reason'");
    assert!(first_line.contains("status"), "CSV header should contain 'status'");
}

#[test]
fn export_tsv_uses_tab_separator() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    let yaml = tmp.path().join("audit.yaml");
    write_audit(&yaml, "version: \"1\"\n");
    let out_tsv = tmp.path().join("out.tsv");

    let status = aaai()
        .args(["export", "--left", b.to_str().unwrap(),
               "--right", a.to_str().unwrap(),
               "--config", yaml.to_str().unwrap(),
               "--format", "tsv",
               "--out", out_tsv.to_str().unwrap()])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
    let content = fs::read_to_string(&out_tsv).unwrap();
    let first_line = content.lines().next().unwrap_or("");
    assert!(first_line.contains('\t'), "TSV header should use tab separator");
}

#[test]
fn merge_detect_conflicts() {
    let tmp = tempfile::tempdir().unwrap();
    let base = tmp.path().join("base.yaml");
    let overlay = tmp.path().join("overlay.yaml");
    write_audit(&base, r#"version: "1"
entries:
  - path: f.txt
    diff_type: Modified
    reason: "base"
    strategy:
      type: None
    enabled: true
"#);
    write_audit(&overlay, r#"version: "1"
entries:
  - path: f.txt
    diff_type: Added
    reason: "overlay"
    strategy:
      type: None
    enabled: true
"#);

    let out = aaai()
        .args(["merge", base.to_str().unwrap(), overlay.to_str().unwrap(),
               "--detect-conflicts"])
        .output().unwrap();
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(stdout.contains("conflict") || stdout.contains("Conflict"),
        "conflict detection should mention conflicts");
}

#[test]
fn report_sarif_format_valid() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    let yaml = tmp.path().join("audit.yaml");
    write_audit(&yaml, "version: \"1\"\n");
    let out = tmp.path().join("result.sarif");

    let status = aaai()
        .args(["report", "--left", b.to_str().unwrap(),
               "--right", a.to_str().unwrap(),
               "--config", yaml.to_str().unwrap(),
               "--format", "sarif",
               "--out", out.to_str().unwrap()])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
    let content = fs::read_to_string(&out).unwrap();
    let v: serde_json::Value = serde_json::from_str(&content)
        .expect("SARIF output must be valid JSON");
    assert_eq!(v["version"], "2.1.0", "SARIF version must be 2.1.0");
}

#[test]
fn history_stats_exits_0() {
    let status = aaai()
        .args(["history", "--stats"])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
}

#[test]
fn audit_warns_on_large_file_with_linematch() {
    // Verify the audit JSON output includes the Warning field / or at least exits cleanly.
    // (We can't easily create a >1 MB file in a quick test, so we verify the command works.)
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&b, "cfg.toml", "x = 1\n");
    write(&a, "cfg.toml", "x = 2\n");
    let yaml = tmp.path().join("audit.yaml");
    write_audit(&yaml, r#"version: "1"
entries:
  - path: cfg.toml
    diff_type: Modified
    reason: "value change"
    strategy:
      type: LineMatch
      rules:
        - action: Removed
          line: "x = 1"
        - action: Added
          line: "x = 2"
    enabled: true
"#);
    let out = aaai()
        .args(["audit", "--left", b.to_str().unwrap(),
               "--right", a.to_str().unwrap(),
               "--config", yaml.to_str().unwrap(),
               "--json-output", "--no-history"])
        .output().unwrap();
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).unwrap();
    let v: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(v["result"], "PASSED");
}

// ── Phase 9: previously untested commands ───────────────────────────────

#[test]
fn completions_bash_exits_0() {
    let out = aaai().args(["completions", "bash"]).output().unwrap();
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(stdout.contains("aaai"), "bash completion should mention 'aaai'");
}

#[test]
fn completions_zsh_exits_0() {
    let out = aaai().args(["completions", "zsh"]).output().unwrap();
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(!stdout.is_empty(), "zsh completion output should not be empty");
}

#[test]
fn config_init_creates_aaai_yaml() {
    let tmp = tempfile::tempdir().unwrap();
    let status = aaai()
        .args(["config", "--init", "--dir", tmp.path().to_str().unwrap()])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
    let config_path = tmp.path().join(".aaai.yaml");
    assert!(config_path.exists(), ".aaai.yaml should be created");
    let content = fs::read_to_string(&config_path).unwrap();
    assert!(content.contains("version"), ".aaai.yaml should contain 'version'");
}

#[test]
fn config_init_skips_existing() {
    let tmp = tempfile::tempdir().unwrap();
    // Create first
    aaai().args(["config", "--init", "--dir", tmp.path().to_str().unwrap()])
        .status().unwrap();
    // Try again — should report already exists, not overwrite
    let out = aaai()
        .args(["config", "--init", "--dir", tmp.path().to_str().unwrap()])
        .output().unwrap();
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(stdout.contains("already exists") || stdout.contains("既に"),
        "should report existing config");
}

#[test]
fn dashboard_exits_0() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    let yaml = tmp.path().join("audit.yaml");
    write_audit(&yaml, "version: \"1\"\n");

    let status = aaai()
        .args(["dashboard",
               "--left",   b.to_str().unwrap(),
               "--right",  a.to_str().unwrap(),
               "--config", yaml.to_str().unwrap()])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
}

#[test]
fn init_non_interactive_creates_config() {
    let tmp = tempfile::tempdir().unwrap();
    let status = aaai()
        .args(["init", "--dir", tmp.path().to_str().unwrap(), "--non-interactive"])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
    let config_path = tmp.path().join(".aaai.yaml");
    assert!(config_path.exists(), "non-interactive init should create .aaai.yaml");
}

#[test]
fn lint_json_output_valid() {
    let tmp = tempfile::tempdir().unwrap();
    let yaml = tmp.path().join("audit.yaml");
    write_audit(&yaml, r#"version: "1"
entries:
  - path: f.txt
    diff_type: Modified
    reason: "valid reason text here"
    strategy:
      type: None
    enabled: true
"#);
    let out = aaai()
        .args(["lint", yaml.to_str().unwrap(), "--json-output"])
        .output().unwrap();
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&stdout)
        .expect("lint --json-output must produce valid JSON");
    assert!(parsed.is_array(), "lint JSON must be an array");
}

#[test]
fn lint_json_output_finds_empty_linematch() {
    let tmp = tempfile::tempdir().unwrap();
    let yaml = tmp.path().join("audit.yaml");
    write_audit(&yaml, r#"version: "1"
entries:
  - path: f.txt
    diff_type: Modified
    reason: "reason here"
    strategy:
      type: LineMatch
      rules: []
    enabled: true
"#);
    let out = aaai()
        .args(["lint", yaml.to_str().unwrap(), "--json-output"])
        .output().unwrap();
    // Should exit 1 because of empty-linematch error
    assert_eq!(out.status.code(), Some(1));
    let stdout = String::from_utf8(out.stdout).unwrap();
    let issues: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let has_empty_linematch = issues.as_array().unwrap()
        .iter()
        .any(|i| i["kind"] == "empty-linematch");
    assert!(has_empty_linematch, "should detect empty-linematch");
}

#[test]
fn version_json_output_valid() {
    let out = aaai().args(["version", "--json-output"]).output().unwrap();
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).unwrap();
    let v: serde_json::Value = serde_json::from_str(&stdout)
        .expect("version --json-output must produce valid JSON");
    assert!(v["version"].is_string(), "version field must be present");
    assert!(v["license"].is_string(), "license field must be present");
}

#[test]
fn version_plain_exits_0() {
    let status = aaai().args(["version"]).status().unwrap();
    assert_eq!(status.code(), Some(0));
}

// ── Phase 11: coverage補完 ───────────────────────────────────────────────────

// ── audit: 追加フラグ ─────────────────────────────────────────────────────────

#[test]
fn audit_exit_4_on_config_error() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    let bad_yaml = tmp.path().join("bad.yaml");
    write_audit(&bad_yaml, "not: valid: yaml: [[[\n");

    let status = aaai()
        .args(["audit",
               "--left",   b.to_str().unwrap(),
               "--right",  a.to_str().unwrap(),
               "--config", bad_yaml.to_str().unwrap(),
               "--no-history"])
        .status().unwrap();
    assert_eq!(status.code(), Some(4), "invalid YAML config must exit 4");
}

#[test]
fn audit_verbose_shows_reason() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&b, "f.txt", "old\n");
    write(&a, "f.txt", "new\n");
    let yaml = tmp.path().join("audit.yaml");
    write_audit(&yaml, r#"version: "1"
entries:
  - path: f.txt
    diff_type: Modified
    reason: "verbose reason text"
    strategy:
      type: None
    enabled: true
"#);
    let out = aaai()
        .args(["audit",
               "--left",   b.to_str().unwrap(),
               "--right",  a.to_str().unwrap(),
               "--config", yaml.to_str().unwrap(),
               "--verbose", "--no-history"])
        .output().unwrap();
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(stdout.contains("verbose reason text"),
        "verbose mode should print the reason");
}

#[test]
fn audit_mask_secrets_redacts_output() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&b, "f.txt", "x\n");
    write(&a, "f.txt", "y\n");
    let yaml = tmp.path().join("audit.yaml");
    write_audit(&yaml, r#"version: "1"
entries:
  - path: f.txt
    diff_type: Modified
    reason: "api_key=sk-abcdefghijklmnop12345678 changed"
    strategy:
      type: None
    enabled: true
"#);
    let out = aaai()
        .args(["audit",
               "--left",   b.to_str().unwrap(),
               "--right",  a.to_str().unwrap(),
               "--config", yaml.to_str().unwrap(),
               "--verbose", "--mask-secrets", "--no-history"])
        .output().unwrap();
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(!stdout.contains("sk-abcdefghijklmnop"),
        "--mask-secrets must redact secret values from output");
    assert!(stdout.contains("MASKED"),
        "--mask-secrets should replace with MASKED marker");
}

#[test]
fn audit_suppress_warnings_flag() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&b, "f.txt", "old\n");
    write(&a, "f.txt", "new\n");
    let yaml = tmp.path().join("audit.yaml");
    write_audit(&yaml, r#"version: "1"
entries:
  - path: f.txt
    diff_type: Modified
    reason: "change"
    strategy:
      type: None
    enabled: true
"#);
    let status = aaai()
        .args(["audit",
               "--left",   b.to_str().unwrap(),
               "--right",  a.to_str().unwrap(),
               "--config", yaml.to_str().unwrap(),
               "--suppress-warnings", "no-approver",
               "--no-history"])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
}

// ── snap: 追加フラグ ─────────────────────────────────────────────────────────

#[test]
fn snap_list_templates_exits_0() {
    let out = aaai()
        .args(["snap",
               "--left", "/tmp", "--right", "/tmp",
               "--out", "/tmp/x.yaml",
               "--list-templates"])
        .output().unwrap();
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(stdout.contains("version_bump") || stdout.contains("port_change"),
        "list-templates should show template IDs");
}

#[test]
fn snap_template_applied() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&b, "app.toml", "version = \"1.0.0\"\n");
    write(&a, "app.toml", "version = \"1.1.0\"\n");
    let out_path = tmp.path().join("audit.yaml");

    let status = aaai()
        .args(["snap",
               "--left",     b.to_str().unwrap(),
               "--right",    a.to_str().unwrap(),
               "--out",      out_path.to_str().unwrap(),
               "--template", "version_bump"])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
    let content = fs::read_to_string(&out_path).unwrap();
    assert!(content.contains("Regex") || content.contains("regex"),
        "version_bump template should set Regex strategy");
}

#[test]
fn snap_approver_flag_sets_approved_by() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&a, "new.txt", "content\n");
    let out_path = tmp.path().join("audit.yaml");

    let status = aaai()
        .args(["snap",
               "--left",     b.to_str().unwrap(),
               "--right",    a.to_str().unwrap(),
               "--out",      out_path.to_str().unwrap(),
               "--approver", "alice"])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
    let content = fs::read_to_string(&out_path).unwrap();
    assert!(content.contains("alice"),
        "--approver should set approved_by in generated entries");
}

#[test]
fn snap_merge_adds_only_new_entries() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&b, "existing.txt", "old\n");
    write(&a, "existing.txt", "new\n");
    write(&a, "added.txt",    "hello\n");

    let out_path = tmp.path().join("audit.yaml");
    // First snap
    aaai().args(["snap",
                 "--left",  b.to_str().unwrap(),
                 "--right", a.to_str().unwrap(),
                 "--out",   out_path.to_str().unwrap()])
          .status().unwrap();
    // Set reason on existing entry so --merge should skip it
    let content = fs::read_to_string(&out_path).unwrap();
    let with_reason = content.replace("reason: ''", "reason: 'already approved'");
    fs::write(&out_path, with_reason).unwrap();

    // Second snap with --merge should not overwrite existing reason
    let status = aaai()
        .args(["snap",
               "--left",  b.to_str().unwrap(),
               "--right", a.to_str().unwrap(),
               "--out",   out_path.to_str().unwrap(),
               "--merge"])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
    let final_content = fs::read_to_string(&out_path).unwrap();
    assert!(final_content.contains("already approved"),
        "--merge should not overwrite entries that already have a reason");
}

// ── report: 追加フォーマット ───────────────────────────────────────────────────

#[test]
fn report_json_format_creates_valid_file() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    let yaml = tmp.path().join("audit.yaml");
    write_audit(&yaml, "version: \"1\"\n");
    let out = tmp.path().join("report.json");

    let status = aaai()
        .args(["report",
               "--left",   b.to_str().unwrap(),
               "--right",  a.to_str().unwrap(),
               "--config", yaml.to_str().unwrap(),
               "--format", "json",
               "--out",    out.to_str().unwrap()])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
    assert!(out.exists());
    let v: serde_json::Value =
        serde_json::from_str(&fs::read_to_string(&out).unwrap()).unwrap();
    assert!(v.get("result").is_some(), "JSON report must have 'result' field");
}

#[test]
fn report_include_diff_embeds_diff_block() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&b, "f.txt", "line1\n");
    write(&a, "f.txt", "line2\n");
    let yaml = tmp.path().join("audit.yaml");
    write_audit(&yaml, r#"version: "1"
entries:
  - path: f.txt
    diff_type: Modified
    reason: "changed"
    strategy:
      type: None
    enabled: true
"#);
    let out = tmp.path().join("report.md");

    let status = aaai()
        .args(["report",
               "--left",         b.to_str().unwrap(),
               "--right",        a.to_str().unwrap(),
               "--config",       yaml.to_str().unwrap(),
               "--include-diff",
               "--out",          out.to_str().unwrap()])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
    let content = fs::read_to_string(&out).unwrap();
    assert!(content.contains("```diff") || content.contains("-line1") || content.contains("+line2"),
        "--include-diff should embed actual diff text");
}

// ── history: 追加フラグ ────────────────────────────────────────────────────────

#[test]
fn history_prune_exits_0() {
    // prune は履歴ファイルが存在しなくても 0 で終了する
    let status = aaai()
        .args(["history", "--prune", "100"])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
}

#[test]
fn history_n_flag_limits_output() {
    let out = aaai()
        .args(["history", "-n", "3"])
        .output().unwrap();
    assert_eq!(out.status.code(), Some(0));
}

#[test]
fn history_json_output_is_array() {
    let out = aaai()
        .args(["history", "--json-output", "-n", "5"])
        .output().unwrap();
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).unwrap();
    let v: serde_json::Value = serde_json::from_str(&stdout)
        .expect("history --json-output must be valid JSON");
    assert!(v.is_array(), "history --json-output must be a JSON array");
}

// ── lint: 追加フラグ ──────────────────────────────────────────────────────────

#[test]
fn lint_detects_duplicate_path() {
    let tmp = tempfile::tempdir().unwrap();
    let yaml = tmp.path().join("dup.yaml");
    write_audit(&yaml, r#"version: "1"
entries:
  - path: f.txt
    diff_type: Modified
    reason: "first"
    strategy:
      type: None
    enabled: true
  - path: f.txt
    diff_type: Modified
    reason: "duplicate"
    strategy:
      type: None
    enabled: true
"#);
    let out = aaai()
        .args(["lint", yaml.to_str().unwrap(), "--json-output"])
        .output().unwrap();
    // duplicate-path is an error → exit 1
    assert_eq!(out.status.code(), Some(1));
    let issues: serde_json::Value =
        serde_json::from_str(&String::from_utf8(out.stdout).unwrap()).unwrap();
    let has_dup = issues.as_array().unwrap()
        .iter().any(|i| i["kind"] == "duplicate-path");
    assert!(has_dup, "lint should detect duplicate-path entries");
}

#[test]
fn lint_require_ticket_warns_missing() {
    let tmp = tempfile::tempdir().unwrap();
    let yaml = tmp.path().join("audit.yaml");
    write_audit(&yaml, r#"version: "1"
entries:
  - path: f.txt
    diff_type: Modified
    reason: "change without ticket"
    strategy:
      type: None
    enabled: true
"#);
    let out = aaai()
        .args(["lint", yaml.to_str().unwrap(),
               "--require-ticket", "--json-output"])
        .output().unwrap();
    let stdout = String::from_utf8(out.stdout).unwrap();
    let issues: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let has_ticket_warn = issues.as_array().unwrap()
        .iter().any(|i| i["kind"] == "missing-ticket");
    assert!(has_ticket_warn, "--require-ticket should warn when ticket is absent");
}

#[test]
fn lint_min_reason_len_warns_short() {
    let tmp = tempfile::tempdir().unwrap();
    let yaml = tmp.path().join("audit.yaml");
    write_audit(&yaml, r#"version: "1"
entries:
  - path: f.txt
    diff_type: Modified
    reason: "ok"
    strategy:
      type: None
    enabled: true
"#);
    let out = aaai()
        .args(["lint", yaml.to_str().unwrap(),
               "--min-reason-len", "20", "--json-output"])
        .output().unwrap();
    let stdout = String::from_utf8(out.stdout).unwrap();
    let issues: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let has_short = issues.as_array().unwrap()
        .iter().any(|i| i["kind"] == "short-reason");
    assert!(has_short, "--min-reason-len should warn when reason is shorter than threshold");
}

// ── merge: 実際のマージ動作 ────────────────────────────────────────────────────

#[test]
fn merge_actually_merges_entries() {
    let tmp = tempfile::tempdir().unwrap();
    let base = tmp.path().join("base.yaml");
    let overlay = tmp.path().join("overlay.yaml");
    let merged = tmp.path().join("merged.yaml");

    write_audit(&base, r#"version: "1"
entries:
  - path: base.txt
    diff_type: Added
    reason: "from base"
    strategy:
      type: None
    enabled: true
"#);
    write_audit(&overlay, r#"version: "1"
entries:
  - path: overlay.txt
    diff_type: Added
    reason: "from overlay"
    strategy:
      type: None
    enabled: true
"#);

    let status = aaai()
        .args(["merge",
               base.to_str().unwrap(),
               overlay.to_str().unwrap(),
               "--out", merged.to_str().unwrap()])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
    assert!(merged.exists(), "merge should create output file");
    let content = fs::read_to_string(&merged).unwrap();
    assert!(content.contains("base.txt"),    "merged file should contain base entries");
    assert!(content.contains("overlay.txt"), "merged file should contain overlay entries");
}

#[test]
fn merge_dry_run_does_not_write() {
    let tmp = tempfile::tempdir().unwrap();
    let base = tmp.path().join("base.yaml");
    let overlay = tmp.path().join("overlay.yaml");
    let out = tmp.path().join("out.yaml");

    write_audit(&base,    "version: \"1\"\n");
    write_audit(&overlay, "version: \"1\"\n");

    let status = aaai()
        .args(["merge",
               base.to_str().unwrap(),
               overlay.to_str().unwrap(),
               "--out", out.to_str().unwrap(),
               "--dry-run"])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
    assert!(!out.exists(), "merge --dry-run must NOT write the output file");
}

// ── diff: 追加フラグ ──────────────────────────────────────────────────────────

#[test]
fn diff_content_flag_shows_diff_text() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&b, "f.txt", "old line\n");
    write(&a, "f.txt", "new line\n");

    let out = aaai()
        .args(["diff",
               "--left",    b.to_str().unwrap(),
               "--right",   a.to_str().unwrap(),
               "--content"])
        .output().unwrap();
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(stdout.contains("+new line") || stdout.contains("-old line"),
        "--content should show inline diff text");
}

#[test]
fn diff_all_flag_includes_unchanged() {
    let tmp = tempfile::tempdir().unwrap();
    let b = tmp.path().join("before");
    let a = tmp.path().join("after");
    setup_dirs(&b, &a);
    write(&b, "same.txt", "same\n");
    write(&a, "same.txt", "same\n");
    write(&a, "added.txt", "new\n");

    let out = aaai()
        .args(["diff",
               "--left",  b.to_str().unwrap(),
               "--right", a.to_str().unwrap(),
               "--all"])
        .output().unwrap();
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(stdout.contains("same.txt"),
        "--all should include Unchanged files in output");
}

// ── config: discover ==========================================================

#[test]
fn config_show_when_no_config_found() {
    // Run from a temp dir with no .aaai.yaml
    let tmp = tempfile::tempdir().unwrap();
    let out = aaai()
        .args(["config"])
        .current_dir(tmp.path())
        .output().unwrap();
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(stdout.contains("No") || stdout.contains("not found"),
        "config with no .aaai.yaml should report not found");
}

// ── watch: smoke test =========================================================

#[test]
fn watch_help_exits_0() {
    let status = aaai()
        .args(["watch", "--help"])
        .status().unwrap();
    assert_eq!(status.code(), Some(0));
}

// ── completions: fish/powershell ──────────────────────────────────────────────

#[test]
fn completions_fish_exits_0() {
    let out = aaai().args(["completions", "fish"]).output().unwrap();
    assert_eq!(out.status.code(), Some(0));
    assert!(!String::from_utf8(out.stdout).unwrap().is_empty(),
        "fish completion output should not be empty");
}

#[test]
fn completions_powershell_exits_0() {
    let out = aaai().args(["completions", "powershell"]).output().unwrap();
    assert_eq!(out.status.code(), Some(0));
}