tldr-cli 0.1.2

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
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
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
# Pattern Analysis Commands - Rust Port Specification

**Created:** 2026-02-04
**Author:** architect-agent
**Source:** Python v1 at `/Users/cosimo/.opc-dev/opc/packages/tldr-code/tldr/cli/commands/`
**Target:** `/Users/cosimo/.opc-dev/opc/packages/tldr-code/tldr-rs/crates/tldr-cli/src/commands/patterns/`

## Overview

This specification defines the Rust port of 8 TLDR commands for pattern analysis, including behavioral constraint extraction, cohesion metrics, coupling analysis, mutability tracking, purity analysis, temporal constraint mining, interface extraction, and resource lifecycle analysis.

These commands help users understand code quality, design patterns, and potential issues in their Python codebase. All commands follow established patterns from the contracts module.

## Module Architecture

```
patterns/
├── mod.rs              # Module exports and re-exports
├── types.rs            # Shared data types across all commands
├── error.rs            # PatternsError enum and Result type
├── validation.rs       # Path safety, resource limits (TIGER mitigations)
├── behavioral.rs       # behavioral command - pre/postcondition extraction
├── cohesion.rs         # cohesion command - LCOM4 class cohesion
├── coupling.rs         # coupling command - pairwise module coupling
├── mutability.rs       # mutability command - variable/parameter mutation
├── purity.rs           # purity command - effect/purity analysis
├── temporal.rs         # temporal command - temporal constraint mining
├── interface.rs        # interface command - public API extraction
└── resources.rs        # resources command - resource lifecycle analysis
```

## Shared Types (`types.rs`)

### Confidence Level

```rust
use serde::{Deserialize, Serialize};

/// Confidence level for inferred patterns and analysis results.
///
/// # Serialization
///
/// Serializes to snake_case: `"high"`, `"medium"`, `"low"`
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Confidence {
    /// High confidence - direct code evidence
    High,
    /// Medium confidence - inferred from patterns
    Medium,
    /// Low confidence - heuristic or partial evidence
    Low,
}

impl Default for Confidence {
    fn default() -> Self {
        Self::Medium
    }
}

impl std::fmt::Display for Confidence {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::High => write!(f, "high"),
            Self::Medium => write!(f, "medium"),
            Self::Low => write!(f, "low"),
        }
    }
}
```

### Docstring Style

```rust
/// Documentation style detected in source code.
///
/// Used by behavioral analysis to parse docstrings correctly.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DocstringStyle {
    /// Google-style docstrings (Args:, Returns:, Raises:)
    Google,
    /// NumPy-style docstrings (Parameters, Returns sections)
    Numpy,
    /// Sphinx/reST style docstrings (:param:, :returns:, :raises:)
    Sphinx,
    /// Plain docstrings without structured sections
    Plain,
}

impl Default for DocstringStyle {
    fn default() -> Self {
        Self::Plain
    }
}

impl std::fmt::Display for DocstringStyle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Google => write!(f, "google"),
            Self::Numpy => write!(f, "numpy"),
            Self::Sphinx => write!(f, "sphinx"),
            Self::Plain => write!(f, "plain"),
        }
    }
}
```

### Effect Type

```rust
/// Type of side effect detected in code.
///
/// Used by purity and behavioral analysis.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EffectType {
    /// I/O operations (file, network, console)
    Io,
    /// Writing to global variables
    GlobalWrite,
    /// Writing to object attributes (self.x = ...)
    AttributeWrite,
    /// Modifying collections in place (list.append, dict.update)
    CollectionModify,
    /// Calling functions with potential side effects
    Call,
}

impl std::fmt::Display for EffectType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io => write!(f, "io"),
            Self::GlobalWrite => write!(f, "global_write"),
            Self::AttributeWrite => write!(f, "attribute_write"),
            Self::CollectionModify => write!(f, "collection_modify"),
            Self::Call => write!(f, "call"),
        }
    }
}
```

### Condition Source

```rust
/// Source of a pre/postcondition constraint.
///
/// Tracks where a constraint was extracted from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConditionSource {
    /// Guard clause (if x < 0: raise ValueError)
    Guard,
    /// Docstring description
    Docstring,
    /// Type hint annotation
    TypeHint,
    /// Assert statement
    Assertion,
    /// icontract decorator (@require, @ensure)
    Icontract,
    /// deal library decorator
    Deal,
}

impl std::fmt::Display for ConditionSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Guard => write!(f, "guard"),
            Self::Docstring => write!(f, "docstring"),
            Self::TypeHint => write!(f, "type_hint"),
            Self::Assertion => write!(f, "assertion"),
            Self::Icontract => write!(f, "icontract"),
            Self::Deal => write!(f, "deal"),
        }
    }
}
```

### Cohesion Types

```rust
/// Information about a connected component in LCOM4 analysis.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ComponentInfo {
    /// Methods in this component
    pub methods: Vec<String>,
    /// Fields accessed by this component
    pub fields: Vec<String>,
}

/// Cohesion analysis result for a single class.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ClassCohesion {
    /// Class name
    pub class_name: String,
    /// File path where class is defined
    pub file_path: String,
    /// Line number of class definition
    pub line: u32,
    /// LCOM4 value (1 = cohesive, >1 = split candidate)
    pub lcom4: u32,
    /// Number of methods analyzed
    pub method_count: u32,
    /// Number of fields detected
    pub field_count: u32,
    /// Verdict based on LCOM4 value
    pub verdict: CohesionVerdict,
    /// Suggestion for splitting if LCOM4 > 1
    pub split_suggestion: Option<String>,
    /// Connected components (if LCOM4 > 1)
    pub components: Vec<ComponentInfo>,
}

/// Verdict for cohesion analysis.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CohesionVerdict {
    /// Class is cohesive (LCOM4 = 1)
    Cohesive,
    /// Class could be split (LCOM4 > 1)
    SplitCandidate,
}

/// Summary of cohesion analysis across multiple classes.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CohesionSummary {
    /// Total classes analyzed
    pub total_classes: u32,
    /// Number of cohesive classes
    pub cohesive: u32,
    /// Number of split candidates
    pub split_candidates: u32,
    /// Average LCOM4 value
    pub avg_lcom4: f64,
}

/// Full report from cohesion analysis.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CohesionReport {
    /// Cohesion results per class
    pub classes: Vec<ClassCohesion>,
    /// Summary statistics
    pub summary: CohesionSummary,
}
```

### Coupling Types

```rust
/// A single cross-module function call.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CrossCall {
    /// Function making the call
    pub caller: String,
    /// Function being called
    pub callee: String,
    /// Line number of the call
    pub line: u32,
}

/// Calls from one module to another.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CrossCalls {
    /// Individual call sites
    pub calls: Vec<CrossCall>,
    /// Total count of calls
    pub count: u32,
}

/// Coupling verdict based on score.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CouplingVerdict {
    /// Low coupling (0.0-0.2)
    Low,
    /// Moderate coupling (0.2-0.4)
    Moderate,
    /// High coupling (0.4-0.6)
    High,
    /// Very high coupling (0.6-1.0)
    VeryHigh,
}

impl CouplingVerdict {
    /// Determine verdict from coupling score.
    pub fn from_score(score: f64) -> Self {
        if score < 0.2 {
            Self::Low
        } else if score < 0.4 {
            Self::Moderate
        } else if score < 0.6 {
            Self::High
        } else {
            Self::VeryHigh
        }
    }
}

/// Coupling analysis between two modules.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CouplingReport {
    /// Path to first module
    pub path_a: String,
    /// Path to second module
    pub path_b: String,
    /// Calls from A to B
    pub a_to_b: CrossCalls,
    /// Calls from B to A
    pub b_to_a: CrossCalls,
    /// Total cross-module calls
    pub total_calls: u32,
    /// Coupling score (0.0-1.0)
    pub coupling_score: f64,
    /// Verdict based on score
    pub verdict: CouplingVerdict,
}
```

### Purity Types

```rust
/// Purity analysis result for a single function.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FunctionPurity {
    /// Function name
    pub name: String,
    /// Whether the function is pure (no side effects)
    pub pure: bool,
    /// List of detected effects (empty if pure)
    pub effects: Vec<String>,
    /// Confidence level of the analysis
    pub confidence: Confidence,
}

/// Purity report for a single file.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FilePurityReport {
    /// Source file path
    pub source_file: String,
    /// Purity results per function
    pub functions: Vec<FunctionPurity>,
    /// Count of pure functions
    pub pure_count: u32,
}

/// Full purity report (may include multiple files for directory analysis).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PurityReport {
    /// Per-file reports
    pub files: Vec<FilePurityReport>,
    /// Total functions analyzed
    pub total_functions: u32,
    /// Total pure functions
    pub total_pure: u32,
}
```

### Temporal Types

```rust
/// Example location for a temporal constraint.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TemporalExample {
    /// File where the pattern was observed
    pub file: String,
    /// Line number
    pub line: u32,
}

/// A temporal constraint (before -> after sequence).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TemporalConstraint {
    /// Method that must come first
    pub before: String,
    /// Method that must come after
    pub after: String,
    /// Number of times this pattern was observed
    pub support: u32,
    /// Confidence (support / total sequences containing 'before')
    pub confidence: f64,
    /// Example locations where this pattern appears
    pub examples: Vec<TemporalExample>,
}

/// A trigram (3-method sequence).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Trigram {
    /// The 3-method sequence
    pub sequence: [String; 3],
    /// Number of observations
    pub support: u32,
    /// Confidence score
    pub confidence: f64,
}

/// Metadata about temporal mining.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TemporalMetadata {
    /// Number of files analyzed
    pub files_analyzed: u32,
    /// Total sequences extracted
    pub sequences_extracted: u32,
    /// Minimum support threshold used
    pub min_support: u32,
    /// Minimum confidence threshold used
    pub min_confidence: f64,
}

/// Full temporal constraint report.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TemporalReport {
    /// Discovered temporal constraints
    pub constraints: Vec<TemporalConstraint>,
    /// Discovered trigrams (if requested)
    pub trigrams: Vec<Trigram>,
    /// Analysis metadata
    pub metadata: TemporalMetadata,
}
```

### Interface Types

```rust
/// Information about a public function.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FunctionInfo {
    /// Function name
    pub name: String,
    /// Full signature (e.g., "def foo(x: int, y: str) -> bool")
    pub signature: String,
    /// Docstring if present
    pub docstring: Option<String>,
    /// Line number of definition
    pub lineno: u32,
    /// Whether the function is async
    pub is_async: bool,
}

/// Information about a public method within a class.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MethodInfo {
    /// Method name
    pub name: String,
    /// Full signature
    pub signature: String,
    /// Whether the method is async
    pub is_async: bool,
}

/// Information about a public class.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClassInfo {
    /// Class name
    pub name: String,
    /// Line number of definition
    pub lineno: u32,
    /// Base classes
    pub bases: Vec<String>,
    /// Public methods
    pub methods: Vec<MethodInfo>,
    /// Count of private methods (for completeness)
    pub private_method_count: u32,
}

/// Interface (public API) for a single file.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InterfaceInfo {
    /// File path
    pub file: String,
    /// Contents of __all__ if defined
    pub all_exports: Option<Vec<String>>,
    /// Public functions
    pub functions: Vec<FunctionInfo>,
    /// Public classes
    pub classes: Vec<ClassInfo>,
}
```

### Resource Types

```rust
/// Information about a detected resource.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourceInfo {
    /// Variable name holding the resource
    pub name: String,
    /// Type of resource (e.g., "file", "socket", "connection")
    pub resource_type: String,
    /// Line where resource was created/opened
    pub line: u32,
    /// Whether the resource is properly closed
    pub closed: bool,
}

/// Information about a potential resource leak.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LeakInfo {
    /// Resource that may be leaked
    pub resource: String,
    /// Line where resource was created
    pub line: u32,
    /// Paths to the leak (if --show-paths enabled)
    pub paths: Option<Vec<String>>,
}

/// Information about a double-close issue.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DoubleCloseInfo {
    /// Resource being closed twice
    pub resource: String,
    /// Line of first close
    pub first_close: u32,
    /// Line of second close
    pub second_close: u32,
}

/// Information about use-after-close issue.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UseAfterCloseInfo {
    /// Resource being used after close
    pub resource: String,
    /// Line where resource was closed
    pub close_line: u32,
    /// Line where resource is used after close
    pub use_line: u32,
}

/// Suggestion for using context manager.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContextSuggestion {
    /// Resource that should use context manager
    pub resource: String,
    /// Suggested code pattern
    pub suggestion: String,
}

/// LLM-ready constraint from resource analysis.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ResourceConstraint {
    /// The constraint rule
    pub rule: String,
    /// Context where it applies
    pub context: String,
    /// Confidence level
    pub confidence: f64,
}

/// Summary of resource analysis.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourceSummary {
    /// Total resources detected
    pub resources_detected: u32,
    /// Number of leaks found
    pub leaks_found: u32,
    /// Number of double-close issues
    pub double_closes_found: u32,
    /// Number of use-after-close issues
    pub use_after_closes_found: u32,
}

/// Full resource analysis report.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ResourceReport {
    /// File analyzed
    pub file: String,
    /// Language
    pub language: String,
    /// Function analyzed (if specific function requested)
    pub function: Option<String>,
    /// Detected resources
    pub resources: Vec<ResourceInfo>,
    /// Potential leaks
    pub leaks: Vec<LeakInfo>,
    /// Double-close issues
    pub double_closes: Vec<DoubleCloseInfo>,
    /// Use-after-close issues
    pub use_after_closes: Vec<UseAfterCloseInfo>,
    /// Context manager suggestions
    pub suggestions: Vec<ContextSuggestion>,
    /// LLM constraints (if --constraints enabled)
    pub constraints: Vec<ResourceConstraint>,
    /// Summary statistics
    pub summary: ResourceSummary,
    /// Analysis time in milliseconds
    pub analysis_time_ms: u64,
}
```

### Behavioral Types

```rust
/// A precondition on a function parameter.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Precondition {
    /// Parameter name
    pub param: String,
    /// Constraint expression (e.g., "x > 0")
    pub expression: Option<String>,
    /// Human-readable description from docstring
    pub description: Option<String>,
    /// Type hint if present
    pub type_hint: Option<String>,
    /// Source of this condition
    pub source: ConditionSource,
}

/// A postcondition on function return.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Postcondition {
    /// Constraint expression
    pub expression: Option<String>,
    /// Human-readable description
    pub description: Option<String>,
    /// Return type hint
    pub type_hint: Option<String>,
}

/// Information about an exception the function may raise.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExceptionInfo {
    /// Exception type (e.g., "ValueError")
    pub exception_type: String,
    /// Description of when it's raised
    pub description: Option<String>,
}

/// Information about yield values (for generators).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct YieldInfo {
    /// Type hint for yielded values
    pub type_hint: Option<String>,
    /// Description of yielded values
    pub description: Option<String>,
}

/// Side effect detected in function.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SideEffect {
    /// Type of effect
    pub effect_type: EffectType,
    /// Target of the effect (e.g., "self.count", "global_var")
    pub target: Option<String>,
}

/// Behavioral analysis for a single function.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FunctionBehavior {
    /// Function name
    pub function_name: String,
    /// File path
    pub file_path: String,
    /// Line number of function definition
    pub line: u32,
    /// Whether the function is pure
    pub is_pure: bool,
    /// Whether it's a generator
    pub is_generator: bool,
    /// Whether it's an async function
    pub is_async: bool,
    /// Preconditions on parameters
    pub preconditions: Vec<Precondition>,
    /// Postconditions on return
    pub postconditions: Vec<Postcondition>,
    /// Exceptions that may be raised
    pub exceptions: Vec<ExceptionInfo>,
    /// Yield information (if generator)
    pub yields: Vec<YieldInfo>,
    /// Detected side effects
    pub side_effects: Vec<SideEffect>,
}

/// Class invariant.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClassInvariant {
    /// Invariant expression
    pub expression: String,
}

/// Behavioral analysis for a class.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ClassBehavior {
    /// Class name
    pub class_name: String,
    /// Class invariants
    pub invariants: Vec<ClassInvariant>,
    /// Method behaviors
    pub methods: Vec<FunctionBehavior>,
}

/// Full behavioral analysis report.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BehavioralReport {
    /// File analyzed
    pub file_path: String,
    /// Detected docstring style
    pub docstring_style: DocstringStyle,
    /// Whether icontract library is used
    pub has_icontract: bool,
    /// Whether deal library is used
    pub has_deal: bool,
    /// Function behaviors
    pub functions: Vec<FunctionBehavior>,
    /// Class behaviors
    pub classes: Vec<ClassBehavior>,
}
```

### Mutability Types

```rust
/// Mutability information for a variable.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VariableMutability {
    /// Variable name
    pub name: String,
    /// Whether the variable is ever reassigned
    pub mutable: bool,
    /// Number of reassignments
    pub reassignments: u32,
    /// Number of in-place mutations
    pub mutations: u32,
}

/// Mutability information for a function parameter.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ParameterMutability {
    /// Parameter name
    pub name: String,
    /// Whether the parameter is mutated
    pub mutated: bool,
    /// Lines where mutation occurs
    pub mutation_sites: Vec<u32>,
}

/// Collection mutation detected.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CollectionMutation {
    /// Variable being mutated
    pub variable: String,
    /// Operation (e.g., "append", "update", "pop")
    pub operation: String,
    /// Line number
    pub line: u32,
}

/// Mutability analysis for a function.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FunctionMutability {
    /// Function name
    pub name: String,
    /// Variable mutability info
    pub variables: Vec<VariableMutability>,
    /// Parameter mutability info
    pub parameters: Vec<ParameterMutability>,
    /// Collection mutations
    pub collection_mutations: Vec<CollectionMutation>,
}

/// Field mutability for a class.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FieldMutability {
    /// Field name
    pub name: String,
    /// Whether the field is mutable after __init__
    pub mutable: bool,
    /// Whether the field is only set in __init__
    pub init_only: bool,
}

/// Mutability analysis for a class.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ClassMutability {
    /// Class name
    pub name: String,
    /// Field mutability info
    pub fields: Vec<FieldMutability>,
}

/// Summary of mutability analysis.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MutabilitySummary {
    /// Functions analyzed
    pub functions_analyzed: u32,
    /// Classes analyzed
    pub classes_analyzed: u32,
    /// Total variables
    pub total_variables: u32,
    /// Mutable variables
    pub mutable_variables: u32,
    /// Immutable variables
    pub immutable_variables: u32,
    /// Percentage of immutable variables
    pub immutable_pct: f64,
    /// Parameters analyzed
    pub parameters_analyzed: u32,
    /// Mutated parameters
    pub mutated_parameters: u32,
    /// Percentage of unmutated parameters
    pub unmutated_pct: f64,
    /// Fields analyzed
    pub fields_analyzed: u32,
    /// Mutable fields
    pub mutable_fields: u32,
    /// Constraints generated (if --constraints)
    pub constraints_generated: u32,
}

/// Full mutability report.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MutabilityReport {
    /// File analyzed
    pub file: String,
    /// Language
    pub language: String,
    /// Function mutability results
    pub functions: Vec<FunctionMutability>,
    /// Class mutability results
    pub classes: Vec<ClassMutability>,
    /// Summary statistics
    pub summary: MutabilitySummary,
    /// Analysis time in milliseconds
    pub analysis_time_ms: u64,
}
```

---

## Error Types (`error.rs`)

```rust
use std::path::PathBuf;
use thiserror::Error;

/// Errors specific to pattern analysis commands.
#[derive(Debug, Error)]
pub enum PatternsError {
    /// Source file not found.
    #[error("file not found: {}", path.display())]
    FileNotFound { path: PathBuf },

    /// Function not found in source file.
    #[error("function '{function}' not found in {}", file.display())]
    FunctionNotFound { function: String, file: PathBuf },

    /// Class not found in source file.
    #[error("class '{class_name}' not found in {}", file.display())]
    ClassNotFound { class_name: String, file: PathBuf },

    /// Parse error in source file.
    #[error("parse error in {}: {message}", file.display())]
    ParseError { file: PathBuf, message: String },

    /// File too large to analyze.
    #[error("file too large: {} ({bytes} bytes, max {max_bytes} bytes)", path.display())]
    FileTooLarge { path: PathBuf, bytes: u64, max_bytes: u64 },

    /// Directory scan limit exceeded.
    #[error("directory scan limit exceeded: {count} files found, max {max_files}")]
    TooManyFiles { count: u32, max_files: u32 },

    /// Analysis depth limit exceeded.
    #[error("analysis depth limit exceeded: depth {depth}, max {max_depth}")]
    DepthLimitExceeded { depth: u32, max_depth: u32 },

    /// Analysis timed out.
    #[error("analysis timed out after {timeout_secs}s")]
    Timeout { timeout_secs: u64 },

    /// Invalid parameter value.
    #[error("invalid parameter: {message}")]
    InvalidParameter { message: String },

    /// Path traversal attempt detected.
    #[error("path traversal blocked: {} attempts to escape project root", path.display())]
    PathTraversal { path: PathBuf },

    /// Unsupported language.
    #[error("unsupported language: {language} (only Python is supported)")]
    UnsupportedLanguage { language: String },

    /// No constraints found (not an error, but special exit code).
    #[error("no constraints found matching criteria")]
    NoConstraintsFound,

    /// Issues found (for resources command).
    #[error("resource issues found: {leaks} leaks, {double_closes} double-closes, {use_after_closes} use-after-close")]
    IssuesFound {
        leaks: u32,
        double_closes: u32,
        use_after_closes: u32,
    },

    /// Generic IO error.
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    /// JSON serialization error.
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),
}

/// Result type for pattern analysis commands.
pub type PatternsResult<T> = Result<T, PatternsError>;

impl PatternsError {
    /// Create a FileNotFound error.
    pub fn file_not_found(path: impl Into<PathBuf>) -> Self {
        Self::FileNotFound { path: path.into() }
    }

    /// Create a FunctionNotFound error.
    pub fn function_not_found(function: impl Into<String>, file: impl Into<PathBuf>) -> Self {
        Self::FunctionNotFound {
            function: function.into(),
            file: file.into(),
        }
    }

    /// Create a ParseError.
    pub fn parse_error(file: impl Into<PathBuf>, message: impl Into<String>) -> Self {
        Self::ParseError {
            file: file.into(),
            message: message.into(),
        }
    }
}
```

---

## Validation (`validation.rs`)

```rust
//! Input validation and path safety utilities for Pattern Analysis commands.
//!
//! Provides security-focused validation functions to mitigate:
//! - **TIGER-02**: Path traversal attacks via malicious file paths
//! - **TIGER-03**: Unbounded recursion in analysis
//! - **TIGER-04**: Memory exhaustion from large files
//! - **TIGER-08**: Stack overflow from deeply nested ASTs
//!
//! All file paths are canonicalized and checked against project boundaries.

use std::fs;
use std::path::{Path, PathBuf};

use super::error::{PatternsError, PatternsResult};

// =============================================================================
// Resource Limits (TIGER Mitigations)
// =============================================================================

/// Maximum file size for analysis (10 MB).
pub const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024;

/// Warning threshold for file size (1 MB).
pub const WARN_FILE_SIZE: u64 = 1024 * 1024;

/// Maximum files to scan in directory analysis.
pub const MAX_DIRECTORY_FILES: u32 = 1000;

/// Maximum AST traversal depth.
pub const MAX_AST_DEPTH: usize = 100;

/// Maximum recursion depth for analysis algorithms.
pub const MAX_ANALYSIS_DEPTH: usize = 500;

/// Maximum function name length.
pub const MAX_FUNCTION_NAME_LEN: usize = 256;

/// Maximum constraints to report per file.
pub const MAX_CONSTRAINTS_PER_FILE: usize = 500;

// =============================================================================
// Blocked System Directories
// =============================================================================

const BLOCKED_PREFIXES: &[&str] = &[
    "/etc/",
    "/etc/passwd",
    "/etc/shadow",
    "/root/",
    "/sys/",
    "/proc/",
    "/dev/",
    "/var/run/",
    "/var/log/",
    "/private/etc/",
    "C:\\Windows\\",
    "C:\\System32\\",
];

// =============================================================================
// Path Validation
// =============================================================================

/// Validate and canonicalize a file path.
///
/// # Security
///
/// - Canonicalizes path (resolves symlinks, `.`, `..`)
/// - Rejects system directories
/// - Validates UTF-8 encoding
pub fn validate_file_path(path: &Path) -> PatternsResult<PathBuf> {
    if !path.exists() {
        return Err(PatternsError::FileNotFound {
            path: path.to_path_buf(),
        });
    }

    let canonical = fs::canonicalize(path).map_err(|_| PatternsError::FileNotFound {
        path: path.to_path_buf(),
    })?;

    let canonical_str = canonical.to_string_lossy();
    for blocked in BLOCKED_PREFIXES {
        if canonical_str.starts_with(blocked) || canonical_str == blocked.trim_end_matches('/') {
            return Err(PatternsError::PathTraversal {
                path: path.to_path_buf(),
            });
        }
    }

    if canonical.to_str().is_none() {
        return Err(PatternsError::PathTraversal {
            path: path.to_path_buf(),
        });
    }

    Ok(canonical)
}

/// Validate a file path ensuring it stays within a project root.
pub fn validate_file_path_in_project(
    path: &Path,
    project_root: &Path,
) -> PatternsResult<PathBuf> {
    let canonical = validate_file_path(path)?;

    let canonical_root = fs::canonicalize(project_root).map_err(|_| PatternsError::FileNotFound {
        path: project_root.to_path_buf(),
    })?;

    if !canonical.starts_with(&canonical_root) {
        return Err(PatternsError::PathTraversal {
            path: path.to_path_buf(),
        });
    }

    Ok(canonical)
}

/// Check if a path contains path traversal patterns.
pub fn has_path_traversal_pattern(path: &Path) -> bool {
    let path_str = path.to_string_lossy();
    path_str.contains("..") || path_str.contains('\0')
}

// =============================================================================
// Function Name Validation
// =============================================================================

/// Validate a function name for safety.
pub fn validate_function_name(name: &str) -> PatternsResult<()> {
    if name.is_empty() {
        return Err(PatternsError::InvalidParameter {
            message: "function name cannot be empty".to_string(),
        });
    }

    if name.len() > MAX_FUNCTION_NAME_LEN {
        return Err(PatternsError::InvalidParameter {
            message: format!(
                "function name too long ({} chars, max {})",
                name.len(),
                MAX_FUNCTION_NAME_LEN
            ),
        });
    }

    let suspicious_chars = [';', '(', ')', '{', '}', '[', ']', '`', '"', '\'', '\\', '/', '\0'];
    for c in name.chars() {
        if suspicious_chars.contains(&c) {
            return Err(PatternsError::InvalidParameter {
                message: format!("function name contains invalid character: '{}'", c),
            });
        }
    }

    if let Some(first) = name.chars().next() {
        if !first.is_alphabetic() && first != '_' {
            return Err(PatternsError::InvalidParameter {
                message: "function name must start with letter or underscore".to_string(),
            });
        }
    }

    Ok(())
}

// =============================================================================
// Safe File Reading
// =============================================================================

/// Safely read a file with size limits and UTF-8 validation.
pub fn read_file_safe(path: &Path) -> PatternsResult<String> {
    let canonical = validate_file_path(path)?;

    let metadata = fs::metadata(&canonical)?;
    let size = metadata.len();

    if size > MAX_FILE_SIZE {
        return Err(PatternsError::FileTooLarge {
            path: path.to_path_buf(),
            bytes: size,
            max_bytes: MAX_FILE_SIZE,
        });
    }

    let content = fs::read(&canonical)?;

    String::from_utf8(content).map_err(|_| PatternsError::ParseError {
        file: path.to_path_buf(),
        message: "file is not valid UTF-8".to_string(),
    })
}

// =============================================================================
// Depth Checking
// =============================================================================

/// Check if analysis depth limit has been exceeded.
pub fn check_analysis_depth(current_depth: usize) -> PatternsResult<()> {
    if current_depth >= MAX_ANALYSIS_DEPTH {
        Err(PatternsError::DepthLimitExceeded {
            depth: current_depth as u32,
            max_depth: MAX_ANALYSIS_DEPTH as u32,
        })
    } else {
        Ok(())
    }
}

/// Check if file count limit has been exceeded.
pub fn check_file_count(count: u32, max_files: u32) -> PatternsResult<()> {
    if count > max_files {
        Err(PatternsError::TooManyFiles { count, max_files })
    } else {
        Ok(())
    }
}
```

---

## Command Specifications

### 1. behavioral

**Purpose:** Extract behavioral constraints (pre/postconditions, exceptions, side effects) from Python source code.

#### CLI Interface

```
tldr behavioral <file> [function] [OPTIONS]

Arguments:
  <file>      Python source file to analyze (required)
  [function]  Specific function to analyze (optional - analyzes all if not specified)

Options:
  -f, --format <FORMAT>    Output format [default: json] [possible values: json, text]
  --constraints            Generate LLM-ready constraints
```

#### Args Struct

```rust
#[derive(Debug, Args)]
pub struct BehavioralArgs {
    /// Python source file to analyze
    pub file: PathBuf,

    /// Specific function to analyze (optional)
    pub function: Option<String>,

    /// Output format
    #[arg(long, short = 'f', default_value = "json")]
    pub format: OutputFormat,

    /// Generate LLM-ready constraints
    #[arg(long)]
    pub constraints: bool,
}
```

#### Algorithm

1. Parse source file with tree-sitter-python
2. Detect docstring style (Google, NumPy, Sphinx, plain)
3. Check for icontract/deal imports
4. For each function:
   a. Extract preconditions from:
      - Guard clauses (`if x < 0: raise`)
      - Assertions (`assert isinstance(x, str)`)
      - Type hints
      - Docstring Args/Parameters section
   b. Extract postconditions from:
      - Return type hints
      - Assertions after `result =`
      - Docstring Returns section
   c. Extract exceptions from:
      - Explicit `raise` statements
      - Docstring Raises section
   d. Detect side effects by analyzing writes

#### Output Schema (JSON)

```json
{
  "file_path": "string",
  "docstring_style": "google|numpy|sphinx|plain",
  "has_icontract": false,
  "has_deal": false,
  "functions": [
    {
      "function_name": "string",
      "file_path": "string",
      "line": 10,
      "is_pure": true,
      "is_generator": false,
      "is_async": false,
      "preconditions": [
        {
          "param": "x",
          "expression": "x > 0",
          "description": "must be positive",
          "type_hint": "int",
          "source": "guard"
        }
      ],
      "postconditions": [...],
      "exceptions": [
        {
          "exception_type": "ValueError",
          "description": "if x is negative"
        }
      ],
      "yields": [...],
      "side_effects": [
        {
          "effect_type": "io",
          "target": "stdout"
        }
      ]
    }
  ],
  "classes": [
    {
      "class_name": "MyClass",
      "invariants": [{"expression": "self.count >= 0"}],
      "methods": [...]
    }
  ]
}
```

#### Exit Codes

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | File not found or parse error |
| 2 | Invalid arguments |

#### Example Usage

```bash
# Analyze all functions in a file
tldr behavioral src/utils.py

# Analyze specific function
tldr behavioral src/utils.py process_data

# Generate LLM constraints
tldr behavioral src/utils.py --constraints

# Text output
tldr behavioral src/utils.py -f text
```

---

### 2. cohesion

**Purpose:** Compute LCOM4 (Lack of Cohesion of Methods) metric for classes.

LCOM4=1 means the class is cohesive. LCOM4>1 suggests the class could be split into multiple classes.

#### CLI Interface

```
tldr cohesion <path> [OPTIONS]

Arguments:
  <path>  File or directory to analyze (required)

Options:
  --min-methods <N>        Minimum methods for analysis [default: 2]
  --include-dunder         Include dunder methods (__init__, etc.)
  -f, --format <FORMAT>    Output format [default: json]
```

#### Args Struct

```rust
#[derive(Debug, Args)]
pub struct CohesionArgs {
    /// File or directory to analyze
    pub path: PathBuf,

    /// Minimum methods for a class to be analyzed
    #[arg(long, default_value = "2")]
    pub min_methods: u32,

    /// Include dunder methods in analysis
    #[arg(long)]
    pub include_dunder: bool,

    /// Output format
    #[arg(long, short = 'f', default_value = "json")]
    pub format: OutputFormat,
}
```

#### Algorithm: LCOM4 via Union-Find

1. Parse class, extract methods and field accesses (`self.x`)
2. Build bipartite graph: methods <-> fields they access
3. Add edges for intra-class method calls (`self.method()`)
4. Count connected components via union-find
5. LCOM4 = number of connected components

```rust
/// Compute LCOM4 for a class.
///
/// # Algorithm
///
/// 1. Create a node for each method and each field
/// 2. Add edges: method -> field if method accesses field
/// 3. Add edges: method -> method if one calls the other
/// 4. Count connected components using union-find
fn compute_lcom4(methods: &[MethodAnalysis], fields: &[String]) -> u32 {
    let mut uf = UnionFind::new(methods.len() + fields.len());
    
    // Map method/field names to indices
    let method_idx: HashMap<&str, usize> = methods.iter()
        .enumerate()
        .map(|(i, m)| (m.name.as_str(), i))
        .collect();
    
    let field_idx: HashMap<&str, usize> = fields.iter()
        .enumerate()
        .map(|(i, f)| (f.as_str(), methods.len() + i))
        .collect();
    
    // Connect methods to fields they access
    for (i, method) in methods.iter().enumerate() {
        for field in &method.field_accesses {
            if let Some(&fi) = field_idx.get(field.as_str()) {
                uf.union(i, fi);
            }
        }
    }
    
    // Connect methods that call each other
    for (i, method) in methods.iter().enumerate() {
        for called in &method.method_calls {
            if let Some(&ci) = method_idx.get(called.as_str()) {
                uf.union(i, ci);
            }
        }
    }
    
    // Count unique roots (connected components)
    let mut roots = HashSet::new();
    for i in 0..methods.len() {
        roots.insert(uf.find(i));
    }
    
    roots.len() as u32
}
```

#### Output Schema (JSON)

```json
{
  "classes": [
    {
      "class_name": "UserManager",
      "file_path": "src/user.py",
      "line": 10,
      "lcom4": 2,
      "method_count": 6,
      "field_count": 4,
      "verdict": "split_candidate",
      "split_suggestion": "Consider splitting into: UserAuth (methods: login, logout, authenticate; fields: password_hash, session) and UserProfile (methods: get_name, update_email; fields: name, email)",
      "components": [
        {"methods": ["login", "logout", "authenticate"], "fields": ["password_hash", "session"]},
        {"methods": ["get_name", "update_email"], "fields": ["name", "email"]}
      ]
    }
  ],
  "summary": {
    "total_classes": 5,
    "cohesive": 3,
    "split_candidates": 2,
    "avg_lcom4": 1.4
  }
}
```

#### Exit Codes

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | File/directory not found or parse error |

---

### 3. coupling

**Purpose:** Analyze coupling between two modules by tracking cross-module function calls.

#### CLI Interface

```
tldr coupling <path_a> <path_b> [OPTIONS]

Arguments:
  <path_a>  First module to analyze (required)
  <path_b>  Second module to analyze (required)

Options:
  -f, --format <FORMAT>  Output format [default: json]
```

#### Args Struct

```rust
#[derive(Debug, Args)]
pub struct CouplingArgs {
    /// First module to analyze
    pub path_a: PathBuf,

    /// Second module to analyze
    pub path_b: PathBuf,

    /// Output format
    #[arg(long, short = 'f', default_value = "json")]
    pub format: OutputFormat,
}
```

#### Algorithm

1. Parse both modules, extract imports and defined names
2. Find function call sites in each module
3. Match calls to imported names from the other module
4. Compute coupling score as `cross_calls / (total_functions * 2)`
5. Determine verdict based on score threshold

```rust
/// Compute coupling score between two modules.
fn compute_coupling_score(a_to_b: u32, b_to_a: u32, funcs_a: u32, funcs_b: u32) -> f64 {
    let total_funcs = funcs_a + funcs_b;
    if total_funcs == 0 {
        return 0.0;
    }
    let cross_calls = a_to_b + b_to_a;
    (cross_calls as f64) / (total_funcs as f64 * 2.0)
}
```

#### Output Schema (JSON)

```json
{
  "path_a": "src/user.py",
  "path_b": "src/auth.py",
  "a_to_b": {
    "calls": [
      {"caller": "get_user", "callee": "validate_token", "line": 15},
      {"caller": "create_user", "callee": "hash_password", "line": 32}
    ],
    "count": 2
  },
  "b_to_a": {
    "calls": [
      {"caller": "login", "callee": "get_user", "line": 10}
    ],
    "count": 1
  },
  "total_calls": 3,
  "coupling_score": 0.25,
  "verdict": "moderate"
}
```

#### Exit Codes

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | File not found or parse error |

---

### 4. mutability

**Purpose:** Analyze mutability of variables, parameters, collections, and class fields.

#### CLI Interface

```
tldr mutability <file> [function] [OPTIONS]

Arguments:
  <file>      Source file to analyze (required)
  [function]  Function to analyze (optional)

Options:
  --lang <LANG>           Language override (python only) [default: auto]
  --include-fields        Include class field mutability analysis (M3)
  --include-aliases       Include alias propagation analysis (M5)
  --no-collections        Skip collection mutation detection (M4)
  --constraints           Generate type constraints (M8)
  --summary               Output summary statistics only
  -f, --format <FORMAT>   Output format [default: json]
```

#### Args Struct

```rust
#[derive(Debug, Args)]
pub struct MutabilityArgs {
    /// Source file to analyze
    pub file: PathBuf,

    /// Function to analyze (optional)
    pub function: Option<String>,

    /// Language override
    #[arg(long, default_value = "auto")]
    pub lang: String,

    /// Include class field mutability analysis
    #[arg(long)]
    pub include_fields: bool,

    /// Include alias propagation analysis
    #[arg(long)]
    pub include_aliases: bool,

    /// Skip collection mutation detection
    #[arg(long)]
    pub no_collections: bool,

    /// Generate type constraints
    #[arg(long)]
    pub constraints: bool,

    /// Output summary only
    #[arg(long)]
    pub summary: bool,

    /// Output format
    #[arg(long, short = 'f', default_value = "json")]
    pub format: OutputFormat,
}
```

#### Analysis Types

| ID | Analysis | Description |
|----|----------|-------------|
| M1 | Variable mutability | Which variables are reassigned |
| M2 | Parameter mutations | Which parameters are modified |
| M3 | Field mutability | Class fields modified after `__init__` |
| M4 | Collection mutations | `list.append`, `dict.update`, etc. |
| M5 | Alias propagation | Mutation through aliases |
| M8 | Type constraints | Generate immutable type hints |

#### Output Schema (JSON)

```json
{
  "file": "src/utils.py",
  "language": "python",
  "functions": [
    {
      "name": "process",
      "variables": [
        {"name": "count", "mutable": true, "reassignments": 3, "mutations": 0},
        {"name": "result", "mutable": false, "reassignments": 0, "mutations": 0}
      ],
      "parameters": [
        {"name": "data", "mutated": true, "mutation_sites": [15, 22]},
        {"name": "config", "mutated": false, "mutation_sites": []}
      ],
      "collection_mutations": [
        {"variable": "results", "operation": "append", "line": 18}
      ]
    }
  ],
  "classes": [
    {
      "name": "Counter",
      "fields": [
        {"name": "count", "mutable": true, "init_only": false},
        {"name": "name", "mutable": false, "init_only": true}
      ]
    }
  ],
  "summary": {
    "functions_analyzed": 5,
    "classes_analyzed": 2,
    "total_variables": 15,
    "mutable_variables": 6,
    "immutable_variables": 9,
    "immutable_pct": 60.0,
    "parameters_analyzed": 10,
    "mutated_parameters": 2,
    "unmutated_pct": 80.0,
    "fields_analyzed": 8,
    "mutable_fields": 3,
    "constraints_generated": 0
  },
  "analysis_time_ms": 45
}
```

#### Exit Codes

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | File/function not found or parse error |
| 2 | Invalid arguments |

---

### 5. purity

**Purpose:** Analyze function purity (side-effect free) across a file or directory.

#### CLI Interface

```
tldr purity <path> [OPTIONS]

Arguments:
  <path>  File or directory to analyze (required)

Options:
  --no-interprocedural    Disable interprocedural propagation
  --include-tests         Include test files in directory analysis
  -f, --format <FORMAT>   Output format [default: json]
```

#### Args Struct

```rust
#[derive(Debug, Args)]
pub struct PurityArgs {
    /// File or directory to analyze
    pub path: PathBuf,

    /// Disable interprocedural propagation
    #[arg(long)]
    pub no_interprocedural: bool,

    /// Include test files in directory analysis
    #[arg(long)]
    pub include_tests: bool,

    /// Output format
    #[arg(long, short = 'f', default_value = "json")]
    pub format: OutputFormat,
}
```

#### Algorithm

1. For each function, detect direct effects:
   - I/O operations (open, print, read, write)
   - Global variable writes
   - Attribute writes (self.x = ...)
   - Collection mutations
2. If interprocedural enabled:
   - Build call graph
   - Propagate impurity from callees to callers
3. Assign confidence based on analysis completeness

#### Output Schema (JSON)

```json
{
  "files": [
    {
      "source_file": "src/utils.py",
      "functions": [
        {"name": "add", "pure": true, "effects": [], "confidence": "high"},
        {"name": "log", "pure": false, "effects": ["io"], "confidence": "high"},
        {"name": "update_cache", "pure": false, "effects": ["global_write"], "confidence": "medium"}
      ],
      "pure_count": 1
    }
  ],
  "total_functions": 3,
  "total_pure": 1
}
```

#### Exit Codes

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | File/directory not found or parse error |

---

### 6. temporal

**Purpose:** Mine temporal constraints (method call sequences) from a codebase.

#### CLI Interface

```
tldr temporal <path> [OPTIONS]

Arguments:
  <path>  Directory or file to analyze (required)

Options:
  --min-support <N>        Minimum pattern occurrences [default: 2]
  --min-confidence <F>     Minimum confidence (0.0-1.0) [default: 0.5]
  --query <METHOD>         Filter for specific method
  --lang <LANG>            Language [default: auto]
  --max-files <N>          Maximum files to analyze [default: 1000]
  --include-trigrams       Mine 3-method sequences
  --include-examples <N>   Number of examples per constraint [default: 3]
  -f, --format <FORMAT>    Output format [default: json]
```

#### Args Struct

```rust
#[derive(Debug, Args)]
pub struct TemporalArgs {
    /// Directory or file to analyze
    pub path: PathBuf,

    /// Minimum occurrences for a pattern
    #[arg(long, default_value = "2")]
    pub min_support: u32,

    /// Minimum confidence threshold (0.0-1.0)
    #[arg(long, default_value = "0.5")]
    pub min_confidence: f64,

    /// Filter for specific method
    #[arg(long)]
    pub query: Option<String>,

    /// Language
    #[arg(long, default_value = "auto")]
    pub lang: String,

    /// Maximum files to analyze
    #[arg(long, default_value = "1000")]
    pub max_files: u32,

    /// Mine 3-method sequences
    #[arg(long)]
    pub include_trigrams: bool,

    /// Number of examples per constraint
    #[arg(long, default_value = "3")]
    pub include_examples: u32,

    /// Output format
    #[arg(long, short = 'f', default_value = "json")]
    pub format: OutputFormat,
}
```

#### Algorithm

1. Extract method call sequences from each function
2. Build frequency table of (before, after) pairs
3. Calculate confidence: `count(A->B) / count(A)`
4. Filter by min_support and min_confidence
5. Optionally mine trigrams (3-method sequences)

#### Output Schema (JSON)

```json
{
  "constraints": [
    {
      "before": "open",
      "after": "close",
      "support": 15,
      "confidence": 0.93,
      "examples": [
        {"file": "src/io.py", "line": 42},
        {"file": "src/db.py", "line": 18}
      ]
    },
    {
      "before": "acquire",
      "after": "release",
      "support": 8,
      "confidence": 0.89,
      "examples": [...]
    }
  ],
  "trigrams": [
    {
      "sequence": ["open", "read", "close"],
      "support": 12,
      "confidence": 0.85
    }
  ],
  "metadata": {
    "files_analyzed": 45,
    "sequences_extracted": 230,
    "min_support": 2,
    "min_confidence": 0.5
  }
}
```

#### Exit Codes

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | Error (file not found, parse error) |
| 2 | No constraints found (not an error) |

---

### 7. interface

**Purpose:** Extract the public interface (API surface) of Python files.

#### CLI Interface

```
tldr interface <path> [OPTIONS]

Arguments:
  <path>  File or directory to analyze (required)

Options:
  --lang <LANG>          Language [default: python]
  -f, --format <FORMAT>  Output format [default: json]
```

#### Args Struct

```rust
#[derive(Debug, Args)]
pub struct InterfaceArgs {
    /// File or directory to analyze
    pub path: PathBuf,

    /// Language
    #[arg(long, default_value = "python")]
    pub lang: String,

    /// Output format
    #[arg(long, short = 'f', default_value = "json")]
    pub format: OutputFormat,
}
```

#### Algorithm

1. Parse source file
2. Extract `__all__` if defined
3. For each top-level definition:
   - If name starts with `_`, skip (private)
   - If function: extract name, signature, docstring, async status
   - If class: extract name, bases, public methods
4. For directory: aggregate across all `.py` files

#### Output Schema (JSON)

```json
{
  "file": "src/api.py",
  "all_exports": ["Client", "connect", "Config"],
  "functions": [
    {
      "name": "connect",
      "signature": "def connect(host: str, port: int = 8080) -> Connection",
      "docstring": "Connect to the server.",
      "lineno": 15,
      "is_async": false
    }
  ],
  "classes": [
    {
      "name": "Client",
      "lineno": 30,
      "bases": ["BaseClient"],
      "methods": [
        {"name": "send", "signature": "def send(self, data: bytes) -> None", "is_async": true},
        {"name": "receive", "signature": "def receive(self) -> bytes", "is_async": true}
      ],
      "private_method_count": 3
    }
  ]
}
```

#### Exit Codes

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | File/directory not found or parse error |

---

### 8. resources

**Purpose:** Analyze resource lifecycle to detect leaks, double-close, and use-after-close.

#### CLI Interface

```
tldr resources <file> [function] [OPTIONS]

Arguments:
  <file>      Source file to analyze (required)
  [function]  Function to analyze (optional)

Options:
  --lang <LANG>           Language override [default: auto]
  --check-leaks           Run leak detection (R2) [default: true]
  --check-double-close    Run double-close detection (R3)
  --check-use-after-close Run use-after-close detection (R4)
  --check-all             Run all checks (R2, R3, R4)
  --suggest-context       Suggest context manager usage (R6)
  --show-paths            Show detailed leak paths (R7)
  --constraints           Generate LLM constraints (R9)
  --summary               Output summary only
  -f, --format <FORMAT>   Output format [default: json]
```

#### Args Struct

```rust
#[derive(Debug, Args)]
pub struct ResourcesArgs {
    /// Source file to analyze
    pub file: PathBuf,

    /// Function to analyze (optional)
    pub function: Option<String>,

    /// Language override
    #[arg(long, default_value = "auto")]
    pub lang: String,

    /// Run leak detection (enabled by default)
    #[arg(long, default_value = "true")]
    pub check_leaks: bool,

    /// Run double-close detection
    #[arg(long)]
    pub check_double_close: bool,

    /// Run use-after-close detection
    #[arg(long)]
    pub check_use_after_close: bool,

    /// Run all checks
    #[arg(long)]
    pub check_all: bool,

    /// Suggest context manager usage
    #[arg(long)]
    pub suggest_context: bool,

    /// Show detailed leak paths
    #[arg(long)]
    pub show_paths: bool,

    /// Generate LLM constraints
    #[arg(long)]
    pub constraints: bool,

    /// Output summary only
    #[arg(long)]
    pub summary: bool,

    /// Output format
    #[arg(long, short = 'f', default_value = "json")]
    pub format: OutputFormat,
}
```

#### Analysis Types

| ID | Analysis | Description |
|----|----------|-------------|
| R1 | Resource detection | Identify resources requiring close |
| R2 | Close verification | All-paths leak detection |
| R3 | Double-close detection | Closing resources twice |
| R4 | Use-after-close | Using closed resources |
| R6 | Context manager suggestions | Suggest `with` statement |
| R7 | Leak path enumeration | Detailed paths to leaks |
| R9 | Constraint generation | LLM-ready constraints |

#### Algorithm (R2 - Leak Detection)

1. Build CFG for function
2. Identify resource creation points (open, socket, connect)
3. For each resource:
   a. Find all paths from creation to function exit
   b. Check if all paths include close
   c. If not, report as potential leak

```rust
/// Detect potential resource leaks using CFG path analysis.
fn detect_leaks(cfg: &Cfg, resources: &[Resource]) -> Vec<LeakInfo> {
    let mut leaks = Vec::new();
    
    for resource in resources {
        let creation_block = cfg.block_containing(resource.creation_line);
        let exit_blocks = cfg.exit_blocks();
        
        // Check all paths from creation to each exit
        for exit in exit_blocks {
            let paths = cfg.all_paths(creation_block, exit);
            for path in paths {
                if !path_has_close(&path, &resource.name) {
                    leaks.push(LeakInfo {
                        resource: resource.name.clone(),
                        line: resource.creation_line,
                        paths: Some(vec![format_path(&path)]),
                    });
                    break; // One leak path is enough
                }
            }
        }
    }
    
    leaks
}
```

#### Output Schema (JSON)

```json
{
  "file": "src/db.py",
  "language": "python",
  "function": "query",
  "resources": [
    {"name": "conn", "type": "connection", "line": 10, "closed": true},
    {"name": "file", "type": "file", "line": 15, "closed": false}
  ],
  "leaks": [
    {
      "resource": "file",
      "line": 15,
      "paths": ["15 -> 18 -> 22 (exception) -> exit"]
    }
  ],
  "double_closes": [
    {"resource": "conn", "first_close": 25, "second_close": 30}
  ],
  "use_after_closes": [
    {"resource": "file", "close_line": 20, "use_line": 22}
  ],
  "suggestions": [
    {"resource": "file", "suggestion": "with open(...) as file:"}
  ],
  "constraints": [
    {"rule": "file must be closed on all paths", "context": "query function", "confidence": 0.95}
  ],
  "summary": {
    "resources_detected": 2,
    "leaks_found": 1,
    "double_closes_found": 1,
    "use_after_closes_found": 1
  },
  "analysis_time_ms": 120
}
```

#### Exit Codes

| Code | Meaning |
|------|---------|
| 0 | Success, no issues |
| 1 | File/function not found or parse error |
| 2 | Invalid arguments |
| 3 | Issues found (leaks, double-close, etc.) |

---

## Testing Requirements

### Unit Tests

Each command should have tests for:

1. **Happy path**: Valid input produces expected output
2. **Edge cases**: Empty files, single function, no matches
3. **Error handling**: File not found, parse errors, invalid args
4. **Resource limits**: Large files, deep nesting

### Integration Tests

1. **End-to-end CLI tests**: Run command and verify JSON output
2. **Cross-command consistency**: Ensure types are consistent
3. **Performance tests**: Verify reasonable performance on large files

### Test Coverage Target

- Minimum 80% line coverage
- 100% coverage on error paths
- All TIGER mitigations tested

---

## Security Mitigations

### TIGER (Critical)

| ID | Risk | Mitigation |
|----|------|------------|
| T2 | Path traversal | `validate_file_path`, `validate_file_path_in_project` |
| T3 | Unbounded loops | `MAX_ANALYSIS_DEPTH`, `check_analysis_depth` |
| T4 | Memory exhaustion | `MAX_FILE_SIZE`, `MAX_DIRECTORY_FILES` |
| T8 | Stack overflow | `MAX_AST_DEPTH` |

### ELEPHANT (Important)

| ID | Risk | Mitigation |
|----|------|------------|
| E1 | Timeouts | Add timeout parameter for long analyses |
| E2 | Resource limits | `check_file_count`, max files in directory |
| E3 | Partial failure | Graceful handling of parse errors |
| E4 | Unicode handling | UTF-8 validation in `read_file_safe` |

### PAPER_TIGER (Low)

| ID | Risk | Mitigation |
|----|------|------------|
| P1 | Error messages | Don't leak internal paths |
| P2 | UX | Clear progress for directory scans |
| P3 | Documentation | Explain confidence levels |

---

## Implementation Phases

### Phase 1: Foundation
**Files to create:** `mod.rs`, `types.rs`, `error.rs`, `validation.rs`

**Acceptance:**
- [ ] All types compile
- [ ] Error enum complete
- [ ] Validation functions tested

**Estimated effort:** Small

### Phase 2: Simple Commands
**Files to create:** `cohesion.rs`, `coupling.rs`, `interface.rs`, `purity.rs`

**Dependencies:** Phase 1

**Acceptance:**
- [ ] `tldr cohesion` computes LCOM4
- [ ] `tldr coupling` analyzes module pairs
- [ ] `tldr interface` extracts API
- [ ] `tldr purity` detects effects

**Estimated effort:** Medium

### Phase 3: Medium Commands
**Files to create:** `temporal.rs`, `behavioral.rs`, `mutability.rs`

**Dependencies:** Phase 2

**Acceptance:**
- [ ] `tldr temporal` mines constraints
- [ ] `tldr behavioral` extracts pre/postconditions
- [ ] `tldr mutability` tracks mutations

**Estimated effort:** Medium

### Phase 4: Complex Command
**Files to create:** `resources.rs`

**Dependencies:** Phase 3

**Acceptance:**
- [ ] `tldr resources` detects leaks
- [ ] Double-close detection works
- [ ] Use-after-close detection works

**Estimated effort:** Large

### Phase 5: Testing & Documentation

**Coverage target:** 80%

---

## Success Criteria

1. All 8 commands pass `--help` and produce valid JSON
2. `tldr cohesion` correctly computes LCOM4 on test classes
3. `tldr coupling` correctly identifies cross-module calls
4. `tldr purity` correctly identifies pure functions
5. `tldr temporal` discovers `open->close` patterns
6. `tldr behavioral` extracts guard clause preconditions
7. `tldr mutability` tracks parameter mutations
8. `tldr resources` detects resource leaks in test cases
9. Error messages are actionable and specific
10. All TIGER mitigations pass security review