double-o 0.8.0

Context-efficient command runner for AI coding agents
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
use assert_cmd::Command;
use predicates::prelude::*;
use std::os::unix::fs::PermissionsExt;
use tempfile::TempDir;

fn oo() -> Command {
    Command::cargo_bin("oo").unwrap()
}

#[test]
fn test_echo_passthrough() {
    oo().args(["echo", "hello"])
        .assert()
        .success()
        .stdout("hello\n");
}

#[test]
fn test_multiword_echo() {
    oo().args(["echo", "hello", "world"])
        .assert()
        .success()
        .stdout("hello world\n");
}

#[test]
fn test_false_failure() {
    oo().args(["false"])
        .assert()
        .failure()
        .stdout(predicate::str::starts_with("\u{2717}")); // ✗
}

#[test]
fn test_exit_code_preserved() {
    oo().args(["sh", "-c", "exit 42"]).assert().code(42);
}

#[test]
fn test_version() {
    oo().arg("version")
        .assert()
        .success()
        .stdout(predicate::str::contains(env!("CARGO_PKG_VERSION")));
}

#[test]
fn test_no_args_shows_help() {
    oo().assert()
        .success()
        .stdout(predicate::str::contains("Usage"));
}

#[test]
fn test_large_output_gets_indicator() {
    // `git log` is categorized as Data, so large output gets indexed (●).
    // Create a temp git repo to generate logs that exceed 4KB threshold.
    let dir = TempDir::new().unwrap();
    Command::new("git")
        .args(["init"])
        .current_dir(dir.path())
        .output()
        .unwrap();

    // Create multiple commits with content to exceed 4KB
    for i in 0..100 {
        std::fs::write(dir.path().join("file.txt"), format!("content {}\n", i)).unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(dir.path())
            .output()
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", &format!("commit {}", i)])
            .env("GIT_AUTHOR_NAME", "Test")
            .env("GIT_AUTHOR_EMAIL", "test@example.com")
            .env("GIT_COMMITTER_NAME", "Test")
            .env("GIT_COMMITTER_EMAIL", "test@example.com")
            .current_dir(dir.path())
            .output()
            .unwrap();
    }

    // Run `oo git log` in the repo — should get ● (Large/indexed) indicator
    oo().args(["git", "log"])
        .current_dir(dir.path())
        .assert()
        .success()
        .stdout(predicate::str::starts_with("\u{25CF}")); // ●
}

#[test]
fn test_stderr_included_in_failure() {
    oo().args(["sh", "-c", "echo failure_msg >&2; exit 1"])
        .assert()
        .failure()
        .stdout(predicate::str::contains("failure_msg"));
}

#[test]
fn test_forget_runs() {
    // OO_DATA_DIR isolates the store so the project-scoped delete (issue
    // #168) never wipes the developer's real index.
    let dir = TempDir::new().unwrap();
    oo().arg("forget")
        .env("OO_DATA_DIR", dir.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("Cleared project data"));
}

#[test]
fn test_help_no_args_shows_usage() {
    oo().arg("help")
        .assert()
        .success()
        .stdout(predicate::str::contains("Usage:"));
}

#[test]
fn test_help_includes_help_cmd_in_usage() {
    // Verify the help command itself appears in the no-args usage output
    oo().assert()
        .success()
        .stdout(predicate::str::contains("help [cmd]"));
}

/// The no-args / `oo help` output must list all 8 reserved subcommands,
/// each with a one-line description, plus the tool description line.
fn assert_full_subcommand_list(
    assertion: assert_cmd::assert::Assert,
) -> assert_cmd::assert::Assert {
    let mut assertion = assertion.success();
    for (name, description) in [
        ("recall", "Search indexed output"),
        ("forget", "Clear indexed output for this project"),
        ("learn", "Learn output compression patterns"),
        ("help [cmd]", "cheat-sheet for cmd via cheat.sh"),
        ("init", "Set up hooks for agent frameworks"),
        ("patterns", "List output compression patterns"),
        ("version", "Show version"),
        ("hook", "Agent hook processor"),
    ] {
        assertion = assertion.stdout(predicate::str::contains(name));
        assertion = assertion.stdout(predicate::str::contains(description));
    }
    assertion = assertion.stdout(predicate::str::contains(
        "init [--format claude|generic | --agent pi|claude-code [--global]]",
    ));
    assertion = assertion.stdout(predicate::str::contains(
        "Context-efficient command runner for AI coding agents",
    ));
    // The internal _learn_bg command must never leak into help output.
    assertion.stdout(predicate::str::contains("_learn_bg").not())
}

#[test]
fn test_no_args_lists_all_subcommands() {
    assert_full_subcommand_list(oo().assert());
}

#[test]
fn test_help_no_args_lists_all_subcommands() {
    assert_full_subcommand_list(oo().arg("help").assert());
}

#[test]
fn test_help_empty_arg() {
    Command::cargo_bin("oo")
        .unwrap()
        .args(&["help", ""])
        .assert()
        .failure();
}

// ---------------------------------------------------------------------------
// oo init
// ---------------------------------------------------------------------------

#[test]
fn test_init_creates_hooks_json() {
    let dir = TempDir::new().unwrap();
    oo().arg("init").current_dir(dir.path()).assert().success();

    let hooks_path = dir.path().join(".claude").join("hooks.json");
    assert!(
        hooks_path.exists(),
        ".claude/hooks.json must exist after oo init"
    );
}

#[test]
fn test_init_hooks_json_is_valid_json() {
    let dir = TempDir::new().unwrap();
    oo().arg("init").current_dir(dir.path()).assert().success();

    let content = std::fs::read_to_string(dir.path().join(".claude").join("hooks.json")).unwrap();
    let parsed: serde_json::Value =
        serde_json::from_str(&content).expect("hooks.json must be valid JSON");
    assert!(parsed.get("hooks").is_some());
}

#[test]
fn test_init_prints_agents_snippet() {
    let dir = TempDir::new().unwrap();
    oo().arg("init")
        .current_dir(dir.path())
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Prefix all shell commands with `oo`",
        ));
}

#[test]
fn test_init_second_run_does_not_overwrite() {
    let dir = TempDir::new().unwrap();

    // First run creates the file.
    oo().arg("init").current_dir(dir.path()).assert().success();

    // Overwrite with sentinel content.
    let hooks_path = dir.path().join(".claude").join("hooks.json");
    std::fs::write(&hooks_path, r#"{"hooks":[],"sentinel":true}"#).unwrap();

    // Second run must not clobber the file.
    oo().arg("init").current_dir(dir.path()).assert().success();

    let after = std::fs::read_to_string(&hooks_path).unwrap();
    assert!(
        after.contains("\"sentinel\":true"),
        "pre-existing hooks.json must not be overwritten on second oo init"
    );
}

#[test]
fn test_init_second_run_succeeds_without_error() {
    let dir = TempDir::new().unwrap();
    oo().arg("init").current_dir(dir.path()).assert().success();
    // Second invocation must exit 0 — idempotent.
    oo().arg("init").current_dir(dir.path()).assert().success();
}

// ---------------------------------------------------------------------------
// oo init --format generic
// ---------------------------------------------------------------------------

#[test]
fn test_init_format_generic_exits_success() {
    let dir = TempDir::new().unwrap();
    oo().args(["init", "--format", "generic"])
        .current_dir(dir.path())
        .assert()
        .success();
}

#[test]
fn test_init_format_generic_prints_agents_snippet() {
    let dir = TempDir::new().unwrap();
    oo().args(["init", "--format", "generic"])
        .current_dir(dir.path())
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Prefix all shell commands with `oo`",
        ));
}

#[test]
fn test_init_format_generic_prints_setup_section() {
    let dir = TempDir::new().unwrap();
    oo().args(["init", "--format", "generic"])
        .current_dir(dir.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("## Setup"));
}

#[test]
fn test_init_format_generic_prints_shell_commands_instructions() {
    let dir = TempDir::new().unwrap();
    oo().args(["init", "--format", "generic"])
        .current_dir(dir.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("oo recall"))
        .stdout(predicate::str::contains("oo help"))
        .stdout(predicate::str::contains("oo learn"));
}

#[test]
fn test_init_format_generic_prints_alias_section() {
    let dir = TempDir::new().unwrap();
    oo().args(["init", "--format", "generic"])
        .current_dir(dir.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("alias o='oo'"));
}

#[test]
fn test_init_format_generic_does_not_create_hooks_json() {
    let dir = TempDir::new().unwrap();
    oo().args(["init", "--format", "generic"])
        .current_dir(dir.path())
        .assert()
        .success();
    // Generic format must NOT create any files.
    let hooks_path = dir.path().join(".claude").join("hooks.json");
    assert!(
        !hooks_path.exists(),
        "oo init --format generic must not create .claude/hooks.json"
    );
}

// ---------------------------------------------------------------------------
// oo init --format claude
// ---------------------------------------------------------------------------

#[test]
fn test_init_format_claude_creates_hooks_json() {
    let dir = TempDir::new().unwrap();
    oo().arg("init").current_dir(dir.path()).assert().success();
    let hooks_path = dir.path().join(".claude").join("hooks.json");
    assert!(
        hooks_path.exists(),
        ".claude/hooks.json must exist after oo init --format claude"
    );
}

#[test]
fn test_init_format_claude_prints_agents_snippet() {
    let dir = TempDir::new().unwrap();
    oo().arg("init")
        .current_dir(dir.path())
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Prefix all shell commands with `oo`",
        ));
}

// ---------------------------------------------------------------------------
// oo init --agent pi
// ---------------------------------------------------------------------------

/// `oo init --agent pi` in a temp git repo writes the extension at the git
/// root and prints the written path. HOME is overridden (defensive pattern)
/// so the child never touches the real home.
#[test]
fn test_init_agent_pi_creates_extension_at_git_root() {
    let dir = TempDir::new().unwrap();
    // Create a .git dir so find_root resolves the git root (not cwd fallback).
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();
    oo().args(["init", "--agent", "pi"])
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .env_remove("OO_PI_EXTENSIONS_DIR")
        .assert()
        .success()
        .stdout(predicate::str::contains("Created"))
        .stdout(predicate::str::contains(".pi/extensions/oo.ts"));

    let ext = dir.path().join(".pi").join("extensions").join("oo.ts");
    assert!(
        ext.exists(),
        "oo.ts must exist at the git root after oo init --agent pi"
    );
}

/// Re-running `oo init --agent pi` with an identical existing file is a
/// no-op ("already installed") and still exits 0.
#[test]
fn test_init_agent_pi_idempotent_identical_file() {
    let dir = TempDir::new().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();
    oo().args(["init", "--agent", "pi"])
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .assert()
        .success();

    let ext = dir.path().join(".pi").join("extensions").join("oo.ts");
    let before = std::fs::read_to_string(&ext).unwrap();

    oo().args(["init", "--agent", "pi"])
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("already installed"));

    let after = std::fs::read_to_string(&ext).unwrap();
    assert_eq!(
        after, before,
        "identical file must be a no-op (byte-identical after re-run)"
    );
}

/// An existing DIFFERENT file is not overwritten — the command explains how
/// to proceed and still exits 0 (mirrors the Claude path warn-and-skip).
#[test]
fn test_init_agent_pi_does_not_overwrite_different_file() {
    let dir = TempDir::new().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();
    let ext_dir = dir.path().join(".pi").join("extensions");
    std::fs::create_dir_all(&ext_dir).unwrap();
    let ext = ext_dir.join("oo.ts");
    let custom = "// user-edited extension\nexport default function () {}\n";
    std::fs::write(&ext, custom).unwrap();

    oo().args(["init", "--agent", "pi"])
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .assert()
        .success()
        .stderr(predicate::str::contains("not overwritten"));

    assert_eq!(
        std::fs::read_to_string(&ext).unwrap(),
        custom,
        "existing different file must not be overwritten"
    );
}

/// `--agent pi` outside a git repo writes under cwd (find_root fallback).
#[test]
fn test_init_agent_pi_outside_repo_writes_under_cwd() {
    let dir = TempDir::new().unwrap();
    // No .git dir — find_root falls back to cwd.
    oo().args(["init", "--agent", "pi"])
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .assert()
        .success();

    let ext = dir.path().join(".pi").join("extensions").join("oo.ts");
    assert!(
        ext.exists(),
        "oo.ts must be created under cwd outside a git repo"
    );
}

/// `oo init --agent pi --global` writes under the env-overridden HOME
/// (`$TEMPHOME/.pi/agent/extensions/oo.ts`), never under the git root.
#[test]
fn test_init_agent_pi_global_writes_under_home() {
    let home = TempDir::new().unwrap();
    let repo = TempDir::new().unwrap();
    std::fs::create_dir_all(repo.path().join(".git")).unwrap();
    oo().args(["init", "--agent", "pi", "--global"])
        .current_dir(repo.path())
        .env("HOME", home.path())
        .env_remove("OO_PI_EXTENSIONS_DIR")
        .assert()
        .success();

    let ext = home
        .path()
        .join(".pi")
        .join("agent")
        .join("extensions")
        .join("oo.ts");
    assert!(
        ext.exists(),
        "global oo.ts must land under $TEMPHOME/.pi/agent/extensions"
    );
    // The project (git) root must NOT have received the file — global is
    // home-based and never consults find_root.
    let project_ext = repo.path().join(".pi").join("extensions").join("oo.ts");
    assert!(
        !project_ext.exists(),
        "global install must not write under the git root"
    );
}

/// `OO_PI_EXTENSIONS_DIR` is the FINAL extensions directory: the file lands
/// at `$OO_PI_EXTENSIONS_DIR/oo.ts`, never with a `.pi/agent/extensions`
/// suffix appended, and the git root is never consulted.
#[test]
fn test_init_agent_pi_global_extensions_dir_is_final_dir() {
    let ext_dir = TempDir::new().unwrap();
    let repo = TempDir::new().unwrap();
    std::fs::create_dir_all(repo.path().join(".git")).unwrap();
    oo().args(["init", "--agent", "pi", "--global"])
        .current_dir(repo.path())
        .env("HOME", repo.path())
        .env("OO_PI_EXTENSIONS_DIR", ext_dir.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("Created"));

    let ext = ext_dir.path().join("oo.ts");
    assert!(
        ext.exists(),
        "global oo.ts must land at $OO_PI_EXTENSIONS_DIR/oo.ts"
    );
    // No `.pi/agent/extensions` suffix must be appended under the override.
    let suffixed = ext_dir
        .path()
        .join(".pi")
        .join("agent")
        .join("extensions")
        .join("oo.ts");
    assert!(
        !suffixed.exists(),
        "no .pi/agent/extensions suffix may be appended"
    );
    // The project (git) root must NOT have received the file.
    let project_ext = repo.path().join(".pi").join("extensions").join("oo.ts");
    assert!(
        !project_ext.exists(),
        "global install must not write under the git root"
    );
}

// ---------------------------------------------------------------------------
// oo init --agent claude-code
// ---------------------------------------------------------------------------

/// `oo init --agent claude-code` in a temp git repo merges the oo hook into
/// `.claude/settings.json` at the git root and prints the written path. HOME
/// and OO_CLAUDE_DIR are overridden (defensive) so the child never touches the
/// real home / claude config.
#[test]
fn test_init_agent_claude_code_creates_settings_json_at_git_root() {
    let dir = TempDir::new().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();
    oo().args(["init", "--agent", "claude-code"])
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .env_remove("OO_CLAUDE_DIR")
        .assert()
        .success();

    let settings = dir.path().join(".claude").join("settings.json");
    assert!(
        settings.exists(),
        ".claude/settings.json must exist after oo init --agent claude-code"
    );
    let v: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&settings).unwrap()).unwrap();
    assert!(
        count_oo_hook_entries(&v) >= 1,
        "settings.json must register `oo hook claude`"
    );
}

/// Count the `oo hook claude` entries under `hooks.PreToolUse` (summed across
/// all matcher groups) — the shared check for the init-claude-code tests.
fn count_oo_hook_entries(v: &serde_json::Value) -> usize {
    v["hooks"]["PreToolUse"]
        .as_array()
        .map(|groups| {
            groups
                .iter()
                .filter_map(|g| g["hooks"].as_array())
                .map(|cmds| {
                    cmds.iter()
                        .filter(|c| c["command"] == "oo hook claude")
                        .count()
                })
                .sum::<usize>()
        })
        .unwrap_or(0)
}

/// Re-running `oo init --agent claude-code` is idempotent — exactly one oo
/// entry remains.
#[test]
fn test_init_agent_claude_code_idempotent() {
    let dir = TempDir::new().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();
    let settings = dir.path().join(".claude").join("settings.json");
    oo().args(["init", "--agent", "claude-code"])
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .env_remove("OO_CLAUDE_DIR")
        .assert()
        .success();
    let before = std::fs::read_to_string(&settings).unwrap();
    oo().args(["init", "--agent", "claude-code"])
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .env_remove("OO_CLAUDE_DIR")
        .assert()
        .success();
    let after = std::fs::read_to_string(&settings).unwrap();
    assert_eq!(before, after, "idempotent re-run must not change the file");
    let v: serde_json::Value = serde_json::from_str(&after).unwrap();
    assert_eq!(
        count_oo_hook_entries(&v),
        1,
        "exactly one oo hook entry after re-run"
    );
}

/// `oo init --agent claude-code --global` writes under the env-overridden
/// `OO_CLAUDE_DIR` (the final settings directory), never under the git root.
#[test]
fn test_init_agent_claude_code_global_writes_under_override() {
    let override_dir = TempDir::new().unwrap();
    let repo = TempDir::new().unwrap();
    std::fs::create_dir_all(repo.path().join(".git")).unwrap();
    oo().args(["init", "--agent", "claude-code", "--global"])
        .current_dir(repo.path())
        .env("HOME", repo.path())
        .env("OO_CLAUDE_DIR", override_dir.path())
        .assert()
        .success();

    let settings = override_dir.path().join("settings.json");
    assert!(
        settings.exists(),
        "global settings.json must land at $OO_CLAUDE_DIR/settings.json"
    );
    // The project (git) root must NOT have received the file.
    let project_settings = repo.path().join(".claude").join("settings.json");
    assert!(
        !project_settings.exists(),
        "global install must not write under the git root"
    );
}

/// A malformed existing settings.json is NOT overwritten — the command errors
/// and the file is left intact.
#[test]
fn test_init_agent_claude_code_malformed_existing_errors() {
    let dir = TempDir::new().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();
    let claude_dir = dir.path().join(".claude");
    std::fs::create_dir_all(&claude_dir).unwrap();
    let settings = claude_dir.join("settings.json");
    let corrupt = "{\"hooks\": {";
    std::fs::write(&settings, corrupt).unwrap();

    oo().args(["init", "--agent", "claude-code"])
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .env_remove("OO_CLAUDE_DIR")
        .assert()
        .failure()
        .stderr(predicate::str::contains("not valid JSON"));

    assert_eq!(
        std::fs::read_to_string(&settings).unwrap(),
        corrupt,
        "malformed settings.json must not be overwritten"
    );
}

/// Unknown agent values error naming the supported values.
#[test]
fn test_init_agent_unknown_value_errors() {
    let dir = TempDir::new().unwrap();
    oo().args(["init", "--agent", "cursor"])
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .assert()
        .failure()
        .stderr(predicate::str::contains("unknown --agent value 'cursor'"))
        .stderr(predicate::str::contains("pi, claude-code"));
}

// ---------------------------------------------------------------------------
// oo hook claude (stdin-JSON PreToolUse processor)
// ---------------------------------------------------------------------------

/// `oo hook claude` rewrites a Bash command that has an oo pattern, printing
/// hookSpecificOutput JSON with the rewritten command and exit 0.
#[test]
fn test_hook_claude_rewrites_bash_command() {
    let stdin = "{\"tool_name\":\"Bash\",\"tool_input\":{\"command\":\"cargo test --release\"}}";
    let dir = TempDir::new().unwrap();
    let out = oo()
        .args(["hook", "claude"])
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .write_stdin(stdin)
        .output()
        .unwrap();
    assert!(out.status.success(), "oo hook claude must exit 0");
    let stdout = String::from_utf8_lossy(&out.stdout);
    let v: serde_json::Value =
        serde_json::from_str(stdout.trim()).expect("hook output must be valid JSON: {stdout}");
    assert_eq!(v["hookSpecificOutput"]["hookEventName"], "PreToolUse");
    assert!(
        v["hookSpecificOutput"]["updatedInput"]["command"]
            .as_str()
            .unwrap()
            .starts_with("oo cargo test")
    );
}

/// A Bash command with no matching pattern prints nothing and exits 0.
#[test]
fn test_hook_claude_no_rewrite_is_quiet_exit_zero() {
    let stdin = "{\"tool_name\":\"Bash\",\"tool_input\":{\"command\":\"cat file.txt\"}}";
    let dir = TempDir::new().unwrap();
    let out = oo()
        .args(["hook", "claude"])
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .write_stdin(stdin)
        .output()
        .unwrap();
    assert!(out.status.success());
    assert!(out.stdout.is_empty(), "no rewrite -> empty stdout");
}

/// A non-Bash tool prints nothing and exits 0.
#[test]
fn test_hook_claude_non_bash_is_quiet() {
    let stdin = "{\"tool_name\":\"Read\",\"tool_input\":{\"command\":\"cargo test\"}}";
    let dir = TempDir::new().unwrap();
    let out = oo()
        .args(["hook", "claude"])
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .write_stdin(stdin)
        .output()
        .unwrap();
    assert!(out.status.success());
    assert!(out.stdout.is_empty());
}

/// Invalid / empty stdin prints nothing and exits 0 (fail-open).
#[test]
fn test_hook_claude_invalid_json_is_quiet_exit_zero() {
    for stdin in [r#"{"tool_name":"Bash","#, "", "not json"] {
        let dir = TempDir::new().unwrap();
        let out = oo()
            .args(["hook", "claude"])
            .current_dir(dir.path())
            .env("HOME", dir.path())
            .write_stdin(stdin)
            .output()
            .unwrap();
        assert!(out.status.success(), "must exit 0 for stdin {stdin:?}");
        assert!(
            out.stdout.is_empty(),
            "must print nothing for stdin {stdin:?}"
        );
    }
}

/// OO_DISABLE=1 makes the hook a hard pass-through (empty stdout, exit 0).
#[test]
fn test_hook_claude_oo_disable_is_passthrough() {
    let stdin = "{\"tool_name\":\"Bash\",\"tool_input\":{\"command\":\"cargo test\"}}";
    let dir = TempDir::new().unwrap();
    let out = oo()
        .args(["hook", "claude"])
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .env("OO_DISABLE", "1")
        .write_stdin(stdin)
        .output()
        .unwrap();
    assert!(out.status.success());
    assert!(out.stdout.is_empty(), "OO_DISABLE=1 must not rewrite");
}

/// The hook preserves other tool_input fields (description, timeout) in
/// updatedInput.
#[test]
fn test_hook_claude_preserves_tool_input_fields() {
    let stdin = "{\"tool_name\":\"Bash\",\"tool_input\":{\"command\":\"cargo test\",\"description\":\"view history\",\"timeout\":12000}}";
    let dir = TempDir::new().unwrap();
    let out = oo()
        .args(["hook", "claude"])
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .write_stdin(stdin)
        .output()
        .unwrap();
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap();
    let updated = &v["hookSpecificOutput"]["updatedInput"];
    assert_eq!(updated["description"], "view history");
    assert_eq!(updated["timeout"], 12000);
}

/// `--agent pi` combined with `--format` is a mutual-exclusion error
/// (issue #171, operator decision 1): stderr carries the exact message, exit
/// is non-zero, and NOTHING is written — neither the pi extension nor the
/// Claude hooks file.
#[test]
fn test_init_agent_and_format_is_error_and_writes_nothing() {
    let dir = TempDir::new().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();
    oo().args(["init", "--agent", "pi", "--format", "claude"])
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .env_remove("OO_PI_EXTENSIONS_DIR")
        .assert()
        .failure()
        .stderr(predicate::str::contains(
            "--agent and --format cannot be used together",
        ));

    let pi_ext = dir.path().join(".pi").join("extensions").join("oo.ts");
    let claude_hooks = dir.path().join(".claude").join("hooks.json");
    assert!(
        !pi_ext.exists(),
        "--agent path must not be written on the error"
    );
    assert!(
        !claude_hooks.exists(),
        "--format path must not be written on the error"
    );
}

/// Backward-compat: plain `oo init` still writes `.claude/hooks.json`
/// byte-identical to the embedded constant, with a temp HOME (defensive).
#[test]
fn test_init_plain_still_writes_claude_hooks_json() {
    let dir = TempDir::new().unwrap();
    oo().arg("init")
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .assert()
        .success();

    let hooks_path = dir.path().join(".claude").join("hooks.json");
    assert!(
        hooks_path.exists(),
        "plain oo init must still create .claude/hooks.json"
    );
    let content = std::fs::read_to_string(&hooks_path).unwrap();
    let parsed: serde_json::Value =
        serde_json::from_str(&content).expect("hooks.json must be valid JSON");
    assert!(parsed.get("hooks").is_some());
}

/// The no-args help surface still lists `init` and points at its full usage
/// (the flag matrix lives in `oo init --help`, not in the top-level help).
#[test]
fn test_help_lists_init_with_agent_option() {
    oo().assert()
        .success()
        .stdout(predicate::str::contains("init"))
        .stdout(predicate::str::contains(
            "--agent pi|claude-code [--global]",
        ))
        .stdout(predicate::str::contains("oo init --help"));
}

// ---------------------------------------------------------------------------
// recall command
// ---------------------------------------------------------------------------

#[test]
fn test_recall_no_args() {
    // `oo recall` with no query should fail with a helpful error
    oo().arg("recall")
        .assert()
        .failure()
        .stderr(predicate::str::contains("recall requires a query"));
}

#[test]
fn test_recall_no_results() {
    // A query that matches nothing should exit 0 and mention no results
    oo().args(["recall", "xyzzy_nonexistent_query_12345"])
        .assert()
        .success()
        .stdout(predicate::str::contains("No results found"));
}

// ---------------------------------------------------------------------------
// recall — snippet (bounded default) and --full integration tests
// ---------------------------------------------------------------------------
//
// These tests use OO_DATA_DIR to isolate the store so they don't touch the
// developer's real data-directory oo.db (or vice versa).
// ---------------------------------------------------------------------------

/// Seed a large indexed blob and return (temp_dir, blob_content).
///
/// The blob is > 4 KB so it hits the Large tier (● indexed indicator).
fn index_large_blob() -> (TempDir, String) {
    let dir = TempDir::new().unwrap();
    let blob: String = (0..200)
        .map(|i| {
            format!(
                "sentinel_line_{i:04} data_padding_abcdef_{}\n",
                "x".repeat(50)
            )
        })
        .collect();
    // ~ 200 * 85 = 17 KB — well above 4 KB threshold

    // OO_DATA_DIR isolates the store for this test run
    // `oo <cmd>` where cmd produces >4KB output → Large tier → indexed
    let blob_file = dir.path().join("blob.txt");
    std::fs::write(&blob_file, &blob).unwrap();

    // Use `cat` to produce large output (cat is Data category → Large tier)
    let mut cmd = oo();
    cmd.args(["cat", blob_file.to_str().unwrap()]);
    cmd.env("OO_DATA_DIR", dir.path());
    cmd.assert().success();

    (dir, blob)
}

#[test]
fn test_recall_default_is_bounded() {
    // Index a large blob, recall it — default output must be bounded
    let (dir, blob) = index_large_blob();

    // Recall with a token that appears in the blob
    let mut cmd = oo();
    cmd.args(["recall", "sentinel_line_0100"]);
    cmd.env("OO_DATA_DIR", dir.path());
    let output = cmd.output().unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(output.status.success(), "recall must exit 0");

    // The stdout must be bounded: well under the full blob size
    let stdout_len = stdout.len();
    let blob_len = blob.len();
    assert!(
        stdout_len < blob_len,
        "default recall stdout ({stdout_len} B) must be < full blob ({blob_len} B)"
    );

    // The output must not be empty (results were found)
    assert!(
        !stdout.trim().is_empty(),
        "default recall must produce output"
    );

    // The output should NOT contain the tail of the blob (last 100 chars)
    let blob_tail = &blob[blob.len().saturating_sub(100)..];
    assert!(
        !stdout.contains(blob_tail),
        "default recall must NOT contain the tail of the blob (bounded display)"
    );
}

#[test]
fn test_recall_full_shows_complete_blob() {
    // --full must show the complete stored content
    let (dir, _blob) = index_large_blob();

    let mut cmd = oo();
    cmd.args(["recall", "--full", "sentinel_line_0100"]);
    cmd.env("OO_DATA_DIR", dir.path());
    let output = cmd.output().unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(output.status.success(), "recall must exit 0");

    // The full blob content must appear (at least the last sentinel line)
    assert!(
        stdout.contains("sentinel_line_0199"),
        "--full recall must contain the last sentinel line of the blob"
    );
}

#[test]
fn test_recall_full_flag_position_independent() {
    // Both `oo recall --full <q>` and `oo recall <q> --full` must work
    let (dir, _blob) = index_large_blob();

    // Flag before query
    let mut cmd1 = oo();
    cmd1.args(["recall", "--full", "sentinel_line_0100"]);
    cmd1.env("OO_DATA_DIR", dir.path());
    let out1 = cmd1.output().unwrap();
    assert!(out1.status.success(), "flag-before must be --full mode");

    // Flag after query
    let mut cmd2 = oo();
    cmd2.args(["recall", "sentinel_line_0100", "--full"]);
    cmd2.env("OO_DATA_DIR", dir.path());
    let out2 = cmd2.output().unwrap();
    assert!(out2.status.success(), "flag-after must be --full mode");

    // Both must contain the last sentinel (proves --full mode)
    let stdout1 = String::from_utf8_lossy(&out1.stdout);
    let stdout2 = String::from_utf8_lossy(&out2.stdout);
    assert!(
        stdout1.contains("sentinel_line_0199"),
        "flag-before must be --full mode"
    );
    assert!(
        stdout2.contains("sentinel_line_0199"),
        "flag-after must be --full mode"
    );
}

#[test]
fn test_recall_full_alone_gives_empty_query_error() {
    // `oo recall --full` alone → empty query → error exit 1
    oo().args(["recall", "--full"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("recall requires a query"));
}

#[test]
fn test_recall_default_displays_fts_snippet_not_content_prefix() {
    // Guard for the whole FTS5 snippet feature: the default (non-`--full`)
    // recall output must contain the matched sentinel token — proving the
    // store-provided FTS5 snippet (centered on the best match) is what gets
    // displayed. If the wiring is removed and `cmd_recall` falls back to
    // `bounded_display(&r.content)` (the first ~512 chars of the full blob),
    // the sentinel token — placed well beyond the first 512 chars — will be
    // absent and this test will fail.
    let dir = TempDir::new().unwrap();
    // Build a blob whose first 512 chars contain NO occurrence of the matched
    // token: 150 filler tokens (1350 chars) before the sentinel.
    let filler: String = (0..500).map(|i| format!("filler{i:04}_ ")).collect(); // 500*11 = 5500 chars of filler
    let blob: String = format!("{filler}sentinel_beta_9999 {filler}"); // ~11000 chars total (well above 4 KB → Bounded/Large tier)
    let blob_file = dir.path().join("blob.txt");
    std::fs::write(&blob_file, &blob).unwrap();

    let mut cmd = oo();
    cmd.args(["cat", blob_file.to_str().unwrap()]);
    cmd.env("OO_DATA_DIR", dir.path());
    cmd.assert().success();

    // Default (bounded) recall for a token that appears only in the middle of
    // the blob — never in the first 512 chars.
    let mut cmd = oo();
    cmd.args(["recall", "sentinel_beta_9999"]);
    cmd.env("OO_DATA_DIR", dir.path());
    let output = cmd.output().unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(output.status.success(), "recall must exit 0");

    // The matched sentinel must be shown: an FTS5 snippet centered on the
    // match contains it; `bounded_display(&content)` (first ~512 chars, all
    // filler) does not. The blob is ~11 000 chars (well above 4 KB) so `oo cat`
    // indexes the full content and the FTS5 branch is exercised.
    assert!(
        stdout.contains("sentinel_beta_9999"),
        "default recall must display the FTS5 snippet centered on the matched token\ngot: {stdout}"
    );

    // Sanity: the output is bounded (not the full blob).
    let stdout_len = stdout.len();
    let blob_len = blob.len();
    assert!(
        stdout_len < blob_len,
        "default recall stdout ({stdout_len} B) must be < full blob ({blob_len} B)"
    );
}

// ---------------------------------------------------------------------------
// learn command
// ---------------------------------------------------------------------------

#[test]
fn test_learn_no_args() {
    // `oo learn` with no command should fail with a helpful error
    oo().arg("learn")
        .assert()
        .failure()
        .stderr(predicate::str::contains("learn requires a command"));
}

#[test]
fn test_learn_no_api_key() {
    // `oo learn echo hello` spawns a background child that checks the API key.
    // The foreground process always exits 0 (it just runs the command and detaches).
    // What we can verify: stderr mentions the learning intent for the command.
    oo().args(["learn", "echo", "hello"])
        .env_remove("ANTHROPIC_API_KEY")
        .env_remove("OPENAI_API_KEY")
        .assert()
        .success()
        .stderr(predicate::str::contains("[learning pattern for"));
}

// ---------------------------------------------------------------------------
// run command edge cases
// ---------------------------------------------------------------------------

#[test]
fn test_run_command_not_found() {
    // A command that doesn't exist should result in a failure indicator or error
    oo().args(["nonexistent_binary_xyz_abc_123"])
        .assert()
        .failure();
}

#[test]
fn test_run_multiword_command() {
    // Multiple args are passed through correctly
    oo().args(["echo", "hello", "world"])
        .assert()
        .success()
        .stdout(predicate::str::contains("hello world"));
}

#[test]
fn test_passthrough_git_version() {
    // `git --version` produces small output (< 4096 bytes) and exits 0.
    // oo must pass it through verbatim — no ✓ or ● prefix.
    // This tests the passthrough classification tier end-to-end.
    oo().args(["git", "--version"])
        .assert()
        .success()
        .stdout(predicate::str::starts_with("git version"));
}

#[test]
fn test_failure_stderr_output() {
    // `ls /nonexistent_path_xyz` should exit non-zero and show ✗ with stderr content
    oo().args(["ls", "/nonexistent_path_xyz_abc_12345"])
        .assert()
        .failure()
        .stdout(predicate::str::starts_with("\u{2717}")); // ✗
}

// ---------------------------------------------------------------------------
// parse_action dispatch (CLI integration)
// ---------------------------------------------------------------------------

#[test]
fn test_dispatch_version() {
    // `oo version` must exit 0
    oo().arg("version").assert().success();
}

#[test]
fn test_dispatch_forget() {
    // `oo forget` must exit 0 and clear project data.
    // OO_DATA_DIR isolates the store so the project-scoped delete (issue
    // #168) never wipes the developer's real index.
    let dir = TempDir::new().unwrap();
    oo().arg("forget")
        .env("OO_DATA_DIR", dir.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("Cleared project data"));
}

#[test]
fn test_dispatch_run() {
    // `oo echo hi` dispatches to run — exits 0 with command output
    oo().args(["echo", "hi"])
        .assert()
        .success()
        .stdout(predicate::str::contains("hi"));
}

#[test]
fn test_dispatch_recall_query_joined() {
    // `oo recall hello world` — multi-word query joined, exits 0
    oo().args(["recall", "hello", "world"]).assert().success();
}

#[test]
fn test_dispatch_help() {
    // `oo help` — shows usage
    oo().arg("help")
        .assert()
        .success()
        .stdout(predicate::str::contains("Usage"));
}

#[test]
fn test_dispatch_init() {
    // `oo init` — runs the init command (tested more fully in init block above)
    let dir = TempDir::new().unwrap();
    oo().arg("init").current_dir(dir.path()).assert().success();
}

// ---------------------------------------------------------------------------
// oo patterns subcommand
// ---------------------------------------------------------------------------

#[test]
fn test_patterns_no_learned_patterns() {
    // When no learned patterns exist, built-in patterns are still shown
    let dir = TempDir::new().unwrap();
    oo().arg("patterns")
        .env("HOME", dir.path())
        .env("XDG_CONFIG_HOME", dir.path().join(".config"))
        .assert()
        .success()
        .stdout(predicate::str::contains("Built-in"))
        .stdout(predicate::str::contains("User"));
}

#[test]
fn test_patterns_with_learned_pattern() {
    // When a valid pattern file exists, list it.
    // Use double_o::learn::patterns_dir() to resolve the platform-correct path
    // (macOS: ~/Library/Application Support/oo/patterns, Linux: ~/.config/oo/patterns).
    let dir = TempDir::new().unwrap();
    // Build the platform-appropriate path under our temp HOME by temporarily
    // setting HOME and querying dirs::config_dir equivalent logic.
    // We know patterns_dir() = dirs::config_dir()/oo/patterns, so replicate that.
    #[cfg(target_os = "macos")]
    let patterns_dir = dir
        .path()
        .join("Library")
        .join("Application Support")
        .join("oo")
        .join("patterns");
    #[cfg(not(target_os = "macos"))]
    let patterns_dir = dir.path().join(".config").join("oo").join("patterns");

    std::fs::create_dir_all(&patterns_dir).unwrap();
    std::fs::write(
        patterns_dir.join("pytest.toml"),
        "command_match = \"^pytest\"\n[success]\npattern = '(?P<n>\\d+) passed'\nsummary = \"{n} passed\"\n",
    )
    .unwrap();
    oo().arg("patterns")
        .env("HOME", dir.path())
        .env("XDG_CONFIG_HOME", dir.path().join(".config"))
        .assert()
        .success()
        .stdout(predicate::str::contains("^pytest"));
}

#[test]
fn test_learn_provider_logged_to_stderr() {
    // Part 1: provider name must appear in stderr before background spawn
    oo().args(["learn", "echo", "hello"])
        .env_remove("ANTHROPIC_API_KEY")
        .env_remove("OPENAI_API_KEY")
        .env_remove("CEREBRAS_API_KEY")
        .assert()
        .success()
        .stderr(predicate::str::contains("anthropic"));
}

// ---------------------------------------------------------------------------
// version / format tests
// ---------------------------------------------------------------------------

#[test]
fn test_version_shows_oo_prefix() {
    // The plain "oo" logo must appear in the version output
    oo().arg("version")
        .assert()
        .success()
        .stdout(predicate::str::starts_with("oo "));
}

#[test]
fn test_version_shows_version_number() {
    // Must contain the version from Cargo.toml
    let version = env!("CARGO_PKG_VERSION");
    oo().arg("version")
        .assert()
        .success()
        .stdout(predicate::str::contains(version));
}

// ---------------------------------------------------------------------------
// help command integration
// ---------------------------------------------------------------------------

/// Network-dependent: looks up cheat.sh for `ls`.
/// Marked ignore — run manually when network is available.
#[test]
#[ignore = "requires network access to cheat.sh"]
fn test_help_with_valid_command() {
    oo().args(["help", "ls"])
        .assert()
        .success()
        .stdout(predicate::str::is_empty().not());
}

// ---------------------------------------------------------------------------
// Large Content/Unknown passthrough repros (issue #148)
//
// These are the exact live repros from the ticket: pre-fix, `oo cat` on a
// 110KB file emitted exactly 110,000 bytes and a 30,000-echo `sh -c` emitted
// exactly 150,000 bytes verbatim into the agent's context. Each test
// self-isolates its store via OO_DATA_DIR (fresh temp dir per test) so the
// recall assertions only see the row this test indexed.
//
// The recall assertions deliberately check RETRIEVABILITY ONLY — a distinctive
// marker token embedded in the tail of the original output must return a
// NON-EMPTY recall result whose stored content contains the token. They must
// NOT assert on the shape/boundedness of `oo recall`'s printed output; that is
// issue #147's job.
// ---------------------------------------------------------------------------

/// A single, unambiguous FTS5 token — guaranteed to be a one-token query that
/// the store's per-row phrase matching can resolve (no punctuation, no spaces).
const RECALL_MARKER: &str = "oo148tailmarker7f3a9c";

/// Build a 110,000-byte file whose contents are all distinct 22-character
/// lines (positions 0..5000), each containing the RECALL_MARKER token. The
/// file is large enough to trigger the >4KB threshold, and the marker is
/// guaranteed to be a single FTS5 token in the indexed row. The file's tail
/// (last 5000 lines) also contains the marker, so it survives the
/// byte-based head+tail truncation (tail budget = 40% of 4096 ≈ 1638 bytes ≈
/// ~74 lines of 22-char lines, well within the last 5000 lines).
fn write_repro_file(dir: &std::path::Path) -> std::path::PathBuf {
    let mut content = String::new();
    for i in 0..5000 {
        content.push_str(&format!("line{i:06} {RECALL_MARKER}\n"));
    }
    let path = dir.join("big.txt");
    std::fs::write(&path, &content).unwrap();
    path
}

/// Isolate the store under a fresh temp data dir. Returns the TempDir (kept
/// alive for the duration of the test) and the data-dir path to pass to
/// OO_DATA_DIR on every oo invocation in the test.
fn isolated_store() -> (TempDir, std::path::PathBuf) {
    let dir = TempDir::new().unwrap();
    let data_dir = dir.path().join("oo-data");
    std::fs::create_dir_all(&data_dir).unwrap();
    (dir, data_dir)
}

/// Run `oo recall <marker>` against the isolated store and assert the result is
/// non-empty AND contains the marker token. Returns the recall stdout for the
/// caller to inspect if needed.
fn assert_recall_contains(data_dir: &std::path::Path, marker: &str) {
    let out = oo()
        .args(["recall", marker])
        .env("OO_DATA_DIR", data_dir)
        .assert()
        .success()
        .to_string();
    assert!(
        !out.contains("No results found"),
        "recall on the tail marker must return a non-empty result; got: {out:?}"
    );
    assert!(
        out.contains(marker),
        "recall result must contain the tail marker token; got: {out:?}"
    );
}

#[test]
fn test_content_arm_large_output_bounded_and_recallable() {
    // Repro A (Content arm): `oo cat` on a 110,000-byte file. Pre-fix this
    // emitted exactly 110,000 bytes verbatim. Post-fix: stdout must be bounded
    // far under the full size, the full content must be indexed, and a recall
    // seeded with the tail marker must return a non-empty result containing it.
    let file = TempDir::new().unwrap();
    let big = write_repro_file(file.path());

    let (_guard, data_dir) = isolated_store();
    oo().args(["cat", big.to_str().unwrap()])
        .env("OO_DATA_DIR", &data_dir)
        .assert()
        .success()
        // The pre-fix byte-exact 110,000-byte dump is the bug: bound well under it.
        // The fix caps display at 4096 bytes + one marker line; 20KB leaves a wide
        // margin over that while still being provably not the verbatim 110KB dump.
        .stdout(predicate::function(|out: &str| out.len() < 20_000))
        .stdout(predicate::str::contains(RECALL_MARKER));

    // The full content must have been indexed — recall on the tail marker
    // returns a NON-EMPTY result whose stored content contains the token.
    assert_recall_contains(&data_dir, RECALL_MARKER);
}

#[test]
fn test_unknown_arm_large_output_bounded_and_recallable() {
    // Repro B (Unknown arm): `oo sh -c '<30000 lines> + <marker line>'`.
    // Pre-fix this emitted ~150,000 bytes verbatim (30,000 x "line\n").
    // The shell loop runs first, then the marker line is appended, so the
    // marker sits in the TAIL of the output — the slice that must survive the
    // byte-based head+tail truncation to be displayed, and the whole output
    // (including the marker) is what gets indexed for recall.
    let (_guard, data_dir) = isolated_store();
    oo().args([
        "sh",
        "-c",
        &format!("for i in $(seq 1 30000); do echo line; done; echo {RECALL_MARKER}"),
    ])
    .env("OO_DATA_DIR", &data_dir)
    .assert()
    .success()
    .stdout(predicate::function(|out: &str| out.len() < 20_000))
    .stdout(predicate::str::contains(RECALL_MARKER));

    assert_recall_contains(&data_dir, RECALL_MARKER);
}

#[test]
fn test_forget_removes_everything_recallable() {
    // Issue #168: `oo forget` must remove exactly what `oo recall` can
    // return for the project. Seed a marker via a real invocation, run
    // `oo forget`, then `oo recall` must find nothing.
    let file = TempDir::new().unwrap();
    let big = write_repro_file(file.path());

    let (_guard, data_dir) = isolated_store();
    oo().args(["cat", big.to_str().unwrap()])
        .env("OO_DATA_DIR", &data_dir)
        .assert()
        .success();

    // Sanity: the marker is recallable before forget.
    assert_recall_contains(&data_dir, RECALL_MARKER);

    oo().arg("forget")
        .env("OO_DATA_DIR", &data_dir)
        .assert()
        .success()
        .stdout(predicate::str::contains("Cleared project data"));

    // After forget, recall must return nothing.
    oo().args(["recall", RECALL_MARKER])
        .env("OO_DATA_DIR", &data_dir)
        .assert()
        .success()
        .stdout(predicate::str::contains("No results found"));
}

// ---------------------------------------------------------------------------
// cargo-dist configuration verification
// ---------------------------------------------------------------------------

#[test]
fn test_cargo_toml_has_shell_installer_enabled() {
    // Verify that Cargo.toml configures shell installer for cargo-dist
    let cargo_toml = include_str!("../Cargo.toml");
    assert!(
        cargo_toml.contains(r#"installers = ["shell"]"#),
        "Cargo.toml must have shell installer enabled: installers = [\"shell\"]"
    );
}

#[test]
fn test_cargo_toml_has_install_path_cargo_home() {
    // Verify that Cargo.toml configures install-path as CARGO_HOME
    let cargo_toml = include_str!("../Cargo.toml");
    assert!(
        cargo_toml.contains(r#"install-path = "CARGO_HOME""#),
        "Cargo.toml must have install-path = \"CARGO_HOME\""
    );
}

#[test]
fn test_cargo_toml_has_cargo_dist_version() {
    // Verify that Cargo.toml specifies a cargo-dist version
    let cargo_toml = include_str!("../Cargo.toml");
    assert!(
        cargo_toml.contains("cargo-dist-version ="),
        "Cargo.toml must specify cargo-dist-version for dist config"
    );
}

// ---------------------------------------------------------------------------
// project patterns (.oo/patterns)
// ---------------------------------------------------------------------------

#[test]
fn test_project_patterns_listed_when_present() {
    let dir = TempDir::new().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();
    let pat_dir = dir.path().join(".oo").join("patterns");
    std::fs::create_dir_all(&pat_dir).unwrap();
    std::fs::write(
        pat_dir.join("mytest.toml"),
        "command_match = \"^mytest\"\n[success]\npattern = '(?P<n>\\d+) ok'\nsummary = \"{n} ok\"\n",
    )
    .unwrap();

    oo().arg("patterns")
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .env("XDG_CONFIG_HOME", dir.path().join(".config"))
        .assert()
        .success()
        .stdout(predicate::str::contains("Project"))
        .stdout(predicate::str::contains("^mytest"));
}

#[test]
fn test_project_patterns_override_builtins() {
    // Create a project pattern for "echo" with a success pattern that matches
    // the output, proving project patterns are loaded and take effect.
    let dir = TempDir::new().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();
    let pat_dir = dir.path().join(".oo").join("patterns");
    std::fs::create_dir_all(&pat_dir).unwrap();

    // A pattern that matches "echo" and summarises any output as "proj-match"
    std::fs::write(
        pat_dir.join("echo.toml"),
        "command_match = \"^echo\\\\b\"\n[success]\npattern = '(?s)(?P<all>.+)'\nsummary = \"proj-match\"\n",
    )
    .unwrap();

    // Generate enough output to exceed SMALL_THRESHOLD so the pattern is consulted.
    // SMALL_THRESHOLD is 4096 bytes; we need > 4096 bytes of output.
    let big_arg = "x".repeat(5000);
    oo().args(["echo", &big_arg])
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .env("XDG_CONFIG_HOME", dir.path().join(".config"))
        .assert()
        .success()
        .stdout(predicate::str::contains("proj-match"));
}

// ---------------------------------------------------------------------------
// oo rewrite (#170)
// ---------------------------------------------------------------------------

#[test]
fn test_rewrite_builtin_pattern_prints_and_exits_zero() {
    oo().args(["rewrite", "pytest -q"])
        .assert()
        .success()
        .stdout("oo pytest -q\n");
}

#[test]
fn test_rewrite_multi_segment_only_matching_segment_rewritten() {
    oo().args(["rewrite", "cd src && cargo build"])
        .assert()
        .success()
        .stdout("cd src && oo cargo build\n");
}

#[test]
fn test_rewrite_multibyte_before_separator_does_not_panic() {
    // A multi-byte char before a separator: char-index byte slicing would
    // land mid-codepoint and panic.
    oo().args(["rewrite", "é && pytest -q"])
        .assert()
        .success()
        .stdout("é && oo pytest -q\n");
}

#[test]
fn test_rewrite_no_pattern_exits_one_no_output() {
    oo().args(["rewrite", "git log --stat"])
        .assert()
        .code(1)
        .stdout("");
}

#[test]
fn test_rewrite_pipe_not_rewritten() {
    oo().args(["rewrite", "cargo test | tee out.txt"])
        .assert()
        .code(1)
        .stdout("");
}

#[test]
fn test_rewrite_empty_arg_exits_one_no_output() {
    oo().args(["rewrite", ""]).assert().code(1).stdout("");
}

#[test]
fn test_rewrite_no_arg_exits_one_no_output() {
    oo().arg("rewrite").assert().code(1).stdout("");
}

#[test]
fn test_rewrite_does_not_execute_command() {
    // A fake command with no pattern: if rewrite ever executed the command,
    // the failure indicator or output would appear. None may appear.
    let (keep, path) = make_fake_bin(
        "oo_rewrite_noop_xyz",
        "#!/bin/sh\necho SHOULD_NOT_APPEAR\nexit 7\n",
    );
    let _ = keep;
    oo().args(["rewrite", "oo_rewrite_noop_xyz"])
        .env("PATH", path)
        .assert()
        .code(1)
        .stdout(predicate::str::contains("SHOULD_NOT_APPEAR").not());
}

#[test]
fn test_rewrite_project_pattern_drives_rewrite() {
    // A project-local pattern for a non-builtin command must drive the
    // rewrite through the same load path as `oo <cmd>`.
    let dir = TempDir::new().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();
    let pat_dir = dir.path().join(".oo").join("patterns");
    std::fs::create_dir_all(&pat_dir).unwrap();
    std::fs::write(pat_dir.join("mytool.toml"), "command_match = \"^mytool\"\n").unwrap();

    oo().args(["rewrite", "mytool --fast"])
        .current_dir(dir.path())
        .env("HOME", dir.path())
        .env("XDG_CONFIG_HOME", dir.path().join(".config"))
        .assert()
        .success()
        .stdout("oo mytool --fast\n");
}

// ---------------------------------------------------------------------------
// Savings suffix (issue #150)
// ---------------------------------------------------------------------------

/// Create a temp bin dir containing an executable script named `name` whose
/// body is `script_body`, and return the PATH with that dir prepended.
fn make_fake_bin(name: &str, script_body: &str) -> (TempDir, String) {
    let dir = TempDir::new().unwrap();
    let bin_dir = dir.path().join("bin");
    std::fs::create_dir_all(&bin_dir).unwrap();
    let bin = bin_dir.join(name);
    std::fs::write(&bin, script_body).unwrap();
    std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    (dir, path)
}

/// Quiet Success: a Status-category command with >4 KB output and no matching
/// builtin success pattern produces `✓ {label}` (empty summary). The
/// `[saved …]` suffix must appear on the indicator line.
#[test]
fn test_quiet_success_shows_savings() {
    let (keep, path) = make_fake_bin(
        "go",
        "#!/bin/sh\nfor i in $(seq 1 500); do echo 'building component $i ...'; done\nexit 0\n",
    );
    let _ = keep;
    oo().args(["go", "build"])
        .env("PATH", path)
        .assert()
        .success()
        .stdout(predicate::str::starts_with("\u{2713}"))
        .stdout(predicate::str::contains("[saved "))
        // The suffix must be on the indicator line, not on subsequent lines.
        .stdout(predicate::function(|out: &str| {
            let first_line = out.lines().next().unwrap_or("");
            first_line.starts_with('\u{2713}') && first_line.contains("[saved ")
        }));
}

/// Pattern-summarised Success: >4 KB output matching a builtin pattern with a
/// non-empty summary → `✓ {label} ({summary}) [saved …]`.
#[test]
fn test_summary_success_shows_savings() {
    let (keep, path) = make_fake_bin(
        "cargo",
        "#!/bin/sh\nfor i in $(seq 1 500); do echo \"running test $i ...\"; done\necho \"test result: ok. 42 passed; 0 failed; finished in 1.23s\"\nexit 0\n",
    );
    let _ = keep;
    oo().args(["cargo", "test"])
        .env("PATH", path)
        .assert()
        .success()
        .stdout(predicate::str::starts_with("\u{2713}"))
        .stdout(predicate::str::contains("42 passed"))
        .stdout(predicate::str::contains("[saved "))
        .stdout(predicate::function(|out: &str| {
            let first_line = out.lines().next().unwrap_or("");
            first_line.starts_with('\u{2713}') && first_line.contains("[saved ")
        }));
}

/// Filtered Failure: >4 KB output, non-zero exit. The `[saved …]` suffix must
/// appear on the `✗` indicator line; the filtered output lines that follow
/// must NOT contain the suffix.
#[test]
fn test_failure_shows_savings() {
    let (keep, path) = make_fake_bin(
        "pytest",
        "#!/bin/sh\nfor i in $(seq 1 500); do echo \"ERROR: test_failing_$i failed with assertion error\"; done\nexit 1\n",
    );
    let _ = keep;
    oo().args(["pytest", "-x"])
        .env("PATH", path)
        .assert()
        .failure()
        .stdout(predicate::str::starts_with("\u{2717}"))
        .stdout(predicate::str::contains("[saved "))
        .stdout(predicate::function(|out: &str| {
            let first_line = out.lines().next().unwrap_or("");
            first_line.starts_with('\u{2717}') && first_line.contains("[saved ")
        }));
}

/// REGRESSION LOCK — pre-existing failure formatting: the `✗ {label}`
/// indicator line is followed by a deliberate BLANK LINE before the error
/// body (the `\n` in the payload plus `println!`'s own newline). This must
/// survive both with and without a savings suffix present.
#[test]
fn test_failure_indicator_blank_line_with_suffix() {
    let (keep, path) = make_fake_bin(
        "pytest",
        "#!/bin/sh\nfor i in $(seq 1 500); do echo \"ERROR: test_failing_$i failed with assertion error\"; done\nexit 1\n",
    );
    let _ = keep;
    oo().args(["pytest", "-x"])
        .env("PATH", path)
        .assert()
        .failure()
        .stdout(predicate::function(|out: &str| {
            let mut lines = out.lines();
            let indicator = lines.next().unwrap_or("");
            let blank = lines.next().unwrap_or("");
            indicator.starts_with('\u{2717}') && indicator.contains("[saved ") && blank.is_empty()
        }));
}

/// Same regression as above for the small-failure case where the savings are
/// below `MIN_SAVINGS` and no suffix is printed: the blank line still holds.
#[test]
fn test_failure_indicator_blank_line_without_suffix() {
    oo().args(["false"])
        .assert()
        .failure()
        .stdout(predicate::function(|out: &str| {
            let mut lines = out.lines();
            let indicator = lines.next().unwrap_or("");
            let blank = lines.next().unwrap_or("");
            indicator.starts_with('\u{2717}') && !indicator.contains("[saved ") && blank.is_empty()
        }));
}

/// Large arm regression lock: the `● {label} (indexed … → use `oo recall` to
/// query)` string is unchanged — no `[saved …]` suffix (it already reports
/// its size; no double-reporting).
#[test]
fn test_large_arm_wording_unchanged_no_savings() {
    let dir = TempDir::new().unwrap();
    Command::new("git")
        .args(["init"])
        .current_dir(dir.path())
        .output()
        .unwrap();
    for i in 0..100 {
        std::fs::write(dir.path().join("file.txt"), format!("content {}\n", i)).unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(dir.path())
            .output()
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", &format!("commit {}", i)])
            .env("GIT_AUTHOR_NAME", "Test")
            .env("GIT_AUTHOR_EMAIL", "test@example.com")
            .env("GIT_COMMITTER_NAME", "Test")
            .env("GIT_COMMITTER_EMAIL", "test@example.com")
            .current_dir(dir.path())
            .output()
            .unwrap();
    }

    oo().args(["git", "log"])
        .current_dir(dir.path())
        .assert()
        .success()
        .stdout(predicate::str::starts_with("\u{25CF}"))
        .stdout(predicate::str::contains("indexed"))
        .stdout(predicate::str::contains("use `oo recall` to query"))
        .stdout(predicate::str::contains("[saved ").not());
}

/// Bounded arm regression lock: the `● {label} (output truncated: …)` line is
/// unchanged — no `[saved …]` suffix (its framing line already carries the
/// total size; no double-reporting).
#[test]
fn test_bounded_arm_wording_unchanged_no_savings() {
    let dir = TempDir::new().unwrap();
    let big_file = dir.path().join("big.txt");
    let content = std::iter::repeat("x\n").take(5000).collect::<String>();
    std::fs::write(&big_file, &content).unwrap();

    oo().args(["cat", big_file.to_str().unwrap()])
        .assert()
        .success()
        .stdout(predicate::str::starts_with("\u{25CF}"))
        .stdout(predicate::str::contains("output truncated:"))
        .stdout(predicate::str::contains("use `oo recall` to query"))
        .stdout(predicate::str::contains("[saved ").not());
}

/// Passthrough arm: small output (≤ 4 KiB, 4096 bytes) passes through verbatim with no
/// indicator line and no savings figure.
#[test]
fn test_passthrough_no_savings() {
    oo().args(["echo", "hello"])
        .assert()
        .success()
        .stdout("hello\n");
}

// ---------------------------------------------------------------------------
// clap --help / -h surface (issue #163, ws-clap-help)
//
// The doc-comment on the `args` field of the Cli derive in src/main.rs
// controls both surfaces — clap auto-wires -h from the same doc-comment.
// We assert on the two subcommands that were actually missing from the
// old doc-comment (init, patterns), plus one description phrase per
// subcommand, plus the tool description. `help`/`version` bare-word
// assertions are avoided — they match the Options section lines
// (`-h, --help` / `-V, --version`) and would be vacuous on this surface.
// ---------------------------------------------------------------------------

/// All 8 reserved subcommand names appear in `oo --help` output with a
/// one-line description alongside each. `init` and `patterns` are the two
/// names missing from the old doc-comment — those assertions are the ones
/// that would fail on the pre-fix binary.
#[test]
fn test_clap_help_lists_all_subcommands() {
    oo().arg("--help")
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Context-efficient command runner for AI coding agents",
        ))
        .stdout(predicate::str::contains("recall ("))
        .stdout(predicate::str::contains("forget ("))
        .stdout(predicate::str::contains("learn ("))
        .stdout(predicate::str::contains("help ("))
        .stdout(predicate::str::contains("init ("))
        .stdout(predicate::str::contains("patterns ("))
        .stdout(predicate::str::contains("hook ("))
        .stdout(predicate::str::contains("version ("));
}

/// Same assertions on the short-flag form — clap emits both from the same
/// doc-comment, so -h must not silently drift from --help.
#[test]
fn test_clap_short_help_lists_all_subcommands() {
    oo().arg("-h")
        .assert()
        .success()
        .stdout(predicate::str::contains("Context-efficient command runner"))
        .stdout(predicate::str::contains("recall ("))
        .stdout(predicate::str::contains("forget ("))
        .stdout(predicate::str::contains("learn ("))
        .stdout(predicate::str::contains("help ("))
        .stdout(predicate::str::contains("init ("))
        .stdout(predicate::str::contains("patterns ("))
        .stdout(predicate::str::contains("rewrite ("))
        .stdout(predicate::str::contains("hook ("))
        .stdout(predicate::str::contains("version ("));
}

// ---------------------------------------------------------------------------
// Failure tier recall (issue #185): failed-command output beyond the displayed
// slice must be indexed so `oo recall` can reach it.
// ---------------------------------------------------------------------------

const FAIL_MARKER: &str = "oo185hiddenmarker4c1d";

#[test]
fn test_failure_slice_dropped_lines_are_recallable() {
    // Marker sits at line 150 of 300: smart_truncate keeps head+tail only, so
    // the marker is absent from the displayed slice but present in the output.
    let script = format!(
        "#!/bin/sh\nfor i in $(seq 1 300); do if [ $i -eq 150 ]; then echo {FAIL_MARKER}; else echo \"line $i\"; fi; done\nexit 1\n"
    );
    let (_bin, path) = make_fake_bin("zfailtool", &script);
    let (_guard, data_dir) = isolated_store();

    let assert = oo()
        .args(["zfailtool"])
        .env("PATH", &path)
        .env("OO_DATA_DIR", &data_dir)
        .assert()
        .failure();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).to_string();
    assert!(
        !stdout.contains(FAIL_MARKER),
        "marker must be outside the displayed slice; got: {stdout:?}"
    );
    assert!(
        stdout.contains("use `oo recall` to query"),
        "recall must be advertised after the slice; got: {stdout:?}"
    );

    assert_recall_contains(&data_dir, FAIL_MARKER);
}

#[test]
fn test_failure_fully_displayed_is_not_indexed() {
    // 10 lines is below the truncation threshold: the slice equals the full
    // output, so nothing is indexed and recall is not advertised.
    let script =
        format!("#!/bin/sh\nfor i in $(seq 1 10); do echo \"{FAIL_MARKER} $i\"; done\nexit 1\n");
    let (_bin, path) = make_fake_bin("zfailtool", &script);
    let (_guard, data_dir) = isolated_store();

    let assert = oo()
        .args(["zfailtool"])
        .env("PATH", &path)
        .env("OO_DATA_DIR", &data_dir)
        .assert()
        .failure();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).to_string();
    assert!(
        !stdout.contains("oo recall"),
        "no recall advertisement for fully displayed output; got: {stdout:?}"
    );

    oo().args(["recall", FAIL_MARKER])
        .env("OO_DATA_DIR", &data_dir)
        .assert()
        .success()
        .stdout(predicate::str::contains("No results found"));
}

#[test]
fn test_failure_pattern_slice_showing_all_lines_is_not_indexed() {
    // `cargo test` has a built-in tail pattern. A 5-line failure fits inside
    // its window, so every line is shown; the slice has no trailing newline
    // and must still count as "nothing dropped". The second run uses CRLF
    // endings, which `lines()` also normalises.
    let lf = "#!/bin/sh\nprintf 'oo185fit1\\noo185fit2\\nl3\\nl4\\nl5\\n'\nexit 1\n";
    let crlf =
        "#!/bin/sh\nprintf 'oo185fit1\\r\\noo185fit2\\r\\nl3\\r\\nl4\\r\\nl5\\r\\n'\nexit 1\n";
    for script in [lf, crlf] {
        let (_bin, path) = make_fake_bin("cargo", script);
        let (_guard, data_dir) = isolated_store();

        let assert = oo()
            .args(["cargo", "test"])
            .env("PATH", &path)
            .env("OO_DATA_DIR", &data_dir)
            .assert()
            .failure();
        let stdout = String::from_utf8_lossy(&assert.get_output().stdout).to_string();
        assert!(
            stdout.contains("oo185fit2"),
            "shown lines must be displayed; got: {stdout:?}"
        );
        assert!(
            !stdout.contains("output truncated") && !stdout.contains("oo recall"),
            "fully shown failure must not advertise recall; got: {stdout:?}"
        );

        oo().args(["recall", "oo185fit1"])
            .env("OO_DATA_DIR", &data_dir)
            .assert()
            .success()
            .stdout(predicate::str::contains("No results found"));
    }
}

#[test]
fn test_failure_pattern_slice_with_trailing_empty_line_is_not_indexed() {
    // The tail pattern keeps the trailing empty line in its slice, so the
    // slice and the full output differ only by trailing empty lines: nothing
    // was dropped and recall must not be advertised.
    let script = "#!/bin/sh\nprintf 'oo185empty1\\noo185empty2\\nl3\\n\\n'\nexit 1\n";
    let (_bin, path) = make_fake_bin("cargo", script);
    let (_guard, data_dir) = isolated_store();

    let assert = oo()
        .args(["cargo", "test"])
        .env("PATH", &path)
        .env("OO_DATA_DIR", &data_dir)
        .assert()
        .failure();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).to_string();
    assert!(
        stdout.contains("oo185empty2"),
        "shown lines must be displayed; got: {stdout:?}"
    );
    assert!(
        !stdout.contains("output truncated") && !stdout.contains("oo recall"),
        "fully shown failure must not advertise recall; got: {stdout:?}"
    );
}

#[test]
fn test_failure_index_failure_warns_and_does_not_advertise_recall() {
    // OO_DATA_DIR pointing at a regular file makes the store unopenable.
    let script = "#!/bin/sh\nfor i in $(seq 1 300); do echo \"line $i\"; done\nexit 1\n";
    let (_bin, path) = make_fake_bin("zfailtool", script);
    let file_dir = TempDir::new().unwrap();
    let bogus = file_dir.path().join("not-a-dir");
    std::fs::write(&bogus, b"x").unwrap();

    let assert = oo()
        .args(["zfailtool"])
        .env("PATH", &path)
        .env("OO_DATA_DIR", &bogus)
        .assert()
        .failure();
    let output = assert.get_output();
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    assert!(
        stderr.contains("could not index output for recall"),
        "stderr must carry the index-failure warning; got: {stderr:?}"
    );
    assert!(
        stdout.contains("NOT indexed, recall unavailable"),
        "stdout must say recall is unavailable; got: {stdout:?}"
    );
    assert!(
        !stdout.contains("use `oo recall` to query"),
        "must not advertise recall when indexing failed; got: {stdout:?}"
    );
}