task-journal-cli 0.6.3

task-journal: CLI for append-only AI-coding task reasoning chains. Records hypotheses, decisions, rejections, evidence and renders compact resume packs.
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
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
use assert_cmd::Command;
use predicates::prelude::*;
use predicates::str::contains;

#[test]
fn pack_command_prints_markdown_for_existing_task() {
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "Pack me"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "compact"])
        .assert()
        .success()
        .stdout(contains("# Pack me"));
}

#[test]
fn event_command_appends_decision_visible_in_pack() {
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "T"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args([
            "event",
            &task_id,
            "--type",
            "decision",
            "--text",
            "Adopt Rust",
        ])
        .assert()
        .success();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "full"])
        .assert()
        .success()
        .stdout(contains("Adopt Rust"));
}

#[test]
fn close_command_marks_task_closed_in_pack() {
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "T"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["close", &task_id, "--reason", "shipped"])
        .assert()
        .success();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "full"])
        .assert()
        .success()
        .stdout(contains("status: closed"));
}

#[test]
fn doctor_exits_zero_on_fresh_install() {
    let dir = assert_fs::TempDir::new().unwrap();
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["doctor"])
        .assert()
        .success();
}

#[test]
fn doctor_json_output_is_parseable_and_lists_paths() {
    let dir = assert_fs::TempDir::new().unwrap();
    let output = Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["doctor", "--json"])
        .output()
        .unwrap();
    let stdout = String::from_utf8(output.stdout).unwrap();
    let v: serde_json::Value =
        serde_json::from_str(&stdout).expect("doctor --json must be valid JSON");

    assert!(v.get("data_dir").is_some());
    assert!(v.get("events_dir").is_some());
    assert!(v.get("state_dir").is_some());
    assert!(v.get("known_projects").unwrap().is_array());
    assert!(v.get("issues").unwrap().is_array());
}

fn write_pending(xdg: &std::path::Path, id: &str, text: &str, attempts: u32) {
    let dir = xdg.join("task-journal").join("pending");
    std::fs::create_dir_all(&dir).unwrap();
    let body = serde_json::json!({
        "text": text,
        "error": "test injection",
        "queued_at": "2026-05-07T00:00:00Z",
        "attempts": attempts,
    });
    std::fs::write(
        dir.join(format!("{id}.json")),
        serde_json::to_string_pretty(&body).unwrap(),
    )
    .unwrap();
}

#[test]
fn pending_list_shows_queued_entries() {
    let xdg = assert_fs::TempDir::new().unwrap();
    let proj = assert_fs::TempDir::new().unwrap();
    write_pending(xdg.path(), "tj-pending-1", "I think the cache is racy", 0);

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", xdg.path())
        .current_dir(proj.path())
        .args(["pending", "list"])
        .assert()
        .success()
        .stdout(contains("tj-pending-1"))
        .stdout(contains("I think the cache is racy"));
}

#[test]
fn pending_retry_drains_with_mock_classifier() {
    let xdg = assert_fs::TempDir::new().unwrap();
    let proj = assert_fs::TempDir::new().unwrap();

    // Seed: real task in JSONL so the classifier-mocked event has a
    // legitimate task_id to attach to.
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", xdg.path())
            .current_dir(proj.path())
            .args(["create", "Pending host"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    write_pending(
        xdg.path(),
        "tj-pending-2",
        "Adopted Rust for the journal",
        0,
    );

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", xdg.path())
        .current_dir(proj.path())
        .args([
            "pending",
            "retry",
            "--mock-event-type",
            "decision",
            "--mock-task-id",
            &task_id,
            "--mock-confidence",
            "0.92",
        ])
        .assert()
        .success()
        .stdout(contains("1 drained"));

    // pending file removed
    let pending_file = xdg
        .path()
        .join("task-journal")
        .join("pending")
        .join("tj-pending-2.json");
    assert!(!pending_file.exists(), "drained entry must be removed");

    // event landed in JSONL — visible in pack
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", xdg.path())
        .current_dir(proj.path())
        .args(["pack", &task_id, "--mode", "full"])
        .assert()
        .success()
        .stdout(contains("Adopted Rust for the journal"));
}

#[test]
fn pending_retry_marks_dead_after_max_attempts() {
    let xdg = assert_fs::TempDir::new().unwrap();
    let proj = assert_fs::TempDir::new().unwrap();
    // Already at attempts=2; one more failure should rename to *.dead.json.
    write_pending(xdg.path(), "tj-dying", "any text", 2);

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", xdg.path())
        .current_dir(proj.path())
        // No --mock-* flags → retry fails → attempts becomes 3 → dead.
        .args(["pending", "retry"])
        .assert()
        .success()
        .stdout(contains("1 marked dead"));

    let pending_dir = xdg.path().join("task-journal").join("pending");
    let live = pending_dir.join("tj-dying.json");
    let dead = pending_dir.join("tj-dying.dead.json");
    assert!(!live.exists(), "live file must be gone after dead-rename");
    assert!(dead.exists(), "dead file must exist: {dead:?}");
}

#[test]
fn export_sqlite_round_trips_through_pack() {
    // Setup A: write a project + task in xdg_a/proj_a.
    let xdg_a = assert_fs::TempDir::new().unwrap();
    let proj_a = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", xdg_a.path())
            .current_dir(proj_a.path())
            .args(["create", "Round-trip via sqlite export"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", xdg_a.path())
        .current_dir(proj_a.path())
        .args([
            "event",
            &task_id,
            "--type",
            "decision",
            "--text",
            "Adopt sqlite export",
        ])
        .assert()
        .success();

    // Export the SQLite snapshot to a buffer.
    let snapshot = Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", xdg_a.path())
        .current_dir(proj_a.path())
        .args(["export", "--format", "sqlite"])
        .output()
        .unwrap()
        .stdout;
    assert!(
        snapshot.starts_with(b"SQLite format 3\0"),
        "magic bytes missing"
    );

    // Setup B: a fresh xdg, no JSONL — only the snapshot in state/.
    let xdg_b = assert_fs::TempDir::new().unwrap();
    // Project hash derives from the proj path; we keep the same path so
    // the hash matches what the snapshot was keyed under.
    let project_hash = {
        let out = Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", xdg_a.path())
            .current_dir(proj_a.path())
            .args(["doctor", "--json"])
            .output()
            .unwrap()
            .stdout;
        let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
        v["state_dir"].as_str().unwrap().to_owned()
    };
    // We can't read the project_hash directly, but state_dir/<hash>.sqlite
    // is the file we're after. Re-derive the destination for xdg_b by
    // running doctor against xdg_b too — same proj path = same hash.
    let _ = project_hash;
    let dest_state_dir = xdg_b.path().join("task-journal").join("state");
    std::fs::create_dir_all(&dest_state_dir).unwrap();
    // Pull the source filename (first .sqlite under xdg_a/task-journal/state).
    let src_state_dir = xdg_a.path().join("task-journal").join("state");
    let src_file = std::fs::read_dir(&src_state_dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .map(|e| e.path())
        .find(|p| p.extension().and_then(|s| s.to_str()) == Some("sqlite"))
        .expect("source sqlite present");
    let dest_file = dest_state_dir.join(src_file.file_name().unwrap());
    std::fs::write(&dest_file, &snapshot).unwrap();

    // Pack from the new XDG without a JSONL — assemble must read from the
    // snapshot SQLite alone.
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", xdg_b.path())
        .current_dir(proj_a.path())
        .args(["pack", &task_id, "--mode", "full"])
        .assert()
        .success()
        .stdout(contains("Adopt sqlite export"));
}

#[test]
fn export_html_emits_self_contained_document() {
    let xdg = assert_fs::TempDir::new().unwrap();
    let proj = assert_fs::TempDir::new().unwrap();

    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", xdg.path())
            .current_dir(proj.path())
            .args(["create", "HTML export test"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", xdg.path())
        .current_dir(proj.path())
        .args([
            "event",
            &task_id,
            "--type",
            "decision",
            "--text",
            "Adopt Rust",
        ])
        .assert()
        .success();

    let output = Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", xdg.path())
        .current_dir(proj.path())
        .args(["export", "--format", "html", "--task", &task_id])
        .output()
        .unwrap();
    let html = String::from_utf8(output.stdout).unwrap();

    // Self-contained shape.
    let lower = html.to_lowercase();
    assert!(
        lower.starts_with("<!doctype html>"),
        "html missing doctype: {html}"
    );
    assert!(html.contains("HTML export test"), "task title missing");
    assert!(html.contains("Adopt Rust"), "decision event missing");
    // No external assets — no http/https URL anywhere.
    assert!(!html.contains("http://"), "external http url leaked");
    assert!(!html.contains("https://"), "external https url leaked");
}

#[test]
fn migrate_project_round_trips_data_to_new_path() {
    let xdg = assert_fs::TempDir::new().unwrap();
    let proj_a = assert_fs::TempDir::new().unwrap();
    let proj_b = assert_fs::TempDir::new().unwrap();

    // Create a task with the cwd = proj_a.
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", xdg.path())
            .current_dir(proj_a.path())
            .args(["create", "Migration round-trip"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    // Migrate the data to proj_b.
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", xdg.path())
        .args([
            "migrate-project",
            "--from",
            proj_a.path().to_str().unwrap(),
            "--to",
            proj_b.path().to_str().unwrap(),
        ])
        .assert()
        .success();

    // Pack from proj_b finds the same task.
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", xdg.path())
        .current_dir(proj_b.path())
        .args(["pack", &task_id, "--mode", "full"])
        .assert()
        .success()
        .stdout(contains("Migration round-trip"));
}

#[test]
fn migrate_project_refuses_overwrite_without_force() {
    let xdg = assert_fs::TempDir::new().unwrap();
    let proj_a = assert_fs::TempDir::new().unwrap();
    let proj_b = assert_fs::TempDir::new().unwrap();

    // Both projects have data: create a task in each.
    for proj in [&proj_a, &proj_b] {
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", xdg.path())
            .current_dir(proj.path())
            .args(["create", "Conflicting"])
            .assert()
            .success();
    }

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", xdg.path())
        .args([
            "migrate-project",
            "--from",
            proj_a.path().to_str().unwrap(),
            "--to",
            proj_b.path().to_str().unwrap(),
        ])
        .assert()
        .failure()
        .stderr(contains("destination already exists"));
}

#[test]
fn close_unknown_task_id_returns_error() {
    let dir = assert_fs::TempDir::new().unwrap();
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["close", "tj-doesnotexist", "--reason", "shipped"])
        .assert()
        .failure()
        .stderr(contains("task not found: tj-doesnotexist"));
}

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

    let state = dir.path().join("task-journal").join("state");
    std::fs::create_dir_all(&state).unwrap();

    for hash in ["aaaa1111aaaa1111", "bbbb2222bbbb2222"] {
        let db_path = state.join(format!("{hash}.sqlite"));
        let conn = tj_core::db::open(&db_path).unwrap();
        let mut e = tj_core::event::Event::new(
            format!("tj-{}", &hash[..6]),
            tj_core::event::EventType::Open,
            tj_core::event::Author::User,
            tj_core::event::Source::Cli,
            format!("Marker {hash}"),
        );
        e.meta = serde_json::json!({"title": format!("Title {hash}")});
        tj_core::db::upsert_task_from_event(&conn, &e, hash).unwrap();
        tj_core::db::index_event(&conn, &e).unwrap();
    }

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["search", "Marker", "--all-projects"])
        .assert()
        .success()
        .stdout(contains("aaaa1111").and(contains("bbbb2222")));
}

#[test]
fn search_command_finds_task_by_event_text() {
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "OAuth thing"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args([
            "event",
            &task_id,
            "--type",
            "decision",
            "--text",
            "Adopt Rust + rmcp",
        ])
        .assert()
        .success();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["search", "rmcp"])
        .assert()
        .success()
        .stdout(contains(&task_id));
}

#[test]
fn e2e_create_event_close_pack_search() {
    let dir = assert_fs::TempDir::new().unwrap();
    let env = || {
        let mut cmd = Command::cargo_bin("task-journal").unwrap();
        cmd.env("XDG_DATA_HOME", dir.path());
        cmd
    };

    let task_id = String::from_utf8(
        env()
            .args(["create", "Build pack assembler"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    env()
        .args([
            "event",
            &task_id,
            "--type",
            "hypothesis",
            "--text",
            "Use SQLite views",
        ])
        .assert()
        .success();
    env()
        .args([
            "event",
            &task_id,
            "--type",
            "decision",
            "--text",
            "Rust + rmcp",
        ])
        .assert()
        .success();
    env()
        .args([
            "event",
            &task_id,
            "--type",
            "rejection",
            "--text",
            "Node loses binary",
        ])
        .assert()
        .success();
    env()
        .args(["close", &task_id, "--reason", "shipped"])
        .assert()
        .success();

    env()
        .args(["pack", &task_id, "--mode", "full"])
        .assert()
        .success()
        .stdout(
            contains("Build pack assembler")
                .and(contains("Rust + rmcp"))
                .and(contains("Node loses binary"))
                .and(contains("status: closed")),
        );

    env()
        .args(["search", "rmcp"])
        .assert()
        .success()
        .stdout(contains(&task_id));
}

#[test]
fn e2e_hook_simulation_classifies_and_packs_event() {
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "Stack choice for journal"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args([
            "ingest-hook",
            "--kind",
            "Stop",
            "--text",
            "After review, we adopt Rust because of the single-binary distribution.",
            "--mock-event-type",
            "decision",
            "--mock-task-id",
            &task_id,
            "--mock-confidence",
            "0.92",
        ])
        .assert()
        .success();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "full"])
        .assert()
        .success()
        .stdout(
            contains("Stack choice for journal")
                .and(contains("[decision]"))
                .and(contains("single-binary"))
                .and(contains("[?]").not()),
        );
}

#[test]
fn event_correct_links_to_corrected_event() {
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "Correct me"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    let bad = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args([
                "event",
                &task_id,
                "--type",
                "finding",
                "--text",
                "Migration done (wrong)",
            ])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args([
            "event-correct",
            "--corrects",
            &bad,
            "--task",
            &task_id,
            "--text",
            "Migration was NOT done; finding was wrong",
        ])
        .assert()
        .success();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "full"])
        .assert()
        .success()
        .stdout(contains("Migration was NOT done").and(contains("[correction]")));
}

#[test]
fn install_hooks_command_uses_no_fail_pattern() {
    let dir = assert_fs::TempDir::new().unwrap();
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("HOME", dir.path())
        .args(["install-hooks", "--scope", "user"])
        .assert()
        .success();
    let s = std::fs::read_to_string(dir.path().join(".claude/settings.json")).unwrap();
    assert!(
        s.contains("|| true"),
        "hook command must end with || true so a failed classifier doesn't break Claude Code: {s}"
    );
}

#[test]
fn install_hooks_writes_to_settings_json() {
    let dir = assert_fs::TempDir::new().unwrap();
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("HOME", dir.path())
        .args(["install-hooks", "--scope", "user"])
        .assert()
        .success();

    let settings_path = dir.path().join(".claude").join("settings.json");
    assert!(settings_path.exists());
    let content = std::fs::read_to_string(&settings_path).unwrap();
    assert!(content.contains("UserPromptSubmit"));
    assert!(content.contains("PostToolUse"));
    assert!(content.contains("task-journal ingest-hook"));
    assert!(
        content.contains("SessionStart"),
        "install-hooks must wire SessionStart so resume-pack injection works"
    );
}

#[test]
fn install_hooks_is_idempotent_and_uninstall_works() {
    let dir = assert_fs::TempDir::new().unwrap();
    let claude_dir = dir.path().join(".claude");
    std::fs::create_dir_all(&claude_dir).unwrap();
    std::fs::write(
        claude_dir.join("settings.json"),
        serde_json::json!({"theme": "dark"}).to_string(),
    )
    .unwrap();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("HOME", dir.path())
        .args(["install-hooks", "--scope", "user"])
        .assert()
        .success();
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("HOME", dir.path())
        .args(["install-hooks", "--scope", "user"])
        .assert()
        .success();

    let after_install = std::fs::read_to_string(claude_dir.join("settings.json")).unwrap();
    assert!(
        after_install.contains("\"theme\":\"dark\"")
            || after_install.contains("\"theme\": \"dark\""),
        "must preserve unrelated keys"
    );
    assert!(after_install.contains("UserPromptSubmit"));

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("HOME", dir.path())
        .args(["install-hooks", "--scope", "user", "--uninstall"])
        .assert()
        .success();

    let after_uninstall = std::fs::read_to_string(claude_dir.join("settings.json")).unwrap();
    assert!(
        after_uninstall.contains("\"theme\":\"dark\"")
            || after_uninstall.contains("\"theme\": \"dark\""),
        "must still preserve theme"
    );
    assert!(!after_uninstall.contains("UserPromptSubmit"));
}

#[test]
fn install_hooks_uninstall_preserves_third_party_hook_entries() {
    // Repro for the "uninstall nukes everyone's hooks" bug. The fix
    // must walk into each event array and filter out ONLY commands
    // matching task-journal — other plugins (token-pilot in the
    // wild) keep their entries.
    let dir = assert_fs::TempDir::new().unwrap();
    let claude_dir = dir.path().join(".claude");
    std::fs::create_dir_all(&claude_dir).unwrap();

    // Pre-existing settings: task-journal-style entry + a foreign
    // plugin's hook on the same event.
    let pre = serde_json::json!({
        "hooks": {
            "UserPromptSubmit": [
                {
                    "matcher": "",
                    "hooks": [
                        { "type": "command", "command": "task-journal ingest-hook --kind=$CLAUDE_HOOK_NAME --text=\"$CLAUDE_HOOK_TEXT\" --backend=cli || true" },
                        { "type": "command", "command": "other-plugin do-something" }
                    ]
                }
            ],
            "PostToolUse": [
                {
                    "matcher": "",
                    "hooks": [
                        { "type": "command", "command": "third-party-only-hook" }
                    ]
                }
            ]
        }
    });
    std::fs::write(claude_dir.join("settings.json"), pre.to_string()).unwrap();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("HOME", dir.path())
        .args(["install-hooks", "--scope", "user", "--uninstall"])
        .assert()
        .success();

    let after = std::fs::read_to_string(claude_dir.join("settings.json")).unwrap();
    let v: serde_json::Value = serde_json::from_str(&after).unwrap();

    assert!(
        !after.contains("task-journal ingest-hook"),
        "task-journal entry must be gone: {after}"
    );
    assert!(
        after.contains("other-plugin do-something"),
        "co-located third-party hook must survive: {after}"
    );
    assert!(
        after.contains("third-party-only-hook"),
        "PostToolUse with no task-journal entry must be untouched: {after}"
    );
    // The hooks block itself stays; other plugins' kinds remain.
    assert!(
        v.get("hooks").is_some(),
        "hooks block must still exist: {after}"
    );
}

#[test]
fn install_hooks_with_classifier_command_writes_env() {
    let dir = assert_fs::TempDir::new().unwrap();
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("HOME", dir.path())
        .args([
            "install-hooks",
            "--scope",
            "user",
            "--classifier-command",
            "aimux run dt",
        ])
        .assert()
        .success();
    let content = std::fs::read_to_string(dir.path().join(".claude/settings.json")).unwrap();
    let v: serde_json::Value = serde_json::from_str(&content).unwrap();
    assert_eq!(
        v.get("env")
            .and_then(|e| e.get("TJ_CLASSIFIER_CLI"))
            .and_then(|s| s.as_str()),
        Some("aimux run dt"),
        "env.TJ_CLASSIFIER_CLI must be set: {content}"
    );
}

#[test]
fn install_hooks_without_classifier_command_does_not_set_env() {
    let dir = assert_fs::TempDir::new().unwrap();
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("HOME", dir.path())
        .args(["install-hooks", "--scope", "user"])
        .assert()
        .success();
    let content = std::fs::read_to_string(dir.path().join(".claude/settings.json")).unwrap();
    let v: serde_json::Value = serde_json::from_str(&content).unwrap();
    assert!(
        v.get("env")
            .and_then(|e| e.get("TJ_CLASSIFIER_CLI"))
            .is_none(),
        "TJ_CLASSIFIER_CLI must NOT be present when flag not passed: {content}"
    );
}

#[test]
fn install_hooks_uninstall_removes_classifier_env_but_preserves_others() {
    let dir = assert_fs::TempDir::new().unwrap();
    let claude_dir = dir.path().join(".claude");
    std::fs::create_dir_all(&claude_dir).unwrap();
    std::fs::write(
        claude_dir.join("settings.json"),
        serde_json::json!({ "env": { "OTHER_KEY": "keep_me" } }).to_string(),
    )
    .unwrap();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("HOME", dir.path())
        .args([
            "install-hooks",
            "--scope",
            "user",
            "--classifier-command",
            "aimux run dt",
        ])
        .assert()
        .success();
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("HOME", dir.path())
        .args(["install-hooks", "--scope", "user", "--uninstall"])
        .assert()
        .success();

    let after = std::fs::read_to_string(claude_dir.join("settings.json")).unwrap();
    let v: serde_json::Value = serde_json::from_str(&after).unwrap();
    assert!(
        v.get("env")
            .and_then(|e| e.get("TJ_CLASSIFIER_CLI"))
            .is_none(),
        "TJ_CLASSIFIER_CLI must be removed on uninstall: {after}"
    );
    assert_eq!(
        v.get("env")
            .and_then(|e| e.get("OTHER_KEY"))
            .and_then(|s| s.as_str()),
        Some("keep_me"),
        "unrelated env keys must be preserved: {after}"
    );
}

#[test]
fn ingest_hook_drains_pending_queue_via_mock() {
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "Drain"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    let pending = dir.path().join("task-journal").join("pending");
    std::fs::create_dir_all(&pending).unwrap();
    std::fs::write(
        pending.join("01stuck.json"),
        serde_json::json!({
            "text": "We decided to adopt PKCE flow.",
            "queued_at": "2026-04-30T00:00:00Z"
        })
        .to_string(),
    )
    .unwrap();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args([
            "ingest-hook",
            "--kind",
            "Stop",
            "--text",
            "Live chunk",
            "--mock-event-type",
            "decision",
            "--mock-task-id",
            &task_id,
            "--mock-confidence",
            "0.95",
        ])
        .assert()
        .success();

    let remaining: Vec<_> = std::fs::read_dir(&pending)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().ends_with(".json"))
        .collect();
    assert_eq!(
        remaining.len(),
        0,
        "pending queue must be empty after successful ingest"
    );
}

#[test]
fn stats_command_shows_classifier_counts() {
    let dir = assert_fs::TempDir::new().unwrap();
    let metrics = dir.path().join("task-journal").join("metrics");
    std::fs::create_dir_all(&metrics).unwrap();
    let body = [r#"{"timestamp":"2026-04-30T00:00:00Z","project_hash":"feedface","task_id_guess":"tj-x","event_type":"decision","confidence":0.95,"status":"confirmed","error":null}"#,
        r#"{"timestamp":"2026-04-30T00:00:00Z","project_hash":"feedface","task_id_guess":"tj-x","event_type":"finding","confidence":0.65,"status":"suggested","error":null}"#].join("\n");
    std::fs::write(metrics.join("feedface.jsonl"), body).unwrap();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["stats"])
        .assert()
        .success()
        .stdout(
            contains("classified: 2")
                .and(contains("confirmed: 1"))
                .and(contains("suggested: 1")),
        );
}

#[test]
fn ingest_hook_writes_telemetry_record() {
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "Tel"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args([
            "ingest-hook",
            "--kind",
            "Stop",
            "--text",
            "decided to use Rust",
            "--mock-event-type",
            "decision",
            "--mock-task-id",
            &task_id,
            "--mock-confidence",
            "0.92",
        ])
        .assert()
        .success();

    let metrics_dir = dir.path().join("task-journal").join("metrics");
    let mut total_lines = 0;
    if metrics_dir.exists() {
        for entry in std::fs::read_dir(&metrics_dir).unwrap() {
            let p = entry.unwrap().path();
            if p.extension().and_then(|e| e.to_str()) == Some("jsonl") {
                total_lines += std::fs::read_to_string(&p).unwrap().lines().count();
            }
        }
    }
    assert!(
        total_lines >= 1,
        "expected at least one telemetry line, got {total_lines}"
    );
}

#[test]
fn ingest_hook_session_start_emits_resume_pack_json() {
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "Wire SessionStart pack"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args([
            "event",
            &task_id,
            "--type",
            "decision",
            "--text",
            "Adopt Rust for the journal.",
        ])
        .assert()
        .success();

    let out = Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["ingest-hook", "--kind", "SessionStart", "--text", ""])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let body = String::from_utf8(out).unwrap();

    let v: serde_json::Value = serde_json::from_str(body.trim()).unwrap_or_else(|e| {
        panic!("SessionStart hook stdout must be JSON; got: {body:?}; err: {e}")
    });
    let hso = v
        .get("hookSpecificOutput")
        .expect("hookSpecificOutput key missing");
    assert_eq!(
        hso.get("hookEventName").and_then(|s| s.as_str()),
        Some("SessionStart"),
        "wrong hookEventName: {body}"
    );
    let ctx = hso
        .get("additionalContext")
        .and_then(|s| s.as_str())
        .expect("additionalContext key missing");
    assert!(
        ctx.contains("Wire SessionStart pack"),
        "additionalContext must include task title: {ctx}"
    );
    assert!(
        ctx.contains("Adopt Rust"),
        "additionalContext must include event text: {ctx}"
    );
}

#[test]
fn ingest_hook_session_start_with_no_open_tasks_emits_no_context() {
    let dir = assert_fs::TempDir::new().unwrap();
    let out = Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["ingest-hook", "--kind", "SessionStart", "--text", ""])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let body = String::from_utf8(out).unwrap();
    // Empty stdout is the documented signal to Claude Code that no
    // additionalContext should be injected — we don't want to pollute
    // the system prompt with an empty pack on fresh projects.
    assert!(
        body.trim().is_empty(),
        "SessionStart with no open tasks must emit nothing, got: {body:?}"
    );
}

#[test]
fn create_with_goal_renders_in_pack() {
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "Add OAuth", "--goal", "Implement PKCE flow"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "compact"])
        .assert()
        .success()
        .stdout(contains("**Goal**: Implement PKCE flow"));
}

#[test]
fn create_without_goal_renders_not_set_placeholder() {
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "No goal"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    // Force goal to populate via the post-hoc command path so the row
    // exists in SQLite (create without --goal skips the SQLite write,
    // and pack needs the row to render). Without setting goal here we
    // still exercise the `(not set)` placeholder path because pack
    // reads via ingest_new_events first.
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "compact"])
        .assert()
        .success()
        .stdout(contains("**Goal**: (not set)"));
}

#[test]
fn close_with_outcome_renders_outcome_block() {
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "Ship feature X", "--goal", "deliver X"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args([
            "close",
            &task_id,
            "--outcome",
            "Shipped in v0.4.0",
            "--outcome-tag",
            "done",
        ])
        .assert()
        .success();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "compact"])
        .assert()
        .success()
        .stdout(contains("**Outcome** [done]: Shipped in v0.4.0"));
}

#[test]
fn close_rejects_invalid_outcome_tag() {
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "T"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["close", &task_id, "--outcome", "ok", "--outcome-tag", "wat"])
        .assert()
        .failure()
        .stderr(contains("invalid --outcome-tag"));
}

#[test]
fn goal_command_updates_existing_task() {
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "Initial title"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["goal", &task_id, "Set after the fact"])
        .assert()
        .success();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "compact"])
        .assert()
        .success()
        .stdout(contains("**Goal**: Set after the fact"));
}

#[test]
fn external_add_appends_references() {
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "Linked work"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["external", &task_id, "--add", "beads:claude-memory-rsw"])
        .assert()
        .success();
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["external", &task_id, "--add", "github:#42"])
        .assert()
        .success();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "compact"])
        .assert()
        .success()
        .stdout(contains("**External**: beads:claude-memory-rsw,github:#42"));
}

#[test]
fn ingest_hook_short_circuits_when_in_classifier_env_set() {
    // Recursion guard: classifier sets TJ_IN_CLASSIFIER=1 before
    // spawning claude. The nested claude re-fires our hooks; without
    // this guard, ingest-hook would re-enter the classifier path
    // ad infinitum. With the guard, it returns silently and no event
    // is written.
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "Recursion guard host"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .env("TJ_IN_CLASSIFIER", "1")
        .args([
            "ingest-hook",
            "--kind",
            "UserPromptSubmit",
            "--text",
            "should not be ingested",
            "--mock-event-type",
            "decision",
            "--mock-task-id",
            &task_id,
            "--mock-confidence",
            "0.99",
        ])
        .assert()
        .success();

    // The pack must NOT contain the hook text — guard kicked in
    // before the mock branch could write.
    let out = Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "full"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let body = String::from_utf8(out).unwrap();
    assert!(
        !body.contains("should not be ingested"),
        "TJ_IN_CLASSIFIER must short-circuit before any write: {body}"
    );
}

#[test]
fn ingest_hook_reads_user_prompt_submit_payload_from_stdin() {
    // Real Claude Code passes hook input as JSON over stdin, NOT via env
    // vars. Without this, every captured event has empty text and the
    // classifier rejects it. Regression for claude-memory-rsw.
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "Stdin host"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    let payload = serde_json::json!({
        "hook_event_name": "UserPromptSubmit",
        "session_id": "s-1",
        "transcript_path": "/tmp/x",
        "cwd": "/tmp",
        "prompt": "We adopted Rust for the journal."
    })
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args([
            "ingest-hook",
            "--backend",
            "cli",
            "--mock-event-type",
            "decision",
            "--mock-task-id",
            &task_id,
            "--mock-confidence",
            "0.95",
        ])
        .write_stdin(payload)
        .assert()
        .success();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "full"])
        .assert()
        .success()
        .stdout(contains("We adopted Rust for the journal"));
}

#[test]
fn ingest_hook_reads_post_tool_use_payload_from_stdin() {
    // PostToolUse payloads have no `prompt` field — content lives in
    // `tool_name` / `tool_input` / `tool_response`. The stdin parser must
    // synthesize text from those.
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "Tool host"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    let payload = serde_json::json!({
        "hook_event_name": "PostToolUse",
        "session_id": "s-2",
        "transcript_path": "/tmp/x",
        "cwd": "/tmp",
        "tool_name": "Bash",
        "tool_input": { "command": "cargo test" },
        "tool_response": { "output": "all 222 tests pass" }
    })
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args([
            "ingest-hook",
            "--backend",
            "cli",
            "--mock-event-type",
            "evidence",
            "--mock-task-id",
            &task_id,
            "--mock-confidence",
            "0.9",
        ])
        .write_stdin(payload)
        .assert()
        .success();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "full"])
        .assert()
        .success()
        .stdout(contains("Bash").and(contains("cargo test")));
}

#[test]
fn install_hooks_writes_command_without_bogus_env_var_interpolation() {
    // The old install-hooks emitted $CLAUDE_HOOK_NAME / $CLAUDE_HOOK_TEXT,
    // neither of which Claude Code actually populates. The current command
    // must rely on stdin instead.
    let dir = assert_fs::TempDir::new().unwrap();
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("HOME", dir.path())
        .args(["install-hooks", "--scope", "user"])
        .assert()
        .success();
    let s = std::fs::read_to_string(dir.path().join(".claude/settings.json")).unwrap();
    assert!(
        !s.contains("$CLAUDE_HOOK_NAME") && !s.contains("$CLAUDE_HOOK_TEXT"),
        "install-hooks must not interpolate non-existent env vars: {s}"
    );
}

#[test]
fn ingest_hook_with_mock_writes_classified_event() {
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "Mock target"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args([
            "ingest-hook",
            "--kind",
            "Stop",
            "--text",
            "We decided to adopt Rust.",
            "--mock-event-type",
            "decision",
            "--mock-task-id",
            &task_id,
            "--mock-confidence",
            "0.95",
        ])
        .assert()
        .success();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "full"])
        .assert()
        .success()
        .stdout(contains("We decided to adopt Rust.").and(contains("[decision]")));
}

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

    let ids: Vec<String> = (0..5)
        .map(|_| {
            let out = Command::cargo_bin("task-journal")
                .unwrap()
                .env("XDG_DATA_HOME", dir.path())
                .args(["create", "Same title"])
                .assert()
                .success()
                .get_output()
                .stdout
                .clone();
            String::from_utf8(out).unwrap().trim().to_string()
        })
        .collect();

    let unique: std::collections::HashSet<_> = ids.iter().collect();
    assert_eq!(unique.len(), 5, "task ids must be unique, got: {ids:?}");
}

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

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["create", "Add OAuth login"])
        .assert()
        .success();

    let events_glob = dir.path().join("task-journal").join("events");
    let mut found_lines = 0;
    for entry in std::fs::read_dir(&events_glob).unwrap() {
        let p = entry.unwrap().path();
        if p.extension().and_then(|e| e.to_str()) == Some("jsonl") {
            let body = std::fs::read_to_string(&p).unwrap();
            for line in body.lines() {
                let v: serde_json::Value = serde_json::from_str(line).unwrap();
                if v["type"] == "open" && v["text"].as_str().unwrap_or("").contains("OAuth") {
                    found_lines += 1;
                }
            }
        }
    }
    assert_eq!(found_lines, 1);
}

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

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["create", "First task"])
        .assert()
        .success();
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["create", "Second task"])
        .assert()
        .success();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["events", "list", "--limit", "10"])
        .assert()
        .success()
        .stdout(contains("First task").and(contains("Second task")));
}

#[test]
fn rebuild_state_creates_sqlite_with_one_task() {
    let dir = assert_fs::TempDir::new().unwrap();
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["create", "Build it"])
        .assert()
        .success();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["rebuild-state"])
        .assert()
        .success()
        .stdout(contains("rebuilt"));

    let state_dir = dir.path().join("task-journal").join("state");
    let mut found = 0;
    for entry in std::fs::read_dir(&state_dir).unwrap() {
        let p = entry.unwrap().path();
        if p.extension().and_then(|e| e.to_str()) == Some("sqlite") {
            let conn = rusqlite::Connection::open(&p).unwrap();
            let n: i64 = conn
                .query_row("SELECT COUNT(*) FROM tasks", [], |r| r.get(0))
                .unwrap();
            assert_eq!(n, 1);
            found += 1;
        }
    }
    assert_eq!(found, 1);
}

#[test]
fn ingest_hook_help_hides_mock_flags() {
    Command::cargo_bin("task-journal")
        .unwrap()
        .args(["ingest-hook", "--help"])
        .assert()
        .success()
        .stdout(contains("--mock-event-type").not())
        .stdout(contains("--mock-task-id").not())
        .stdout(contains("--mock-confidence").not())
        .stdout(contains("--kind"))
        .stdout(contains("--text"));
}

#[test]
fn help_lists_subcommands() {
    Command::cargo_bin("task-journal")
        .unwrap()
        .arg("--help")
        .assert()
        .success()
        .stdout(contains("create"))
        .stdout(contains("events"))
        .stdout(contains("rebuild-state"));
}

#[test]
fn ingest_hook_auto_opens_task_when_no_open_tasks() {
    // v0.5.0 Phase A: a UserPromptSubmit hook firing into an empty
    // project must synthesize a task on the fly, otherwise the prompt
    // (and every event after it) is dropped silently.
    let dir = assert_fs::TempDir::new().unwrap();

    // Force the classifier to fail so the rest of the pipeline doesn't
    // try to spawn `claude -p`. Auto-open happens BEFORE the classifier
    // call, so the task should still be created.
    let payload = serde_json::json!({
        "hook_event_name": "UserPromptSubmit",
        "session_id": "s-auto",
        "transcript_path": "/tmp/x",
        "cwd": "/tmp",
        "prompt": "implement FIN-868 paygate fee dedup"
    })
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .env("TJ_CLASSIFIER_CLI", "/bin/false")
        // v0.6.2: real-classifier path now async by default. Force sync
        // here so auto-open + pending side-effects are observable
        // synchronously after the command returns.
        .env("TJ_INGEST_SYNC", "1")
        .args(["ingest-hook", "--backend", "cli"])
        .write_stdin(payload)
        .assert()
        .success();

    // Auto-opened task is now searchable. Pack it and check that the
    // goal field equals the prompt text — that's the contract.
    let search_out = Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["search", "paygate"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let body = String::from_utf8(search_out).unwrap();
    // Search output is task-id-per-line. A non-empty body proves the
    // auto-opened task was indexed by FTS5 against the prompt text.
    let task_id = body
        .lines()
        .next()
        .map(|s| s.trim().to_string())
        .filter(|s| s.starts_with("tj-"))
        .unwrap_or_else(|| {
            panic!("search must surface the auto-opened task by prompt text, got: {body:?}")
        });

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "full"])
        .assert()
        .success()
        .stdout(contains("**Goal**: implement FIN-868 paygate fee dedup"));
}

#[test]
fn reopen_command_flips_status_back_to_open() {
    // v0.5.0 Phase C: a closed task can be revived via `reopen`. The
    // [reopen] event itself triggers the status flip (db lifecycle).
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "Reopen target"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["close", &task_id, "--reason", "first close"])
        .assert()
        .success();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "full"])
        .assert()
        .success()
        .stdout(contains("[status: closed]"));

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["reopen", &task_id, "--reason", "regression came back"])
        .assert()
        .success();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "full"])
        .assert()
        .success()
        .stdout(contains("[status: open]"));
}

#[test]
fn auto_open_links_to_prior_task_referencing_same_issue() {
    // v0.5.0 Phase C: if a fresh prompt mentions a ticket id that
    // already shows up in the journal, the new auto-opened task gets
    // an external "linked:tj-other" pointer so the chain is visible
    // in the pack rather than orphaned.
    let dir = assert_fs::TempDir::new().unwrap();
    let prior = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "Original FIN work"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args([
            "event",
            &prior,
            "--type",
            "decision",
            "--text",
            "fixed FIN-868 paygate fee duplicate write",
        ])
        .assert()
        .success();
    // Close the prior task — auto-open's link target is closed-but-
    // related, exactly the regression-came-back scenario.
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["close", &prior, "--reason", "shipped"])
        .assert()
        .success();

    // Now fire a fresh UserPromptSubmit referencing the same ticket.
    let payload = serde_json::json!({
        "hook_event_name": "UserPromptSubmit",
        "session_id": "s-link",
        "transcript_path": "/tmp/x",
        "cwd": "/tmp",
        "prompt": "FIN-868 came back: paygate fee written twice on partial refund"
    })
    .to_string();
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .env("TJ_CLASSIFIER_CLI", "/bin/false")
        // v0.6.2: force sync so the auto-open side effect (reopen note
        // on stderr) is observable synchronously.
        .env("TJ_INGEST_SYNC", "1")
        .args(["ingest-hook", "--backend", "cli"])
        .write_stdin(payload)
        .assert()
        .success()
        .stderr(contains(format!("reopen {}", prior)));

    // Find the newly auto-opened task and confirm it has a linked
    // pointer back to the prior in External.
    let search_out = Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["search", "paygate"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let body = String::from_utf8(search_out).unwrap();
    let new_id = body
        .lines()
        .find(|l| l.starts_with("tj-") && !l.contains(&prior))
        .map(|s| s.trim().to_string())
        .expect("auto-opened task must show up in search alongside prior");

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &new_id, "--mode", "full"])
        .assert()
        .success()
        // v0.6.0: linked entries surface in their own **Linked** block
        // instead of mashed into External, with the prior task's
        // current status annotated next to the id.
        .stdout(contains("**Linked**:"))
        .stdout(contains(format!("- {} [closed]", prior)));
}

#[test]
fn pack_renders_artifacts_block_from_event_text() {
    // v0.5.0 Phase B: artifacts (commits, PRs, issues) auto-extracted
    // from event text appear in pack as **Artifacts** block.
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "FIN-868 host"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args([
            "event",
            &task_id,
            "--type",
            "decision",
            "--text",
            "fixed in abc1234 — see https://github.com/Digital-Threads/Task-Journal/pull/42 — references FIN-868",
        ])
        .assert()
        .success();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "full"])
        .assert()
        .success()
        .stdout(contains("**Artifacts**:"))
        .stdout(contains("commits: abc1234"))
        .stdout(contains(
            "PRs: https://github.com/Digital-Threads/Task-Journal/pull/42",
        ))
        .stdout(contains("issues: FIN-868"));
}

#[test]
fn reclassify_backfills_artifacts_for_existing_events() {
    // After upgrade from v0.4.x, old events have NULL artifacts. The
    // `reclassify` command must walk the event_index and re-extract.
    let dir = assert_fs::TempDir::new().unwrap();
    let task_id = String::from_utf8(
        Command::cargo_bin("task-journal")
            .unwrap()
            .env("XDG_DATA_HOME", dir.path())
            .args(["create", "Backfill host"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap()
    .trim()
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args([
            "event",
            &task_id,
            "--type",
            "evidence",
            "--text",
            "verified at commit deadbeef99",
        ])
        .assert()
        .success();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["reclassify", &task_id])
        .assert()
        .success()
        .stdout(contains("reclassified"));

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["pack", &task_id, "--mode", "full"])
        .assert()
        .success()
        .stdout(contains("commits: deadbeef99"));
}

#[test]
fn ingest_hook_auto_open_disabled_via_env() {
    // Opt-out path: TJ_AUTO_OPEN_TASKS=0 must restore the v0.4.0
    // behaviour (drop the prompt silently when no open task exists).
    let dir = assert_fs::TempDir::new().unwrap();
    let payload = serde_json::json!({
        "hook_event_name": "UserPromptSubmit",
        "session_id": "s-noop",
        "transcript_path": "/tmp/x",
        "cwd": "/tmp",
        "prompt": "marker_noautoopen_xyz must not appear"
    })
    .to_string();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .env("TJ_CLASSIFIER_CLI", "/bin/false")
        .env("TJ_AUTO_OPEN_TASKS", "0")
        // v0.6.2: force sync so post-conditions are observable.
        .env("TJ_INGEST_SYNC", "1")
        .args(["ingest-hook", "--backend", "cli"])
        .write_stdin(payload)
        .assert()
        .success();

    let search_out = Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .args(["search", "marker_noautoopen_xyz"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let body = String::from_utf8(search_out).unwrap();
    assert!(
        !body.contains("marker_noautoopen_xyz"),
        "auto-open must be skipped when TJ_AUTO_OPEN_TASKS=0, got: {body:?}"
    );
}

// ---------------- v0.6.2 async classifier tests ----------------

/// v0.6.2: ingest-hook must NOT block on the classifier. The
/// real-classifier path queues a v2 pending entry and detaches a
/// worker, so the hook returns in <100ms even when the configured
/// classifier command is `/bin/false` (instant fail) or worse.
#[test]
fn ingest_hook_returns_fast_in_async_mode() {
    let dir = assert_fs::TempDir::new().unwrap();
    let payload = serde_json::json!({
        "hook_event_name": "UserPromptSubmit",
        "session_id": "s-fast",
        "transcript_path": "/tmp/x",
        "cwd": "/tmp",
        "prompt": "fast async marker xyz123"
    })
    .to_string();

    let start = std::time::Instant::now();
    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .env("TJ_CLASSIFIER_CLI", "/bin/false")
        .args(["ingest-hook", "--backend", "cli"])
        .write_stdin(payload)
        .assert()
        .success();
    let elapsed = start.elapsed();

    // Generous budget — the hook itself does almost no work; the
    // classifier subprocess runs in the detached worker. Pre-fix,
    // this took 5-30s. Post-fix, expect well under 1s; assert <2s
    // so flaky CI doesn't fail us.
    assert!(
        elapsed < std::time::Duration::from_millis(2000),
        "ingest-hook must return in <2s in async mode, took {elapsed:?}"
    );

    // A v2 pending entry must have been written. We don't assert
    // worker progress — worker is detached and may or may not have
    // finished by the time we look.
    let pending = dir.path().join("task-journal").join("pending");
    assert!(pending.exists(), "pending dir must exist after queuing");
    let entries: Vec<_> = std::fs::read_dir(&pending)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path().extension().and_then(|s| s.to_str()) == Some("json")
        })
        .collect();
    // Worker may have already drained; in that case at least the
    // worker should have left a v1 pending entry from /bin/false
    // failure (persist_pending in the real-classifier branch). So
    // either way: at least one .json file ought to be present, OR
    // the auto-open happened (events file exists). Be tolerant.
    let events = dir.path().join("task-journal").join("events");
    let has_pending = !entries.is_empty();
    let has_events = events.exists()
        && std::fs::read_dir(&events)
            .map(|d| d.count() > 0)
            .unwrap_or(false);
    assert!(
        has_pending || has_events,
        "either pending entry or events file must exist after async hook"
    );
}

/// classify-worker exits cleanly even when the classifier command is
/// /bin/false. v2 entries that fail to classify get re-queued as v1
/// pending entries (so `pending list` surfaces them).
#[test]
fn classify_worker_handles_classifier_failure_cleanly() {
    let dir = assert_fs::TempDir::new().unwrap();
    // Pre-create a v2 pending entry by hand.
    let pending = dir.path().join("task-journal").join("pending");
    std::fs::create_dir_all(&pending).unwrap();
    let cwd = std::env::current_dir().unwrap();
    let project_hash =
        tj_core::project_hash::from_path(&cwd).expect("compute project hash");
    let events_path = dir
        .path()
        .join("task-journal")
        .join("events")
        .join(format!("{project_hash}.jsonl"));
    std::fs::create_dir_all(events_path.parent().unwrap()).unwrap();

    let entry = pending.join("01worker.json");
    let body = serde_json::json!({
        "schema": "v2",
        "kind": "UserPromptSubmit",
        "text": "worker test marker",
        "project_hash": project_hash,
        "events_path": events_path.to_string_lossy(),
        "backend": "cli",
        "queued_at": "2026-05-08T00:00:00Z",
    });
    std::fs::write(&entry, body.to_string()).unwrap();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .env("TJ_CLASSIFIER_CLI", "/bin/false")
        .args(["classify-worker", "--backend", "cli"])
        .assert()
        .success();

    // Lockfile must not be left behind.
    let state = dir.path().join("task-journal").join("state");
    if state.exists() {
        for e in std::fs::read_dir(&state).unwrap() {
            let p = e.unwrap().path();
            assert!(
                !p.file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or("")
                    .ends_with(".lock"),
                "lockfile must be removed after worker exits, found: {p:?}"
            );
        }
    }
}

/// Lockfile prevents concurrent workers in the same project. We can't
/// easily race two real spawns deterministically in a unit test, so
/// instead simulate a held lock by writing a lockfile with our own
/// (live) PID, then run classify-worker and assert it exits cleanly
/// without draining the queue.
#[test]
fn classify_worker_respects_existing_lock() {
    let dir = assert_fs::TempDir::new().unwrap();
    let cwd = std::env::current_dir().unwrap();
    let project_hash =
        tj_core::project_hash::from_path(&cwd).expect("compute project hash");

    // Pre-create a v2 pending entry.
    let pending = dir.path().join("task-journal").join("pending");
    std::fs::create_dir_all(&pending).unwrap();
    let events_path = dir
        .path()
        .join("task-journal")
        .join("events")
        .join(format!("{project_hash}.jsonl"));
    std::fs::create_dir_all(events_path.parent().unwrap()).unwrap();
    let entry = pending.join("01locked.json");
    std::fs::write(
        &entry,
        serde_json::json!({
            "schema": "v2",
            "kind": "UserPromptSubmit",
            "text": "locked marker",
            "project_hash": project_hash,
            "events_path": events_path.to_string_lossy(),
            "backend": "cli",
            "queued_at": "2026-05-08T00:00:00Z",
        })
        .to_string(),
    )
    .unwrap();

    // Hand-roll a lockfile with this process's (live) PID. The
    // worker should see the live PID and bail without touching the
    // pending entry.
    let state = dir.path().join("task-journal").join("state");
    std::fs::create_dir_all(&state).unwrap();
    let lock_path = state.join(format!("classifier-{project_hash}.lock"));
    std::fs::write(&lock_path, format!("{}\n", std::process::id())).unwrap();

    Command::cargo_bin("task-journal")
        .unwrap()
        .env("XDG_DATA_HOME", dir.path())
        .env("TJ_CLASSIFIER_CLI", "/bin/false")
        .args(["classify-worker", "--backend", "cli"])
        .assert()
        .success();

    // Pending entry must still be there — the second worker bailed.
    assert!(
        entry.exists(),
        "pending entry must survive — second worker must not have drained it"
    );
    // Our hand-rolled lockfile must still be there too — the bailing
    // worker must NOT remove a lock it didn't acquire.
    assert!(
        lock_path.exists(),
        "lockfile must survive — bailing worker must not delete others' locks"
    );
}