fallow-cli 2.78.0

CLI for fallow, Rust-native codebase intelligence for TypeScript and JavaScript
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
#[path = "common/mod.rs"]
mod common;

use common::{
    fallow_bin, parse_json, run_fallow, run_fallow_combined, run_fallow_in_root, run_fallow_raw,
};

// ---------------------------------------------------------------------------
// --fail-on-issues across commands
// ---------------------------------------------------------------------------

#[test]
fn fail_on_issues_check_exits_1_with_issues() {
    let output = run_fallow(
        "check",
        "basic-project",
        &["--fail-on-issues", "--format", "json", "--quiet"],
    );
    assert_eq!(
        output.code, 1,
        "check --fail-on-issues should exit 1 with issues"
    );
}

#[test]
fn fail_on_issues_dupes_exits_1_with_clones() {
    let output = run_fallow(
        "dupes",
        "duplicate-code",
        &[
            "--threshold",
            "0.1",
            "--fail-on-issues",
            "--format",
            "json",
            "--quiet",
        ],
    );
    assert!(
        output.code == 0 || output.code == 1,
        "dupes with --fail-on-issues should not crash, got {}",
        output.code
    );
}

#[test]
fn combined_mode_runs_successfully() {
    let output = run_fallow_combined("basic-project", &["--format", "json", "--quiet"]);
    assert!(
        output.code == 0 || output.code == 1,
        "combined mode should not crash, got exit code {}",
        output.code
    );
    let json: serde_json::Value = serde_json::from_str(&output.stdout)
        .unwrap_or_else(|e| panic!("combined output should be JSON: {e}"));
    assert!(json.is_object(), "combined output should be a JSON object");
}

#[test]
fn combined_json_explain_includes_sectioned_meta() {
    let output = run_fallow_combined(
        "basic-project",
        &["--format", "json", "--quiet", "--explain"],
    );
    assert!(
        output.code == 0 || output.code == 1,
        "combined mode should not crash, got exit code {}",
        output.code
    );
    let json = parse_json(&output);
    assert!(
        json.pointer("/_meta/check/rules/unused-export/description")
            .and_then(serde_json::Value::as_str)
            .is_some_and(|text| text.contains("Named exports")),
        "combined _meta should include dead-code rule descriptions"
    );
    assert!(
        json.pointer("/_meta/dupes/metrics/duplication_percentage/description")
            .and_then(serde_json::Value::as_str)
            .is_some(),
        "combined _meta should include duplication metric descriptions"
    );
    assert!(
        json.pointer("/_meta/health/metrics/cyclomatic/description")
            .and_then(serde_json::Value::as_str)
            .is_some(),
        "combined _meta should include health metric descriptions"
    );
}

#[test]
fn human_explain_adds_inline_descriptions_for_analysis_commands() {
    let check = run_fallow("check", "basic-project", &["--quiet", "--explain"]);
    assert!(
        check
            .stdout
            .contains("Description: Named exports that are never imported"),
        "check --explain should describe dead-code sections, stdout:\n{}",
        check.stdout
    );

    let dupes = run_fallow("dupes", "duplicate-code", &["--quiet", "--explain"]);
    assert!(
        dupes.stdout.contains("Description: A block of code"),
        "dupes --explain should describe duplicate sections, stdout:\n{}",
        dupes.stdout
    );

    let health = run_fallow("health", "complexity-project", &["--quiet", "--explain"]);
    assert!(
        health
            .stdout
            .contains("Description: Function exceeds both cyclomatic and cognitive"),
        "health --explain should describe health sections, stdout:\n{}",
        health.stdout
    );
}

#[test]
fn combined_human_explain_renders_inline_descriptions() {
    let combined = run_fallow_combined("basic-project", &["--quiet", "--explain"]);
    assert!(
        combined.code == 0 || combined.code == 1,
        "combined --explain should not crash, got exit code {}",
        combined.code
    );
    assert!(
        combined
            .stdout
            .contains("Description: Named exports that are never imported"),
        "combined --explain should render dead-code descriptions inline, stdout:\n{}",
        combined.stdout
    );
}

#[test]
fn check_grouped_human_explain_renders_inline_descriptions() {
    let output = run_fallow(
        "check",
        "basic-project",
        &["--quiet", "--explain", "--group-by", "directory"],
    );
    assert!(
        output
            .stdout
            .contains("Description: Named exports that are never imported"),
        "check --group-by --explain should render dead-code descriptions inline, stdout:\n{}",
        output.stdout
    );
}

#[test]
fn combined_mode_config_enabled_coverage_gaps_stays_out_of_health_section() {
    let dir = tempfile::tempdir().expect("create temp dir");
    let config_path = dir.path().join("fallow.json");
    std::fs::write(
        &config_path,
        r#"{
  "rules": {
    "coverage-gaps": "warn"
  }
}
"#,
    )
    .expect("write config file");

    let output = run_fallow_raw(&[
        "--root",
        common::fixture_path("production-mode")
            .to_str()
            .expect("fixture path should be utf-8"),
        "--config",
        config_path.to_str().expect("config path should be utf-8"),
        "--format",
        "json",
        "--quiet",
    ]);
    assert!(
        output.code == 0 || output.code == 1,
        "combined mode should not crash with config-enabled coverage gaps"
    );

    let json = parse_json(&output);
    assert!(
        json["health"].get("coverage_gaps").is_none(),
        "combined mode should not leak coverage_gaps into the embedded health report"
    );
}

#[test]
fn combined_mode_hidden_coverage_gap_gate_does_not_fail() {
    let dir = tempfile::tempdir().expect("create temp dir");
    let config_path = dir.path().join("fallow.json");
    std::fs::write(
        &config_path,
        r#"{
  "rules": {
    "coverage-gaps": "error",
    "unused-files": "off",
    "unused-dependencies": "off",
    "unused-exports": "off",
    "test-only-dependencies": "off"
  }
}
"#,
    )
    .expect("write config file");

    let output = run_fallow_raw(&[
        "--root",
        common::fixture_path("coverage-gaps")
            .to_str()
            .expect("fixture path should be utf-8"),
        "--config",
        config_path.to_str().expect("config path should be utf-8"),
        "--format",
        "json",
        "--quiet",
    ]);
    assert_eq!(
        output.code, 0,
        "combined mode should not fail on hidden coverage-gap gates"
    );

    let json = parse_json(&output);
    assert!(
        json["health"].get("coverage_gaps").is_none(),
        "combined mode should keep hidden coverage gaps out of the embedded health report"
    );
}

#[test]
fn combined_human_output_labels_metrics_line() {
    let output = run_fallow_combined("basic-project", &[]);
    assert!(
        output.code == 0 || output.code == 1,
        "combined human output should not crash, got exit code {}",
        output.code
    );
    let metrics_line = output
        .stderr
        .lines()
        .find(|line| line.contains("dead files"))
        .expect("combined human output should include the orientation metrics line");
    assert!(
        metrics_line.trim_start().starts_with("â–  Metrics:"),
        "combined human output should label the orientation metrics line. line: {metrics_line}\nstderr: {}",
        output.stderr,
    );
}

// ---------------------------------------------------------------------------
// --only / --skip in combined mode
// ---------------------------------------------------------------------------

#[test]
fn combined_only_dead_code() {
    let output = run_fallow_combined(
        "basic-project",
        &["--only", "dead-code", "--format", "json", "--quiet"],
    );
    assert!(
        output.code == 0 || output.code == 1,
        "combined --only dead-code should not crash"
    );
}

#[test]
fn combined_skip_dead_code() {
    let output = run_fallow_combined(
        "basic-project",
        &["--skip", "dead-code", "--format", "json", "--quiet"],
    );
    assert!(
        output.code == 0 || output.code == 1,
        "combined --skip dead-code should not crash"
    );
}

#[test]
fn combined_only_and_skip_are_mutually_exclusive() {
    let output = run_fallow_combined(
        "basic-project",
        &[
            "--only",
            "dead-code",
            "--skip",
            "health",
            "--format",
            "json",
            "--quiet",
        ],
    );
    assert_eq!(
        output.code, 2,
        "--only and --skip together should exit 2 (invalid args)"
    );
}

// ---------------------------------------------------------------------------
// Baseline round-trip
// ---------------------------------------------------------------------------

#[test]
fn save_baseline_creates_file() {
    let dir = std::env::temp_dir().join(format!("fallow-baseline-test-{}", std::process::id()));
    // Pre-clean to avoid false positives from previous runs
    let _ = std::fs::remove_dir_all(&dir);
    let _ = std::fs::create_dir_all(&dir);
    let baseline_path = dir.join("fallow-baselines/dead-code.json");

    let output = run_fallow(
        "check",
        "basic-project",
        &[
            "--save-baseline",
            baseline_path.to_str().unwrap(),
            "--format",
            "json",
            "--quiet",
        ],
    );
    assert!(
        output.code == 0 || output.code == 1,
        "save-baseline should not crash"
    );
    assert!(
        baseline_path.exists(),
        "--save-baseline should create the baseline file"
    );

    let content = std::fs::read_to_string(&baseline_path).unwrap();
    let _: serde_json::Value =
        serde_json::from_str(&content).expect("baseline file should be valid JSON");

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn baseline_filters_known_issues() {
    let dir = std::env::temp_dir().join(format!(
        "fallow-baseline-filter-test-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    let _ = std::fs::create_dir_all(&dir);
    let baseline_path = dir.join("baseline.json");

    run_fallow(
        "check",
        "basic-project",
        &[
            "--save-baseline",
            baseline_path.to_str().unwrap(),
            "--format",
            "json",
            "--quiet",
        ],
    );

    let output = run_fallow(
        "check",
        "basic-project",
        &[
            "--baseline",
            baseline_path.to_str().unwrap(),
            "--format",
            "json",
            "--quiet",
        ],
    );
    let json = parse_json(&output);
    let total = json["total_issues"].as_u64().unwrap_or(0);
    assert_eq!(
        total, 0,
        "baseline should filter all known issues, got {total}"
    );

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn save_baseline_distinguishes_same_unused_dep_across_workspaces() {
    let dir = tempfile::tempdir().expect("create temp dir");
    std::fs::write(
        dir.path().join("package.json"),
        r#"{
  "name": "baseline-workspace-deps",
  "private": true,
  "workspaces": ["packages/*"]
}
"#,
    )
    .expect("write root package.json");
    std::fs::write(
        dir.path().join("tsconfig.json"),
        r#"{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ES2022",
    "moduleResolution": "bundler",
    "strict": true
  }
}
"#,
    )
    .expect("write tsconfig");

    for package in ["app-a", "app-b"] {
        let package_dir = dir.path().join("packages").join(package);
        let src_dir = package_dir.join("src");
        std::fs::create_dir_all(&src_dir).expect("create package src");
        std::fs::write(
            package_dir.join("package.json"),
            format!(
                r#"{{
  "name": "{package}",
  "version": "1.0.0",
  "main": "src/index.ts",
  "dependencies": {{ "lodash-es": "4.17.21" }}
}}
"#
            ),
        )
        .expect("write workspace package.json");
        std::fs::write(
            src_dir.join("index.ts"),
            format!("export const {package}_value = 1;\n").replace('-', "_"),
        )
        .expect("write source file");
    }

    let baseline_path = dir.path().join("baseline.json");
    let output = run_fallow_in_root(
        "dead-code",
        dir.path(),
        &[
            "--save-baseline",
            baseline_path
                .to_str()
                .expect("baseline path should be utf-8"),
            "--format",
            "json",
            "--quiet",
        ],
    );
    assert!(
        output.code == 0 || output.code == 1,
        "save-baseline should not crash, got {}: {}",
        output.code,
        output.stderr
    );

    let baseline: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&baseline_path).expect("read baseline"))
            .expect("baseline should be valid JSON");
    let deps: Vec<&str> = baseline["unused_dependencies"]
        .as_array()
        .expect("unused_dependencies should be an array")
        .iter()
        .map(|value| value.as_str().expect("dependency key should be a string"))
        .collect();

    assert_eq!(
        deps,
        vec![
            "packages/app-a/package.json:lodash-es",
            "packages/app-b/package.json:lodash-es"
        ]
    );
}

// ---------------------------------------------------------------------------
// --changed-since
// ---------------------------------------------------------------------------

#[test]
fn changed_since_accepts_head() {
    let output = run_fallow(
        "check",
        "basic-project",
        &["--changed-since", "HEAD", "--format", "json", "--quiet"],
    );
    assert!(
        output.code == 0 || output.code == 1,
        "check --changed-since HEAD should not crash, got exit {}. stderr: {}",
        output.code,
        output.stderr
    );
    let json = parse_json(&output);
    assert!(
        json.get("total_issues").is_some(),
        "should still have total_issues key even with --changed-since"
    );
}

// ---------------------------------------------------------------------------
// Error paths
// ---------------------------------------------------------------------------

#[test]
fn nonexistent_root_exits_2() {
    let output = run_fallow_raw(&[
        "check",
        "--root",
        "/nonexistent/path/for/testing",
        "--quiet",
    ]);
    assert_eq!(output.code, 2, "nonexistent root should exit 2");
}

#[test]
fn config_with_traversal_glob_exits_2() {
    // Issue #463: config-sourced glob patterns with `..` segments are
    // rejected at load time with exit 2 instead of silently no-op'ing.
    let dir = tempfile::tempdir().expect("create temp dir");
    let root = dir.path();
    std::fs::write(root.join("package.json"), r#"{"name":"test"}"#).expect("write package.json");
    std::fs::write(
        root.join(".fallowrc.json"),
        r#"{ "entry": ["../escape/**"] }"#,
    )
    .expect("write config");

    let output = run_fallow_in_root("check", root, &["--quiet"]);
    assert_eq!(
        output.code, 2,
        "traversal glob in config should exit 2, stderr: {}",
        output.stderr
    );
    assert!(
        output.stderr.contains("entry") && output.stderr.contains("../escape/**"),
        "stderr should mention the offending field + pattern, got: {}",
        output.stderr
    );
}

#[test]
fn config_with_invalid_glob_exits_2() {
    // Issue #463: invalid glob syntax now fails loud at load time instead
    // of being silently dropped.
    let dir = tempfile::tempdir().expect("create temp dir");
    let root = dir.path();
    std::fs::write(root.join("package.json"), r#"{"name":"test"}"#).expect("write package.json");
    std::fs::write(
        root.join(".fallowrc.json"),
        r#"{ "ignorePatterns": ["[unclosed"] }"#,
    )
    .expect("write config");

    let output = run_fallow_in_root("check", root, &["--quiet"]);
    assert_eq!(
        output.code, 2,
        "invalid glob syntax in config should exit 2, stderr: {}",
        output.stderr
    );
    assert!(
        output.stderr.contains("ignorePatterns") && output.stderr.contains("[unclosed"),
        "stderr should mention the offending field + pattern, got: {}",
        output.stderr
    );
}

#[test]
fn external_plugin_file_traversal_glob_exits_2() {
    // Issue #463 second BLOCK: external plugin files loaded from
    // `.fallow/plugins/` (NOT inline `framework[]` in the main config)
    // also reach `glob::glob` on disk via their `fileExists.pattern`.
    // The validation must run on those too, not just on the inline path.
    // Mirrors codex's reproducer: `.fallow/plugins/leak.json` with a
    // traversal-bearing detection pattern.
    let dir = tempfile::tempdir().expect("create temp dir");
    let root = dir.path();
    std::fs::write(root.join("package.json"), r#"{"name":"test"}"#).expect("write package.json");
    std::fs::create_dir_all(root.join(".fallow").join("plugins")).expect("mk .fallow/plugins/");
    std::fs::write(
        root.join(".fallow").join("plugins").join("leak.json"),
        r#"{
            "name": "leaky-plugin",
            "detection": { "type": "fileExists", "pattern": "../secret-marker" }
        }"#,
    )
    .expect("write plugin");

    let output = run_fallow_in_root("check", root, &["--quiet"]);
    assert_eq!(
        output.code, 2,
        "external plugin with traversal glob should exit 2, stderr: {}",
        output.stderr
    );
    assert!(
        output.stderr.contains("framework[].detection")
            && output.stderr.contains("../secret-marker"),
        "stderr should mention the offending field + pattern, got: {}",
        output.stderr
    );
}

#[test]
fn fallow_plugin_root_file_traversal_glob_exits_2() {
    // Issue #463: `fallow-plugin-*` files at the project root are also
    // auto-discovered (third discovery source after `plugins:` and
    // `.fallow/plugins/`). Same validation must apply.
    let dir = tempfile::tempdir().expect("create temp dir");
    let root = dir.path();
    std::fs::write(root.join("package.json"), r#"{"name":"test"}"#).expect("write package.json");
    std::fs::write(
        root.join("fallow-plugin-leak.json"),
        r#"{
            "name": "leaky-root-plugin",
            "entryPoints": ["../entry/**"]
        }"#,
    )
    .expect("write plugin");

    let output = run_fallow_in_root("check", root, &["--quiet"]);
    assert_eq!(
        output.code, 2,
        "fallow-plugin-* root file with traversal glob should exit 2, stderr: {}",
        output.stderr
    );
    assert!(
        output.stderr.contains("framework[].entryPoints") && output.stderr.contains("../entry/**"),
        "stderr should mention the offending field + pattern, got: {}",
        output.stderr
    );
}

#[test]
fn no_package_json_returns_empty_results() {
    let output = run_fallow(
        "check",
        "error-no-package-json",
        &["--format", "json", "--quiet"],
    );
    assert_eq!(
        output.code, 0,
        "missing package.json should exit 0 with no issues, stderr: {}",
        output.stderr
    );
    let json = parse_json(&output);
    assert_eq!(
        json["total_issues"].as_u64().unwrap_or(0),
        0,
        "should have 0 issues without package.json"
    );
}

// ---------------------------------------------------------------------------
// Combined-mode JSON contract: stdout is exactly one JSON document even when
// the project is outside a Git repository (regression for #294).
// ---------------------------------------------------------------------------

#[test]
fn combined_json_outside_git_repo_emits_single_document() {
    use std::process::Command;

    // Build a minimal TS project in a tempdir whose parent chain has no `.git`,
    // so the hotspot pipeline's `is_git_repo` check returns false. We isolate
    // from any inherited `GIT_DIR` / `GIT_WORK_TREE` set by parent test hooks
    // and from any global git config that could redirect rev-parse upward.
    let dir = tempfile::tempdir().expect("create temp dir");
    let root = dir.path();
    std::fs::write(
        root.join("package.json"),
        r#"{"name":"no-git-combined","type":"module","main":"src/index.ts"}"#,
    )
    .expect("write package.json");
    std::fs::write(
        root.join("tsconfig.json"),
        r#"{"compilerOptions":{"target":"ES2020","module":"ES2020","strict":true},"include":["src"]}"#,
    )
    .expect("write tsconfig.json");
    std::fs::create_dir_all(root.join("src")).expect("create src");
    std::fs::write(
        root.join("src/index.ts"),
        "export function add(a: number, b: number): number { return a + b; }\n",
    )
    .expect("write index.ts");

    let mut cmd = Command::new(fallow_bin());
    cmd.arg("--root")
        .arg(root)
        .arg("--format")
        .arg("json")
        .arg("--quiet")
        .env("RUST_LOG", "")
        .env("NO_COLOR", "1")
        .env_remove("GIT_DIR")
        .env_remove("GIT_WORK_TREE")
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_SYSTEM", "/dev/null");
    let output = cmd.output().expect("failed to run fallow binary");
    let stdout = String::from_utf8_lossy(&output.stdout);

    // The bug in #294 was that stdout contained an inline `{"error": true,
    // "message": "hotspot analysis requires a git repository", ...}` followed
    // by the combined report (two top-level JSON values). Parsing as a single
    // value catches that exactly: serde_json rejects trailing input.
    serde_json::from_str::<serde_json::Value>(&stdout).unwrap_or_else(|e| {
        panic!(
            "combined mode outside a git repo must emit exactly one JSON document on stdout: {e}\nstdout was:\n{stdout}\nstderr was:\n{}",
            String::from_utf8_lossy(&output.stderr)
        )
    });

    // And the parsed envelope should be the combined report; schema_version is
    // the canonical marker.
    let json: serde_json::Value = serde_json::from_str(&stdout).expect("already parsed");
    assert!(
        json.get("schema_version").is_some(),
        "stdout should be the combined report envelope, got: {json}"
    );
    assert!(
        json.get("error").is_none(),
        "combined report must not surface a top-level `error` key from a nested hotspot bail-out"
    );
}

// ---------------------------------------------------------------------------
// Issue #468: boundary configuration silent-fail patterns now exit 2 at load.
// ---------------------------------------------------------------------------

#[test]
fn config_with_unknown_boundary_zone_reference_exits_2() {
    // A rule whose `from`/`allow`/`allowTypeOnly` names a zone that does NOT
    // exist in `zones[]` used to log a `tracing::error!` and continue,
    // producing a flood of false-positive boundary violations at analysis
    // time. Now exits 2 at config load with every offending entry enumerated.
    let dir = tempfile::tempdir().expect("create temp dir");
    let root = dir.path();
    std::fs::write(root.join("package.json"), r#"{"name":"test"}"#).expect("write package.json");
    std::fs::write(
        root.join(".fallowrc.json"),
        r#"{
            "boundaries": {
                "zones": [{ "name": "ui", "patterns": ["src/ui/**"] }],
                "rules": [
                    {
                        "from": "typo-from",
                        "allow": ["typo-allow"],
                        "allowTypeOnly": ["typo-type-only"]
                    },
                    {
                        "from": "ui",
                        "allow": ["another-typo"]
                    }
                ]
            }
        }"#,
    )
    .expect("write config");

    let output = run_fallow_in_root("check", root, &["--quiet"]);
    assert_eq!(
        output.code, 2,
        "unknown boundary zone reference should exit 2, stderr: {}",
        output.stderr
    );

    // Every offending tuple should appear in one rendered diagnostic. Users
    // fix all four in one edit instead of one-by-one.
    let stderr = &output.stderr;
    assert!(
        stderr.contains("invalid boundary configuration"),
        "stderr: {stderr}"
    );
    for name in ["typo-from", "typo-allow", "typo-type-only", "another-typo"] {
        assert!(
            stderr.contains(name),
            "stderr should name every offending zone (`{name}`): {stderr}"
        );
    }
}

#[test]
fn config_with_redundant_boundary_root_prefix_exits_2() {
    // `boundaries.zones[].root` + a pattern that redundantly repeats the
    // root double-prefixes the path at classify time and never matches. This
    // used to log a `tracing::error!` and continue with a phantom-empty
    // zone; now exits 2 at config load with the legacy
    // FALLOW-BOUNDARY-ROOT-REDUNDANT-PREFIX tag preserved for CI grep recipes.
    let dir = tempfile::tempdir().expect("create temp dir");
    let root = dir.path();
    std::fs::write(root.join("package.json"), r#"{"name":"test"}"#).expect("write package.json");
    std::fs::write(
        root.join(".fallowrc.json"),
        r#"{
            "boundaries": {
                "zones": [{
                    "name": "ui",
                    "patterns": ["packages/app/src/**"],
                    "root": "packages/app/"
                }],
                "rules": []
            }
        }"#,
    )
    .expect("write config");

    let output = run_fallow_in_root("check", root, &["--quiet"]);
    assert_eq!(
        output.code, 2,
        "redundant root prefix should exit 2, stderr: {}",
        output.stderr
    );
    let stderr = &output.stderr;
    assert!(
        stderr.contains("FALLOW-BOUNDARY-ROOT-REDUNDANT-PREFIX"),
        "stderr should preserve the legacy tag for CI grep recipes: {stderr}"
    );
    assert!(stderr.contains("packages/app/src/**"), "stderr: {stderr}");
}

#[test]
fn fallow_config_subcommand_rejects_unknown_boundary_zone() {
    // `fallow config` lives on a different code path than `check` (calls
    // `FallowConfig::load` / `find_and_load` directly, no `runtime_support`).
    // Without explicit wiring it would print the parsed config and exit 0
    // even when `check` exits 2, giving users a false "loaded fine" signal.
    // Surfaced by review of #468.
    let dir = tempfile::tempdir().expect("create temp dir");
    let root = dir.path();
    std::fs::write(root.join("package.json"), r#"{"name":"test"}"#).expect("write package.json");
    std::fs::write(
        root.join(".fallowrc.json"),
        r#"{
            "boundaries": {
                "zones": [{ "name": "ui", "patterns": ["src/ui/**"] }],
                "rules": [{ "from": "ui", "allow": ["typo-zone"] }]
            }
        }"#,
    )
    .expect("write config");

    let output = run_fallow_raw(&["--root", root.to_str().expect("utf-8 root"), "config"]);
    assert_eq!(
        output.code, 2,
        "fallow config must reject invalid boundary config, stderr: {}",
        output.stderr
    );
    assert!(
        output.stderr.contains("typo-zone"),
        "stderr should name the typo'd zone, got: {}",
        output.stderr
    );
}

#[test]
fn fallow_config_subcommand_json_format_emits_structured_error_envelope() {
    // `--format json` config-load failures must land as the structured
    // `{"error": true, "message": ..., "exit_code": 2}` envelope on stdout,
    // not human text. Locks the JSON error contract for the config subcommand.
    let dir = tempfile::tempdir().expect("create temp dir");
    let root = dir.path();
    std::fs::write(root.join("package.json"), r#"{"name":"test"}"#).expect("write package.json");
    std::fs::write(
        root.join(".fallowrc.json"),
        r#"{
            "boundaries": {
                "zones": [{ "name": "ui", "patterns": ["src/ui/**"] }],
                "rules": [{ "from": "ui", "allow": ["typo-zone"] }]
            }
        }"#,
    )
    .expect("write config");

    let output = run_fallow_raw(&[
        "--root",
        root.to_str().expect("utf-8 root"),
        "--format",
        "json",
        "config",
    ]);
    assert_eq!(output.code, 2, "should exit 2, stderr: {}", output.stderr);
    let parsed: serde_json::Value = serde_json::from_str(&output.stdout).unwrap_or_else(|e| {
        panic!(
            "stdout should be JSON envelope: {e}\nstdout: {}",
            output.stdout
        )
    });
    assert_eq!(parsed["error"], serde_json::Value::Bool(true));
    assert_eq!(parsed["exit_code"], serde_json::Value::from(2));
    let msg = parsed["message"]
        .as_str()
        .expect("message should be a string");
    assert!(msg.contains("invalid boundary configuration"), "msg: {msg}");
    assert!(msg.contains("typo-zone"), "msg: {msg}");
}

#[test]
fn fallow_list_boundaries_json_format_emits_structured_error_envelope() {
    // `fallow list --boundaries --format json` previously hardcoded
    // `OutputFormat::Human` when calling `load_config`, so config-load
    // failures (boundary validation, glob validation, plugin validation)
    // surfaced as human-text errors on stderr instead of the structured JSON
    // envelope JSON consumers expect. Surfaced by review of #468.
    let dir = tempfile::tempdir().expect("create temp dir");
    let root = dir.path();
    std::fs::write(root.join("package.json"), r#"{"name":"test"}"#).expect("write package.json");
    std::fs::write(
        root.join(".fallowrc.json"),
        r#"{
            "boundaries": {
                "zones": [{ "name": "ui", "patterns": ["src/ui/**"] }],
                "rules": [{ "from": "ui", "allow": ["typo-zone"] }]
            }
        }"#,
    )
    .expect("write config");

    let output = run_fallow_raw(&[
        "--root",
        root.to_str().expect("utf-8 root"),
        "--format",
        "json",
        "list",
        "--boundaries",
    ]);
    assert_eq!(output.code, 2, "should exit 2, stderr: {}", output.stderr);
    let parsed: serde_json::Value = serde_json::from_str(&output.stdout).unwrap_or_else(|e| {
        panic!(
            "stdout should be JSON envelope: {e}\nstdout: {}",
            output.stdout
        )
    });
    assert_eq!(parsed["error"], serde_json::Value::Bool(true));
    assert_eq!(parsed["exit_code"], serde_json::Value::from(2));
    let msg = parsed["message"]
        .as_str()
        .expect("message should be a string");
    assert!(msg.contains("invalid boundary configuration"), "msg: {msg}");
    assert!(msg.contains("typo-zone"), "msg: {msg}");
}

#[test]
fn config_with_valid_boundaries_loads_cleanly() {
    // Control: a boundary config whose every zone reference resolves and
    // whose patterns do not redundantly prefix their root continues to load
    // (no analysis sources here, so check exits 0 with zero findings).
    let dir = tempfile::tempdir().expect("create temp dir");
    let root = dir.path();
    std::fs::write(root.join("package.json"), r#"{"name":"test"}"#).expect("write package.json");
    std::fs::write(
        root.join(".fallowrc.json"),
        r#"{
            "boundaries": {
                "zones": [
                    { "name": "ui", "patterns": ["src/ui/**"] },
                    { "name": "db", "patterns": ["src/db/**"] }
                ],
                "rules": [
                    { "from": "ui", "allow": ["db"] }
                ]
            }
        }"#,
    )
    .expect("write config");

    let output = run_fallow_in_root("check", root, &["--quiet"]);
    assert_eq!(
        output.code, 0,
        "valid boundary config should load (exit 0 with no sources), stderr: {}",
        output.stderr
    );
}

// ---------------------------------------------------------------------------
// Regression-baseline schema_version validation (#451)
// ---------------------------------------------------------------------------

#[test]
fn regression_baseline_schema_mismatch_json_format_emits_structured_error_envelope() {
    // `fallow check --regression-baseline <path> --fail-on-regression --format json --quiet`
    // against a baseline whose schema_version does not match this build must:
    //   1. exit 2 (load failure, distinct from exit 1 "regression detected")
    //   2. emit the structured `{"error": true, "message": ..., "exit_code": 2}`
    //      envelope on stdout, not a human-text error on stderr.
    //   3. include the regenerate hint in the message so a CI consumer's log
    //      surfaces a copy-pasteable next step.
    // Locks the OutputFormat-threading path through RegressionOpts into
    // load_regression_baseline.
    let dir = tempfile::tempdir().expect("create temp dir");
    let root = dir.path();
    std::fs::write(root.join("package.json"), r#"{"name":"test"}"#).expect("write package.json");

    let baseline_path = root.join("stale-baseline.json");
    std::fs::write(
        &baseline_path,
        r#"{
  "schema_version": 99,
  "fallow_version": "9.9.9",
  "timestamp": "2030-01-01T00:00:00Z",
  "check": {"total_issues": 0, "unused_files": 0}
}"#,
    )
    .expect("write baseline");

    let output = run_fallow_in_root(
        "check",
        root,
        &[
            "--regression-baseline",
            baseline_path.to_str().expect("utf-8 baseline path"),
            "--fail-on-regression",
            "--format",
            "json",
            "--quiet",
        ],
    );
    assert_eq!(
        output.code, 2,
        "schema mismatch should exit 2, stderr: {}",
        output.stderr
    );

    let parsed: serde_json::Value = serde_json::from_str(&output.stdout).unwrap_or_else(|e| {
        panic!(
            "stdout should be JSON envelope: {e}\nstdout: {}",
            output.stdout
        )
    });
    assert_eq!(parsed["error"], serde_json::Value::Bool(true));
    assert_eq!(parsed["exit_code"], serde_json::Value::from(2));
    let msg = parsed["message"]
        .as_str()
        .expect("message should be a string");
    assert!(msg.contains("schema_version 99"), "msg: {msg}");
    assert!(msg.contains("expects 1"), "msg: {msg}");
    assert!(msg.contains("fallow 9.9.9"), "msg: {msg}");
    assert!(
        msg.contains("fallow check --save-regression-baseline"),
        "msg should include regenerate command, msg: {msg}"
    );
}