tldr-cli 0.1.5

CLI binary for TLDR code analysis tool
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
//! CLI Patterns and Contracts Commands Tests
//!
//! Tests for tldr-cli pattern analysis and contract inference commands:
//! - Patterns: purity, resources, mutability, temporal, coupling, cohesion, interface, behavioral
//! - Contracts: contracts, bounds, invariants, specs, verify, dead-stores, chop
//! - Diagnostics: diagnostics (type checking and linting)
//!
//! See `bugs_cli_patterns_contracts.md` for documented bugs.

use std::fs;
// Path import not needed - using PathBuf via tempfile::TempDir
use std::process::Command;
use tempfile::TempDir;

// =============================================================================
// Test Fixtures
// =============================================================================

/// Create a test project with various Python patterns for testing
fn create_test_project() -> TempDir {
    let temp_dir = TempDir::new().unwrap();
    let project_path = temp_dir.path();

    // Create main.py with various functions for pattern analysis
    fs::write(
        project_path.join("main.py"),
        r#"# Main module with various function patterns

def pure_add(x, y):
    """A pure function - no side effects"""
    return x + y

def impure_function():
    """Function with side effects"""
    with open("file.txt", "w") as f:
        f.write("hello")
    global_state = 1
    return global_state

def mutating_function(items):
    """Function that mutates its input"""
    items.append(42)
    items.sort()
    return items

def guarded_function(x):
    """Function with guard clauses"""
    if x < 0:
        raise ValueError("x must be non-negative")
    if not isinstance(x, int):
        raise TypeError("x must be int")
    return x * 2

class Calculator:
    """A calculator class for cohesion testing"""
    def __init__(self):
        self.value = 0
    
    def add(self, x):
        self.value += x
        return self
    
    def subtract(self, x):
        self.value -= x
        return self
    
    def get_value(self):
        return self.value

def resource_function():
    """Function with resource management"""
    f = open("test.txt", "r")
    data = f.read()
    f.close()
    return data

def leaky_function():
    """Function with potential resource leak"""
    f = open("test.txt", "r")
    data = f.read()
    # Missing f.close() - potential leak
    return data
"#,
    )
    .unwrap();

    // Create utils.py for coupling tests
    fs::write(
        project_path.join("utils.py"),
        r#"# Utility module
from main import pure_add, Calculator

def utility_func(x):
    """Uses functions from main"""
    return pure_add(x, 10)

def create_calc():
    """Creates a calculator"""
    return Calculator()
"#,
    )
    .unwrap();

    // Create tests directory for specs/invariants
    fs::create_dir(project_path.join("tests")).unwrap();
    fs::write(
        project_path.join("tests").join("test_main.py"),
        r#"# Test file for specs extraction
import pytest
from main import pure_add, guarded_function, Calculator

def test_pure_add():
    assert pure_add(2, 3) == 5
    assert pure_add(-1, 1) == 0

def test_pure_add_with_zero():
    assert pure_add(0, 0) == 0

def test_guarded_function_valid():
    assert guarded_function(5) == 10

def test_guarded_function_raises():
    with pytest.raises(ValueError):
        guarded_function(-1)

class TestCalculator:
    def test_calculator_add(self):
        calc = Calculator()
        calc.add(5)
        assert calc.get_value() == 5
    
    def test_calculator_subtract(self):
        calc = Calculator()
        calc.subtract(3)
        assert calc.get_value() == -3
"#,
    )
    .unwrap();

    temp_dir
}

/// Create a minimal test project for edge cases
fn create_minimal_project() -> TempDir {
    let temp_dir = TempDir::new().unwrap();
    let project_path = temp_dir.path();

    fs::write(
        project_path.join("minimal.py"),
        r#"def simple():
    pass
"#,
    )
    .unwrap();

    temp_dir
}

/// Create a project with type hints for bounds analysis
fn create_typed_project() -> TempDir {
    let temp_dir = TempDir::new().unwrap();
    let project_path = temp_dir.path();

    fs::write(
        project_path.join("typed.py"),
        r#"def calculate(x: int, y: int) -> int:
    if x > 0:
        z = x + y
    else:
        z = 0
    return z * 2

def divide(a: int, b: int) -> float:
    return a / b

def bounded(n: int) -> int:
    if n < 0:
        n = 0
    elif n > 100:
        n = 100
    return n
"#,
    )
    .unwrap();

    temp_dir
}

/// Create a project with data flow patterns for chop analysis
fn create_chop_project() -> TempDir {
    let temp_dir = TempDir::new().unwrap();
    let project_path = temp_dir.path();

    fs::write(
        project_path.join("chop_test.py"),
        r#"def data_flow(x):
    y = x + 1      # line 2
    z = y * 2      # line 3
    w = z + 10     # line 4
    return w       # line 5
"#,
    )
    .unwrap();

    temp_dir
}

/// Create a project with dead stores for SSA analysis
fn create_dead_store_project() -> TempDir {
    let temp_dir = TempDir::new().unwrap();
    let project_path = temp_dir.path();

    fs::write(
        project_path.join("dead_store.py"),
        r#"def dead_store_example():
    x = 1          # line 2 - dead store
    x = 2          # line 3 - overwrites without use
    return x       # line 4

def live_store_example():
    x = 1          # line 7 - used
    y = x + 1      # line 8
    return y       # line 9
"#,
    )
    .unwrap();

    temp_dir
}

// =============================================================================
// Resources Command Tests
// =============================================================================

#[test]
fn test_resources_basic_json() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "resources",
            temp_dir.path().join("main.py").to_str().unwrap(),
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr resources");

    // Exit code may be non-zero when leaks are found (exit 3 = leaks detected)
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(!stdout.is_empty(), "Output should not be empty");
}

#[test]
fn test_resources_with_check_flags() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "resources",
            temp_dir.path().join("main.py").to_str().unwrap(),
            "--check-all",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr resources with check-all");

    // Exit code may be non-zero when leaks are found
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(!stdout.is_empty(), "Output should not be empty");
}

#[test]
fn test_resources_text_format() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "resources",
            temp_dir.path().join("main.py").to_str().unwrap(),
            "-o",
            "text",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr resources text");

    // Exit code may be non-zero when leaks are found
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(!stdout.is_empty(), "Output should not be empty");
}

// =============================================================================
// Temporal Command Tests
// =============================================================================

#[test]
fn test_temporal_basic_json() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args(["temporal", temp_dir.path().to_str().unwrap(), "-q"])
        .output()
        .expect("Failed to execute tldr temporal");

    assert!(output.status.success(), "temporal command should succeed");
    let stdout = String::from_utf8_lossy(&output.stdout);
    // May or may not find temporal patterns
    assert!(
        !stdout.is_empty() || stdout.is_empty(),
        "Command should run"
    );
}

#[test]
fn test_temporal_with_options() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "temporal",
            temp_dir.path().to_str().unwrap(),
            "--min-support",
            "1",
            "--min-confidence",
            "0.5",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr temporal with options");

    assert!(
        output.status.success(),
        "temporal with options should succeed"
    );
}

// =============================================================================
// Coupling Command Tests
// =============================================================================

#[test]
fn test_coupling_basic_json() {
    let temp_dir = create_test_project();
    let main_path = temp_dir.path().join("main.py");
    let utils_path = temp_dir.path().join("utils.py");

    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "coupling",
            main_path.to_str().unwrap(),
            utils_path.to_str().unwrap(),
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr coupling");

    assert!(output.status.success(), "coupling command should succeed");
}

#[test]
fn test_coupling_same_file() {
    let temp_dir = create_test_project();
    let main_path = temp_dir.path().join("main.py");

    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "coupling",
            main_path.to_str().unwrap(),
            main_path.to_str().unwrap(),
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr coupling same file");

    // Should either succeed or give a meaningful error
    let _ = output.status;
}

// =============================================================================
// Cohesion Command Tests
// =============================================================================

#[test]
fn test_cohesion_basic_json() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args(["cohesion", temp_dir.path().to_str().unwrap(), "-q"])
        .output()
        .expect("Failed to execute tldr cohesion");

    assert!(output.status.success(), "cohesion command should succeed");
    let stdout = String::from_utf8_lossy(&output.stdout);
    // Should find the Calculator class
    assert!(
        stdout.contains("Calculator") || stdout.contains("class"),
        "Output should contain class information"
    );
}

#[test]
fn test_cohesion_with_min_methods() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "cohesion",
            temp_dir.path().to_str().unwrap(),
            "--min-methods",
            "2",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr cohesion with min-methods");

    assert!(
        output.status.success(),
        "cohesion with min-methods should succeed"
    );
}

#[test]
fn test_cohesion_text_format() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "cohesion",
            temp_dir.path().to_str().unwrap(),
            "-o",
            "text",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr cohesion text");

    assert!(
        output.status.success(),
        "cohesion text format should succeed"
    );
}

// =============================================================================
// Interface Command Tests
// =============================================================================

#[test]
fn test_interface_basic() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "interface",
            temp_dir.path().join("main.py").to_str().unwrap(),
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr interface");

    assert!(output.status.success(), "interface command should succeed");
    let stdout = String::from_utf8_lossy(&output.stdout);
    // Interface analysis should extract public API
    assert!(
        stdout.contains("pure_add") || stdout.contains("function"),
        "Output should contain function information"
    );
}

// =============================================================================
// Behavioral Command Tests
// =============================================================================

#[test]
fn test_behavioral_basic_json() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "behavioral",
            temp_dir.path().join("main.py").to_str().unwrap(),
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr behavioral");

    assert!(output.status.success(), "behavioral command should succeed");
    let stdout = String::from_utf8_lossy(&output.stdout);
    // Should extract behavioral constraints
    assert!(!stdout.is_empty(), "Output should not be empty");
}

#[test]
fn test_behavioral_with_function() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "behavioral",
            temp_dir.path().join("main.py").to_str().unwrap(),
            "guarded_function",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr behavioral with function");

    assert!(
        output.status.success(),
        "behavioral with function should succeed"
    );
}

// =============================================================================
// Contracts Command Tests
// =============================================================================

#[test]
fn test_contracts_basic_json() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "contracts",
            temp_dir.path().join("main.py").to_str().unwrap(),
            "guarded_function",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr contracts");

    assert!(output.status.success(), "contracts command should succeed");
    let stdout = String::from_utf8_lossy(&output.stdout);
    // Should extract preconditions from guard clauses
    assert!(
        stdout.contains("preconditions") || stdout.contains("condition"),
        "Output should contain preconditions"
    );
}

#[test]
fn test_contracts_text_format() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "contracts",
            temp_dir.path().join("main.py").to_str().unwrap(),
            "guarded_function",
            "-o",
            "text",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr contracts text");

    assert!(
        output.status.success(),
        "contracts text format should succeed"
    );
}

// =============================================================================
// Bounds Command Tests
// =============================================================================

#[test]
fn test_bounds_basic_json() {
    let temp_dir = create_typed_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "bounds",
            temp_dir.path().join("typed.py").to_str().unwrap(),
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr bounds");

    assert!(output.status.success(), "bounds command should succeed");
    let stdout = String::from_utf8_lossy(&output.stdout);
    // Bounds analysis should produce interval results
    assert!(!stdout.is_empty(), "Output should not be empty");
}

#[test]
fn test_bounds_with_function() {
    let temp_dir = create_typed_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "bounds",
            temp_dir.path().join("typed.py").to_str().unwrap(),
            "calculate",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr bounds with function");

    assert!(
        output.status.success(),
        "bounds with function should succeed"
    );
}

// =============================================================================
// Invariants Command Tests
// =============================================================================

#[test]
fn test_invariants_basic() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "invariants",
            temp_dir.path().join("main.py").to_str().unwrap(),
            "--from-tests",
            temp_dir.path().join("tests").to_str().unwrap(),
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr invariants");

    assert!(output.status.success(), "invariants command should succeed");
}

#[test]
fn test_invariants_with_min_obs() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "invariants",
            temp_dir.path().join("main.py").to_str().unwrap(),
            "--from-tests",
            temp_dir.path().join("tests").to_str().unwrap(),
            "--min-obs",
            "1",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr invariants with min-obs");

    assert!(
        output.status.success(),
        "invariants with min-obs should succeed"
    );
}

// =============================================================================
// Specs Command Tests
// =============================================================================

#[test]
fn test_specs_basic() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "specs",
            "--from-tests",
            temp_dir.path().join("tests").to_str().unwrap(),
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr specs");

    assert!(output.status.success(), "specs command should succeed");
    let stdout = String::from_utf8_lossy(&output.stdout);
    // Should extract specs from test assertions
    assert!(
        stdout.contains("pure_add") || stdout.contains("function"),
        "Output should contain function specs"
    );
}

#[test]
fn test_specs_with_function_filter() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "specs",
            "--from-tests",
            temp_dir.path().join("tests").to_str().unwrap(),
            "--function",
            "pure_add",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr specs with function filter");

    assert!(
        output.status.success(),
        "specs with function filter should succeed"
    );
}

// =============================================================================
// Verify Command Tests
// =============================================================================

#[test]
fn test_verify_basic() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args(["verify", temp_dir.path().to_str().unwrap(), "-q"])
        .output()
        .expect("Failed to execute tldr verify");

    assert!(output.status.success(), "verify command should succeed");
    let stdout = String::from_utf8_lossy(&output.stdout);
    // Verify produces a dashboard report
    assert!(
        stdout.contains("contracts") || stdout.contains("specs") || stdout.contains("verify"),
        "Output should contain verification results"
    );
}

#[test]
fn test_verify_quick_mode() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args(["verify", temp_dir.path().to_str().unwrap(), "--quick", "-q"])
        .output()
        .expect("Failed to execute tldr verify --quick");

    assert!(output.status.success(), "verify --quick should succeed");
}

// =============================================================================
// Dead-Stores Command Tests
// =============================================================================

#[test]
fn test_dead_stores_basic() {
    let temp_dir = create_dead_store_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "dead-stores",
            temp_dir.path().join("dead_store.py").to_str().unwrap(),
            "dead_store_example",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr dead-stores");

    assert!(
        output.status.success(),
        "dead-stores command should succeed"
    );
}

#[test]
fn test_dead_stores_with_compare() {
    let temp_dir = create_dead_store_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "dead-stores",
            temp_dir.path().join("dead_store.py").to_str().unwrap(),
            "dead_store_example",
            "--compare",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr dead-stores --compare");

    assert!(
        output.status.success(),
        "dead-stores --compare should succeed"
    );
}

// =============================================================================
// Chop Command Tests
// =============================================================================

#[test]
fn test_chop_basic() {
    let temp_dir = create_chop_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "chop",
            temp_dir.path().join("chop_test.py").to_str().unwrap(),
            "data_flow",
            "2",
            "5",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr chop");

    assert!(output.status.success(), "chop command should succeed");
    let stdout = String::from_utf8_lossy(&output.stdout);
    // Chop should find lines on dependency path
    assert!(!stdout.is_empty(), "Output should not be empty");
}

#[test]
fn test_chop_same_line() {
    let temp_dir = create_chop_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "chop",
            temp_dir.path().join("chop_test.py").to_str().unwrap(),
            "data_flow",
            "2",
            "2",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr chop same line");

    assert!(output.status.success(), "chop same line should succeed");
}

// =============================================================================
// Diagnostics Command Tests
// =============================================================================

#[test]
fn test_diagnostics_basic() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args(["diagnostics", temp_dir.path().to_str().unwrap(), "-q"])
        .output()
        .expect("Failed to execute tldr diagnostics");

    // Exit codes: 0=clean, 1=diagnostics found, 60=no tools, 61=tools failed
    let exit_code = output.status.code().unwrap_or(-1);
    assert!(
        exit_code == 0 || exit_code == 1 || exit_code == 60 || exit_code == 61,
        "diagnostics should exit with known code, got {}",
        exit_code
    );
}

#[test]
fn test_diagnostics_with_severity() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "diagnostics",
            temp_dir.path().to_str().unwrap(),
            "--severity",
            "error",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr diagnostics with severity");

    let exit_code = output.status.code().unwrap_or(-1);
    assert!(
        exit_code == 0 || exit_code == 1 || exit_code == 60 || exit_code == 61,
        "diagnostics with severity should exit with known code, got {}",
        exit_code
    );
}

#[test]
fn test_diagnostics_no_typecheck() {
    let temp_dir = create_test_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "diagnostics",
            temp_dir.path().to_str().unwrap(),
            "--no-typecheck",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr diagnostics --no-typecheck");

    let exit_code = output.status.code().unwrap_or(-1);
    assert!(
        exit_code == 0 || exit_code == 60 || exit_code == 61,
        "diagnostics --no-typecheck should exit with known code"
    );
}

// =============================================================================
// Error Handling Tests
// =============================================================================

#[test]
fn test_patterns_nonexistent_file() {
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args(["purity", "/nonexistent/path/file.py", "-q"])
        .output()
        .expect("Failed to execute tldr purity on nonexistent file");

    assert!(!output.status.success(), "Should fail for nonexistent file");
}

#[test]
fn test_contracts_nonexistent_function() {
    let temp_dir = create_minimal_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "contracts",
            temp_dir.path().join("minimal.py").to_str().unwrap(),
            "nonexistent_function",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr contracts on nonexistent function");

    // May succeed with empty result or fail with error
    let _ = output.status;
}

#[test]
fn test_chop_invalid_line_numbers() {
    let temp_dir = create_chop_project();
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "chop",
            temp_dir.path().join("chop_test.py").to_str().unwrap(),
            "data_flow",
            "0",
            "999",
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr chop with invalid lines");

    // May succeed or fail depending on implementation
    let _ = output.status;
}

// =============================================================================
// Help Tests
// =============================================================================

#[test]
fn test_patterns_help() {
    let commands = [
        "resources",
        "temporal",
        "coupling",
        "cohesion",
        "interface",
        "behavioral",
    ];

    for cmd in &commands {
        let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
            .args([cmd, "--help"])
            .output()
            .unwrap_or_else(|_| panic!("Failed to execute tldr {} --help", cmd));

        assert!(output.status.success(), "{} --help should succeed", cmd);
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            stdout.contains("Usage:"),
            "Help should contain Usage section"
        );
        assert!(
            stdout.contains("Options:"),
            "Help should contain Options section"
        );
    }
}

#[test]
fn test_contracts_help() {
    let commands = [
        "contracts",
        "bounds",
        "invariants",
        "specs",
        "verify",
        "dead-stores",
        "chop",
    ];

    for cmd in &commands {
        let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
            .args([cmd, "--help"])
            .output()
            .unwrap_or_else(|_| panic!("Failed to execute tldr {} --help", cmd));

        assert!(output.status.success(), "{} --help should succeed", cmd);
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            stdout.contains("Usage:"),
            "Help should contain Usage section"
        );
    }
}

#[test]
fn test_diagnostics_help() {
    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args(["diagnostics", "--help"])
        .output()
        .expect("Failed to execute tldr diagnostics --help");

    assert!(output.status.success(), "diagnostics --help should succeed");
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("Usage:"),
        "Help should contain Usage section"
    );
    assert!(
        stdout.contains("--strict"),
        "Help should mention --strict flag"
    );
    assert!(
        stdout.contains("--severity"),
        "Help should mention --severity flag"
    );
}

// =============================================================================
// Multi-Language Tests
// =============================================================================

#[test]
fn test_patterns_rust_file() {
    let temp_dir = TempDir::new().unwrap();
    let project_path = temp_dir.path();

    fs::write(
        project_path.join("test.rs"),
        r#"fn add(a: i32, b: i32) -> i32 {
    a + b
}

fn main() {
    println!("{}", add(1, 2));
}
"#,
    )
    .unwrap();

    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "purity",
            project_path.join("test.rs").to_str().unwrap(),
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr purity on Rust file");

    // May succeed or fail depending on Rust support
    let _ = output.status;
}

#[test]
fn test_patterns_go_file() {
    let temp_dir = TempDir::new().unwrap();
    let project_path = temp_dir.path();

    fs::write(
        project_path.join("test.go"),
        r#"package main

func Add(a, b int) int {
    return a + b
}
"#,
    )
    .unwrap();

    let output = Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
        .args([
            "purity",
            project_path.join("test.go").to_str().unwrap(),
            "-q",
        ])
        .output()
        .expect("Failed to execute tldr purity on Go file");

    // May succeed or fail depending on Go support
    let _ = output.status;
}