pma 0.3.0

Lint TODO.md files across many git repositories and rank their tasks in an Eisenhower matrix
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
use std::fs;
use std::path::PathBuf;
use std::process::{Command, Output};

/// A scratch directory unique to one test, removed when dropped.
struct Scratch(PathBuf);

impl Scratch {
    fn new(name: &str) -> Self {
        let dir = std::env::temp_dir().join(format!("pma-test-{}-{name}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        Scratch(dir)
    }

    fn project(&self, name: &str, todo: &str) -> PathBuf {
        let dir = self.0.join(name);
        fs::create_dir_all(&dir).unwrap();
        fs::write(dir.join("TODO.md"), todo).unwrap();
        dir
    }
}

impl Drop for Scratch {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.0);
    }
}

fn pma(args: &[&std::ffi::OsStr]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_pma"))
        .args(args)
        .output()
        .unwrap()
}

fn stdout(out: &Output) -> String {
    String::from_utf8_lossy(&out.stdout).into_owned()
}

#[test]
fn clean_file_exits_zero_silently() {
    let s = Scratch::new("clean");
    let dir = s.project("a", "# TODO\n\n## High\n\n- [ ] thing\n");
    let out = pma(&["lint".as_ref(), dir.as_os_str()]);
    assert!(out.status.success());
    assert_eq!(stdout(&out), "");
    assert!(out.stderr.is_empty());
}

#[test]
fn warnings_alone_exit_zero() {
    let s = Scratch::new("warn");
    let dir = s.project("a", "# TODO\n\n## Low\n\n- [x] finished #42\n");
    let out = pma(&["lint".as_ref(), dir.as_os_str()]);
    assert!(out.status.success());
    let todo = dir.join("TODO.md");
    assert_eq!(
        stdout(&out),
        format!(
            "{}:5: warning: `#42` is text; write `gh:42` to link the issue\n",
            todo.display()
        )
    );
}

#[test]
fn prune_lists_then_removes_finished_items() {
    let s = Scratch::new("prune");
    let text = "# TODO\n\n## High\n\n- [x] shipped\n  notes\n- [ ] open\n\n## Done\n\n- [x] old\n- [ ] stray\n";
    let a = s.project("a", text);
    let bad = s.project("bad", "## High\n\n- [x] kept\n");
    let todo = a.join("TODO.md");

    let out = pma(&["prune".as_ref(), a.as_os_str(), bad.as_os_str()]);
    assert!(out.status.success());
    assert_eq!(
        stdout(&out),
        format!(
            "{0}:9: remove `## Done`, lines 9-12\n\
             {0}:12: remove open item with `## Done`: `- [ ] stray`\n\
             {0}:5: remove `shipped`\n\
             {1}: skipped: lint errors; see `pma lint`\n\
             2 removals; run `pma prune --apply` to make them\n",
            todo.display(),
            bad.join("TODO.md").display()
        )
    );
    assert_eq!(fs::read_to_string(&todo).unwrap(), text);

    let out = pma(&["prune".as_ref(), "--apply".as_ref(), a.as_os_str()]);
    assert!(out.status.success());
    assert!(
        stdout(&out).ends_with("2 removals made; TODO.md edits are uncommitted\n"),
        "{}",
        stdout(&out)
    );
    assert_eq!(
        fs::read_to_string(&todo).unwrap(),
        "# TODO\n\n## High\n\n- [ ] open\n"
    );
    let out = pma(&[
        "prune".as_ref(),
        a.as_os_str(),
        s.0.join("none").as_os_str(),
    ]);
    assert_eq!(out.status.code(), Some(1));
    assert!(
        stdout(&out).ends_with("nothing to prune\n"),
        "{}",
        stdout(&out)
    );
}

#[test]
fn errors_in_any_file_exit_one_and_every_file_is_checked() {
    let s = Scratch::new("errors");
    let bad = s.project("bad", "## High\n");
    let good = s.project("good", "# TODO\n");
    let missing = s.0.join("missing");
    fs::create_dir_all(&missing).unwrap();

    let out = pma(&[
        "lint".as_ref(),
        bad.as_os_str(),
        good.as_os_str(),
        missing.as_os_str(),
    ]);
    assert_eq!(out.status.code(), Some(1));
    let text = stdout(&out);
    assert!(
        text.contains(&format!("{}:1: error:", bad.join("TODO.md").display())),
        "{text}"
    );
    assert!(
        text.contains(&format!("{}: error:", missing.join("TODO.md").display())),
        "{text}"
    );
    assert!(!text.contains(&good.display().to_string()), "{text}");
    assert_eq!(
        String::from_utf8_lossy(&out.stderr),
        "2 errors, 0 warnings\n"
    );
}

const DAY: i64 = 86_400;

fn now() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64
}

fn git(dir: &std::path::Path, args: &[&str], date: Option<i64>) {
    let mut cmd = Command::new("git");
    cmd.arg("-C")
        .arg(dir)
        .args(["-c", "user.name=t", "-c", "user.email=t@example.com"])
        .args(args);
    cmd.env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_NOSYSTEM", "1");
    if let Some(d) = date {
        cmd.env("GIT_AUTHOR_DATE", format!("@{d} +0000"))
            .env("GIT_COMMITTER_DATE", format!("@{d} +0000"));
    }
    let out = cmd.output().unwrap();
    assert!(
        out.status.success(),
        "git {args:?}: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

fn pma_in(home: &std::path::Path, args: &[&str]) -> (String, String, bool) {
    let out = Command::new(env!("CARGO_BIN_EXE_pma"))
        .env("PMA_HOME", home)
        .args(args)
        .output()
        .unwrap();
    (
        String::from_utf8_lossy(&out.stdout).into_owned(),
        String::from_utf8_lossy(&out.stderr).into_owned(),
        out.status.success(),
    )
}

fn ok(home: &std::path::Path, args: &[&str]) -> String {
    let (out, err, success) = pma_in(home, args);
    assert!(success, "pma {args:?} failed\nstdout: {out}\nstderr: {err}");
    out
}

#[test]
fn scan_rank_and_explain_a_real_repo() {
    let s = Scratch::new("stage2");
    let home = s.0.join("home");
    let root = s.0.join("root");
    let alpha = root.join("alpha");
    fs::create_dir_all(&alpha).unwrap();
    fs::create_dir_all(root.join("beta")).unwrap();
    git(&root.join("beta"), &["init", "-q"], None);

    // Committed 100 days ago: two items and a source file.
    git(&alpha, &["init", "-q"], None);
    fs::write(
        alpha.join("TODO.md"),
        "# TODO\n\n## High\n\n### core\n\n- [ ] old high\n\n## Low\n\n- [ ] old low\n",
    )
    .unwrap();
    fs::write(alpha.join("lib.rs"), "\n").unwrap();
    git(&alpha, &["add", "."], None);
    git(&alpha, &["commit", "-qm", "init"], Some(now() - 100 * DAY));
    // 50 days ago the low item was retagged. Its text is unchanged, so it keeps
    // its age; the commit only touched TODO.md, so it is not activity.
    fs::write(
        alpha.join("TODO.md"),
        "# TODO\n\n## High\n\n### core\n\n- [ ] old high\n\n## Low\n\n- [ ] old low #later\n",
    )
    .unwrap();
    git(&alpha, &["commit", "-qam", "retag"], Some(now() - 50 * DAY));
    // A branch left by a run the database no longer knows.
    git(&alpha, &["branch", "pma/stray"], None);
    // Not committed: a new item, which also leaves the tree dirty.
    fs::write(
        alpha.join("TODO.md"),
        "# TODO\n\n## High\n\n### core\n\n- [ ] old high\n- [ ] new high\n\n## Low\n\n- [ ] old low #later\n",
    )
    .unwrap();

    let (_, err, success) = pma_in(&home, &["scan"]);
    assert!(!success && err.contains("pma root add"), "{err}");
    let (_, err, success) = pma_in(&home, &["matrix"]);
    assert!(!success && err.contains("pma scan"), "{err}");

    ok(&home, &["root", "add", root.to_str().unwrap()]);
    ok(&home, &["tier", "alpha", "1"]);
    assert_eq!(ok(&home, &["tier", "alpha"]), "1\n");
    let (_, err, success) = pma_in(&home, &["tier", "alpha", "6"]);
    assert!(!success && err.contains("1 to 5"), "{err}");

    let scanned = ok(&home, &["scan", "--offline"]);
    assert_eq!(
        scanned.split(" in ").next(),
        Some("scanned 2 projects"),
        "{scanned}"
    );
    assert!(
        scanned.ends_with(": 1 with TODO.md, 3 open items\n"),
        "{scanned}"
    );

    let matrix = ok(&home, &["matrix", "--all"]);
    let expected = "\
Q1 Do right away: 0

Q2 Schedule for later: 2
  alpha:7  T1  high  open 100d  core  old high
  alpha:8  T1  high  open 0d    core  new high

Q3 Delegate or avoid: 0

Q4 Remove: 3
  alpha     T1  medium  open 0d    resolve local changes: 1 changed file, 1 leftover pma branch
  alpha:12  T1  low     open 100d  old low
  alpha     T1  low     open 70d   review project: no code commits in 100 days
";
    let (head, body) = matrix.split_once("\n\n").unwrap();
    assert_eq!(
        head,
        "last scan just now; 1 tiered projects, 1 untiered (pma tier <project> <1-5>)"
    );
    assert_eq!(body, expected);

    let status = ok(&home, &["status", "--explain"]);
    assert!(status.contains("\nalpha    1     0."), "{status}");
    assert!(
        status.contains("  ci        n/a     w=3         unknown: offline"),
        "{status}"
    );
    assert!(status.contains("open: 2 high, 1 low"), "{status}");

    // Lowering tier 1's multiplier makes its high items unimportant.
    ok(&home, &["config", "tiers.1", "0.3"]);
    assert_eq!(ok(&home, &["config", "tiers.1"]), "0.3\n");
    assert!(ok(&home, &["config"]).contains("tiers.1 = 0.3  (set)\n"));
    assert!(ok(&home, &["matrix", "-q", "q1"]).ends_with("Q1 Do right away: 0\n"));
    let (_, err, success) = pma_in(&home, &["config", "tiers.1", "much"]);
    assert!(
        !success && err.contains("tiers.1: expected a number"),
        "{err}"
    );
    ok(&home, &["config", "tiers.1", "--reset"]);
    assert!(ok(&home, &["matrix", "-q", "q2"]).contains("Q2 Schedule for later: 2\n"));

    // An untiered project joins the matrix once there is a tier for it.
    assert!(ok(&home, &["matrix"]).contains("1 untiered"));
    ok(&home, &["config", "default_tier", "5"]);
    let matrix = ok(&home, &["matrix"]);
    assert!(matrix.contains("2 tiered projects, 0 untiered"), "{matrix}");
    ok(&home, &["config", "default_tier", "--reset"]);

    // Age orders `pma stale`; it no longer moves anything into Q1.
    let stale = ok(&home, &["stale", "-n", "2"]);
    assert!(
        stale.contains("alpha:7   T1  high  open 100d  old high"),
        "{stale}"
    );
    assert!(stale.trim_end().ends_with("and 1 more"), "{stale}");

    // A rescan keeps the tier and each task's first sighting.
    ok(&home, &["scan", "--offline", "alpha"]);
    assert_eq!(ok(&home, &["tier", "alpha"]), "1\n");
}

/// A stand-in for `claude -p`: writes a file named by the task, tries to push,
/// and prints a result costing $0.10.
const FAKE_CLAUDE: &str = r#"#!/bin/sh
case "$2" in
  *"reviewer's feedback"*) echo hi > hello.txt ;;
  *"add greeting"*) echo hi > hello.txt ;;
  *"second task"*) echo two > second.txt ;;
  *"third task"*) echo three > third.txt ;;
esac
if git push -q origin HEAD:refs/heads/agent 2>/dev/null; then echo pushed; else echo blocked; fi >> "$PUSH_LOG"
echo '{"type":"result","subtype":"success","is_error":false,"result":"did it","total_cost_usd":0.1}'
"#;

/// A worker with no structured output and no allowlist: the exit status is
/// its only verdict and its cost is unknown. It also proves `{dir}` reaches a
/// worker that takes its directory as an argument.
const PLAIN_WORKER: &str = r#"#!/bin/sh
cd "$3" || exit 1
echo hi > hello.txt
echo "wrote hello.txt in $3"
"#;

/// A stand-in that strays: an untracked workflow, a rename out of scope, and
/// a deletion. Its own summary claims it only touched the manifest.
const STRAYING_CLAUDE: &str = r#"#!/bin/sh
mkdir -p .github/workflows
echo "on: push" > .github/workflows/ci.yml
echo bump >> Cargo.lock
git mv Makefile build.mk
git rm -q notes.txt
echo '{"type":"result","subtype":"success","is_error":false,"result":"updated Cargo.lock","total_cost_usd":0.1}'
"#;

struct Env {
    home: PathBuf,
    bin: PathBuf,
    push_log: PathBuf,
}

impl Env {
    fn command(&self, args: &[&str]) -> Command {
        let path = format!(
            "{}:{}",
            self.bin.display(),
            std::env::var("PATH").unwrap_or_default()
        );
        let mut cmd = Command::new(env!("CARGO_BIN_EXE_pma"));
        cmd.env("PMA_HOME", &self.home)
            .env("PATH", path)
            .env("PUSH_LOG", &self.push_log)
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_NOSYSTEM", "1")
            .env("GIT_AUTHOR_NAME", "u")
            .env("GIT_AUTHOR_EMAIL", "u@example.com")
            .env("GIT_COMMITTER_NAME", "u")
            .env("GIT_COMMITTER_EMAIL", "u@example.com")
            .args(args);
        cmd
    }

    fn run(&self, args: &[&str]) -> (String, String, bool) {
        let out = self.command(args).output().unwrap();
        (
            String::from_utf8_lossy(&out.stdout).into_owned(),
            String::from_utf8_lossy(&out.stderr).into_owned(),
            out.status.success(),
        )
    }

    fn ok(&self, args: &[&str]) -> String {
        let (out, err, success) = self.run(args);
        assert!(success, "pma {args:?} failed\nstdout: {out}\nstderr: {err}");
        out
    }
}

fn git_out(dir: &std::path::Path, args: &[&str]) -> String {
    let out = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(args)
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .output()
        .unwrap();
    String::from_utf8_lossy(&out.stdout).into_owned()
}

/// Installs `scripts` as executables on the `PATH` of a new `Env`, and a
/// tiered project `alpha` cloned from `origin.git`. Returns the env, origin
/// and the clone.
fn dispatch_env(s: &Scratch, scripts: &[(&str, &str)]) -> (Env, PathBuf, PathBuf) {
    use std::os::unix::fs::PermissionsExt;

    let bin = s.0.join("bin");
    fs::create_dir_all(&bin).unwrap();
    for (name, script) in scripts {
        fs::write(bin.join(name), script).unwrap();
        fs::set_permissions(bin.join(name), fs::Permissions::from_mode(0o755)).unwrap();
    }
    let env = Env {
        home: s.0.join("home"),
        bin,
        push_log: s.0.join("push.log"),
    };

    // origin holds three items and a test that needs hello.txt.
    let seed = s.0.join("seed");
    fs::create_dir_all(&seed).unwrap();
    git(&seed, &["init", "-q", "-b", "main"], None);
    fs::write(
        seed.join("TODO.md"),
        "# TODO\n\n## High\n\n- [ ] add greeting #agent\n  say hello in hello.txt\n- [ ] second task #agent gh:7\n- [ ] third task #agent\n\n## Low\n\n- [ ] guarded task #manual\n",
    )
    .unwrap();
    fs::write(seed.join("Makefile"), "test:\n\ttest -f hello.txt\n").unwrap();
    git(&seed, &["add", "."], None);
    git(&seed, &["commit", "-qm", "init"], None);
    let origin = s.0.join("origin.git");
    git(&s.0, &["clone", "-q", "--bare", "seed", "origin.git"], None);
    let root = s.0.join("root");
    fs::create_dir_all(&root).unwrap();
    git(&root, &["clone", "-q", "../origin.git", "alpha"], None);
    let alpha = root.join("alpha");

    env.ok(&["root", "add", root.to_str().unwrap()]);
    env.ok(&["tier", "alpha", "1"]);
    env.ok(&["scan", "--offline"]);
    (env, origin, alpha)
}

#[test]
fn dispatch_review_rework_and_ship() {
    let s = Scratch::new("stage3");
    let (env, origin, alpha) = dispatch_env(&s, &[("claude", FAKE_CLAUDE)]);
    env.ok(&["config", "publish", "push"]);

    // Both runs start from origin; the second fails its verify.
    let out = env.ok(&["dispatch", "--auto", "-n", "2"]);
    assert!(
        out.contains("#1 alpha: add greeting\n#2 alpha: second task\n"),
        "{out}"
    );
    assert!(
        out.ends_with("2 ready, 0 failed, $0.20 spent; see `pma review`\n"),
        "{out}"
    );
    assert_eq!(
        fs::read_to_string(&env.push_log).unwrap(),
        "blocked\nblocked\n"
    );
    let (_, err, success) = env.run(&["dispatch", "alpha:5"]);
    assert!(!success && err.contains("already has a run"), "{err}");

    let list = env.ok(&["review"]);
    assert!(
        list.contains("#1  ready  alpha  verify ok      $0.10"),
        "{list}"
    );
    assert!(
        list.contains("#2  ready  alpha  verify FAILED  $0.10"),
        "{list}"
    );
    let detail = env.ok(&["review", "1"]);
    assert!(detail.starts_with("#1 ready  alpha  Q2\n"), "{detail}");
    // Class B, a base that failed and a head that passes: the check
    // discriminates, so nothing objects.
    assert!(
        detail.contains("accept: every recorded gate is clean"),
        "{detail}"
    );
    assert!(list.contains("clean"), "{list}");
    // #2 failed its verify, so it is not.
    let failed = env.ok(&["review", "2"]);
    assert!(
        failed.contains("read this run because:\n  - verify failed at the head"),
        "{failed}"
    );
    // The test needs hello.txt, which the base does not have: the agent
    // fixed a failing tree rather than leaving a green one green.
    assert!(
        detail.contains("`make test`: base FAILED, head passed"),
        "{detail}"
    );
    assert!(detail.contains("+hi"), "{detail}");
    // #1 names hello.txt and carries a description, in a small repository
    // with a working check. #2 is two words with neither.
    assert!(detail.contains("2 of 5 (v1)"), "{detail}");
    assert!(failed.contains("4 of 5 (v1)"), "{failed}");
    let (out, _, _) = env.run(&["review", "2", "--approve"]);
    assert_eq!(out, "");

    // Rework keeps the worktree and adds the reviewer's fix.
    let out = env.ok(&["review", "2", "--rework", "tests need hello.txt"]);
    assert!(out.contains("verify ok  $0.20"), "{out}");

    // The rework does not overwrite the failed attempt that preceded it.
    let detail = env.ok(&["review", "2", "--minutes", "7"]);
    let attempts = detail
        .split_once("attempts:\n")
        .unwrap_or_default()
        .1
        .lines()
        .take(2)
        .collect::<Vec<_>>();
    assert!(attempts[0].contains("verify FAILED"), "{detail}");
    assert!(attempts[1].contains("verify passed"), "{detail}");
    assert!(
        detail.contains("reviewed") && detail.contains("7m00s"),
        "{detail}"
    );
    // A run seen twice sums its review time.
    let detail = env.ok(&["review", "2", "--minutes", "3"]);
    assert!(detail.contains("10m00s"), "{detail}");
    // One attempt says nothing the rows above it do not.
    assert!(!env.ok(&["review", "1"]).contains("attempts:"));

    env.ok(&["review", "1", "--approve"]);
    // Approving an approved run re-takes its evidence rather than refusing.
    env.ok(&["review", "2", "--approve"]);
    env.ok(&["review", "2", "--approve"]);
    let (_, err, success) = env.run(&["review", "9", "--approve"]);
    assert!(!success && err.contains("no run #9"), "{err}");

    // An item that exists only in the local file cannot be dispatched.
    let local = fs::read_to_string(alpha.join("TODO.md")).unwrap().replace(
        "- [ ] third task #agent\n",
        "- [ ] third task #agent\n- [ ] local only #agent\n",
    );
    fs::write(alpha.join("TODO.md"), local).unwrap();
    env.ok(&["scan", "--offline"]);
    let (_, err, success) = env.run(&["dispatch", "alpha:9"]);
    assert!(
        !success && err.contains("commit and push it first"),
        "{err}"
    );
    assert!(!env.home.join("worktrees/alpha/local-only").exists());

    // A rejected run leaves no worktree or branch.
    env.ok(&["dispatch", "alpha:8"]);
    env.ok(&["review", "3", "--reject"]);
    assert!(!env.home.join("worktrees/alpha/third-task").exists());
    assert_eq!(git_out(&alpha, &["branch", "--list", "pma/third-task"]), "");

    let out = env.ok(&["ship"]);
    assert!(out.contains("#1 alpha: pushed "), "{out}");
    assert!(out.contains("#2 alpha: pushed "), "{out}");
    let log = git_out(&origin, &["log", "--format=%B|", "main"]);
    assert!(
        log.starts_with("second task\n\nCloses #7\n|\nadd greeting\n|"),
        "{log:?}"
    );
    assert_eq!(
        git_out(&origin, &["show", "main:TODO.md"]),
        "# TODO\n\n## High\n\n- [x] add greeting #agent\n  say hello in hello.txt\n- [x] second task #agent gh:7\n- [ ] third task #agent\n\n## Low\n\n- [ ] guarded task #manual\n"
    );
    assert_eq!(git_out(&origin, &["show", "main:second.txt"]), "two\n");
    assert_eq!(git_out(&origin, &["branch", "--list", "agent"]), "");
    assert!(!env.home.join("worktrees/alpha/add-greeting").exists());
    assert_eq!(git_out(&alpha, &["branch", "--list", "pma/*"]), "");
    assert_eq!(env.ok(&["review"]), "no runs to review\n");
    assert_eq!(env.ok(&["ship"]), "nothing approved\n");

    // `third task` failed its verify and was then rejected, so it is not
    // dispatched again without an explicit reset.
    let (_, err, success) = env.run(&["dispatch", "alpha:8"]);
    assert!(
        !success && err.contains("2 attempts on `third task` were used without an accepted result"),
        "{err}"
    );

    // A run whose budget would exceed the batch's does not start, and a run
    // that never reached the agent consumes no attempt.
    env.ok(&["config", "batch_budget", "0.05"]);
    let out = env.ok(&["dispatch", "alpha:8", "--retry"]);
    assert!(
        out.contains("not started: batch budget $0.05 reached"),
        "{out}"
    );
    assert!(
        out.ends_with("0 ready, 1 failed, $0.00 spent; see `pma review`\n"),
        "{out}"
    );
    // Four runs: two shipped, `third task` rejected, and one refused at the
    // batch budget, which is not decided because no one judged it. One passed
    // on its first attempt and one after a rework, so four attempts in all,
    // and the refused run reported no cost.
    let report = env.ok(&["report"]);
    assert!(
        report.contains("67% of 3 decided runs accepted"),
        "{report}"
    );
    let b: Vec<&str> = report
        .lines()
        .find(|l| l.starts_with("B "))
        .unwrap()
        .split_whitespace()
        .collect();
    assert_eq!(
        &b[..8],
        ["B", "4", "1", "2", "2", "0", "4", "$0.40+1?"],
        "{report}"
    );
    assert!(report.contains("10m00s"), "review time: {report}");
    assert!(
        env.ok(&["report", "--by", "project"])
            .contains("by project"),
        "{report}"
    );
    let (_, err, ok) = env.run(&["report", "--by", "model"]);
    assert!(!ok && err.contains("unknown dimension `model`"), "{err}");

    // The budget refusal never reached the agent, so it consumed nothing:
    // rejecting it leaves one attempt against the task, not two, and no
    // second reset is needed.
    env.ok(&["config", "batch_budget", "5.0"]);
    env.ok(&["review", "4", "--reject"]);
    env.ok(&["dispatch", "alpha:8"]);
    env.ok(&["review", "5", "--reject"]);
}

/// A stand-in for `gh pr`, driven by files in `$PMA_HOME`: `pr-state` for
/// `pr view`, `pr-list` for an open pull request, `pr-create-fails`.
const FAKE_GH_PR: &str = r#"#!/bin/sh
case "$1 $2" in
  "pr create")
    if [ -e "$PMA_HOME/pr-create-fails" ]; then echo "HTTP 502" >&2; exit 1; fi
    echo "https://github.com/me/alpha/pull/1" ;;
  "pr list") if [ -e "$PMA_HOME/pr-list" ]; then cat "$PMA_HOME/pr-list"; fi ;;
  "pr view") cat "$PMA_HOME/pr-state" ;;
  *) echo "fake gh: unexpected $*" >&2; exit 1 ;;
esac
"#;

#[test]
fn a_pull_request_holds_its_task_until_merged_or_closed() {
    let s = Scratch::new("pr");
    let (env, origin, alpha) = dispatch_env(&s, &[("claude", FAKE_CLAUDE), ("gh", FAKE_GH_PR)]);
    let pr_state = env.home.join("pr-state");

    env.ok(&["dispatch", "alpha:5"]);
    env.ok(&["review", "1", "--approve"]);
    let out = env.ok(&["ship"]);
    assert_eq!(out, "#1 alpha: https://github.com/me/alpha/pull/1\n");
    assert_eq!(
        git_out(&origin, &["branch", "--list", "pma/*"]),
        "  pma/add-greeting\n"
    );

    fs::write(&pr_state, "OPEN\n").unwrap();
    assert!(env.ok(&["review"]).contains("#1  pr-open  alpha"));
    let out = env.ok(&["dispatch", "--auto", "-n", "1"]);
    assert!(out.contains("#2 alpha: second task"), "{out}");
    env.ok(&["review", "2", "--reject"]);
    let (_, err, success) = env.run(&["dispatch", "alpha:5"]);
    assert!(!success && err.contains("already has a run"), "{err}");
    let (_, err, success) = env.run(&["review", "1", "--reject"]);
    assert!(
        !success && err.contains("open pull request; merge or close it"),
        "{err}"
    );

    // A closed pull request frees the task. Its remote branch stays, so the
    // new run takes another name.
    fs::write(&pr_state, "CLOSED\n").unwrap();
    let out = env.ok(&["review"]);
    assert!(
        out.starts_with("#1 alpha: pull request closed without merging: https://"),
        "{out}"
    );
    let out = env.ok(&["dispatch", "alpha:5"]);
    assert!(out.contains("#3 alpha: add greeting"), "{out}");
    assert!(env.ok(&["review", "3"]).contains("pma/add-greeting-2 in"));

    env.ok(&["review", "3", "--approve"]);
    env.ok(&["ship"]);
    fs::write(&pr_state, "MERGED\n").unwrap();
    let out = env.ok(&["review"]);
    assert_eq!(
        out,
        "#3 alpha: pull request merged: https://github.com/me/alpha/pull/1\nno runs to review\n"
    );
    assert!(!alpha.join("hello.txt").exists(), "the clone is untouched");
}

#[test]
fn ship_resumes_after_a_partial_failure() {
    let s = Scratch::new("resume");
    let (env, origin, alpha) = dispatch_env(&s, &[("claude", FAKE_CLAUDE), ("gh", FAKE_GH_PR)]);
    env.ok(&["config", "publish", "push"]);

    // The push succeeds and removing the worktree fails.
    env.ok(&["dispatch", "alpha:5"]);
    env.ok(&["review", "1", "--approve"]);
    let worktree = env.home.join("worktrees/alpha/add-greeting");
    git(
        &alpha,
        &["worktree", "lock", worktree.to_str().unwrap()],
        None,
    );
    let out = env.ok(&["ship"]);
    assert!(
        out.starts_with("#1 alpha: pushed ") && out.contains("; warning: worktree not removed: "),
        "{out}"
    );
    assert_eq!(
        env.ok(&["review"]),
        "no runs to review\n",
        "shipped all the same"
    );

    // As if pma had stopped between the push and recording it.
    rusqlite::Connection::open(env.home.join("projects.db"))
        .unwrap()
        .execute("UPDATE runs SET state = 'approved' WHERE id = 1", [])
        .unwrap();
    git(
        &alpha,
        &["worktree", "unlock", worktree.to_str().unwrap()],
        None,
    );
    let out = env.ok(&["ship"]);
    assert!(out.starts_with("#1 alpha: already pushed "), "{out}");
    assert!(!worktree.exists());
    assert_eq!(
        git_out(&origin, &["log", "--format=%s", "main"]),
        "add greeting\ninit\n",
        "pushed once"
    );

    // `gh pr create` fails after the push; the retry finds the pull request.
    env.ok(&["config", "publish", "pr"]);
    env.ok(&["dispatch", "alpha:7"]);
    env.ok(&["review", "2", "--approve"]);
    fs::write(env.home.join("pr-create-fails"), "").unwrap();
    let (out, _, success) = env.run(&["ship"]);
    assert!(!success && out.contains("gh pr create: HTTP 502"), "{out}");
    assert!(env.ok(&["review"]).contains("#2  approved"));
    fs::remove_file(env.home.join("pr-create-fails")).unwrap();
    fs::write(
        env.home.join("pr-list"),
        "https://github.com/me/alpha/pull/9\n",
    )
    .unwrap();
    assert_eq!(
        env.ok(&["ship"]),
        "#2 alpha: https://github.com/me/alpha/pull/9\n"
    );
}

#[test]
fn auto_dispatch_passes_over_refused_tasks_and_names_the_cause() {
    let s = Scratch::new("refused");
    let (env, origin, alpha) = dispatch_env(&s, &[("claude", FAKE_CLAUDE)]);

    // The clone has an unpushed item first, and is behind a tick on origin.
    let todo = fs::read_to_string(alpha.join("TODO.md")).unwrap();
    fs::write(
        alpha.join("TODO.md"),
        todo.replace(
            "- [ ] add greeting",
            "- [ ] local only #agent\n- [ ] add greeting",
        ),
    )
    .unwrap();
    let other = s.0.join("other");
    git(
        &s.0,
        &["clone", "-q", origin.to_str().unwrap(), "other"],
        None,
    );
    let ticked = fs::read_to_string(other.join("TODO.md"))
        .unwrap()
        .replace("- [ ] third task", "- [x] third task");
    fs::write(other.join("TODO.md"), ticked).unwrap();
    git(&other, &["commit", "-qam", "tick"], None);
    git(&other, &["push", "-q"], None);
    env.ok(&["scan", "--offline"]);

    let (out, err, success) = env.run(&["dispatch", "--auto", "-n", "1"]);
    assert!(success, "{err}");
    assert!(
        err.contains("warning: alpha: `local only` is not in TODO.md on origin/main; commit and push it first"),
        "{err}"
    );
    assert!(out.starts_with("#1 alpha: add greeting\n"), "{out}");

    let (_, err, success) = env.run(&["dispatch", "alpha:9"]);
    assert!(
        !success && err.contains("`third task` is already done on origin/main; pull the clone"),
        "{err}"
    );

    // Class D: refused before any worktree exists.
    let (_, err, success) = env.run(&["dispatch", "alpha:13"]);
    assert!(
        !success && err.contains("`guarded task` is class D and is not dispatched"),
        "{err}"
    );
    assert!(!env.home.join("worktrees/alpha/guarded-task").exists());
    assert_eq!(
        git_out(&alpha, &["branch", "--list", "pma/guarded-task"]),
        ""
    );
}

/// Every path a run changed is checked, whatever the agent says it did and
/// whatever class the task was predicted to be. A deps task is class A, whose
/// scope is manifests alone.
#[test]
fn the_scope_check_reads_the_whole_change_not_the_agents_report() {
    let s = Scratch::new("scope");
    let (env, _, alpha) = dispatch_env(&s, &[("claude", STRAYING_CLAUDE)]);
    // The moved Makefile takes the test target with it; the scope check is
    // what this test is about.
    env.ok(&["config", "projects.alpha.verify", "none"]);
    fs::write(alpha.join("Cargo.lock"), "lock\n").unwrap();
    fs::write(alpha.join("notes.txt"), "notes\n").unwrap();
    git(&alpha, &["add", "Cargo.lock", "notes.txt"], None);
    git(&alpha, &["commit", "-qm", "lock"], None);
    git(&alpha, &["push", "-q"], None);
    env.ok(&["scan", "--offline"]);
    env.ok(&["dispatch", "alpha:5"]);

    // Five paths from four edits: the untracked workflow, the edited lock
    // file, both sides of the rename, and the deletion. The agent reported
    // only the lock file.
    let detail = env.ok(&["review", "1"]);
    assert!(detail.contains("B, any path"), "{detail}");
    assert!(
        detail.contains("1 of 5 files OUTSIDE: .github/workflows/ci.yml"),
        "{detail}"
    );
    assert!(detail.contains("updated Cargo.lock"), "{detail}");
    // Without a verify command there is no acceptance, whatever the scope.
    assert!(
        detail.contains("  - outside class B: .github/workflows/ci.yml"),
        "{detail}"
    );
    assert!(detail.contains("  - no verify command"), "{detail}");
    assert!(env.ok(&["review"]).contains("2 to read"), "{detail}");
}

/// A second worker runs through the same dispatch, review and ship path as
/// `claude`, with no code that knows its name.
#[test]
fn a_worker_without_json_output_or_an_allowlist_runs_the_same_path() {
    let s = Scratch::new("adapter");
    let (env, origin, _) = dispatch_env(&s, &[("plain", PLAIN_WORKER)]);
    env.ok(&["config", "publish", "push"]);

    let listed = env.ok(&["agent"]);
    assert!(listed.contains("* claude"), "{listed}");
    assert!(listed.contains("cost,allowlist"), "{listed}");

    env.ok(&["agent", "set", "plain", "command", "plain"]);
    env.ok(&[
        "agent",
        "set",
        "plain",
        "args",
        r#"["--task","{prompt}","{dir}"]"#,
    ]);
    env.ok(&["config", "agent", "plain"]);
    let listed = env.ok(&["agent"]);
    assert!(listed.contains("* plain"), "{listed}");
    assert!(listed.contains("text-tail"), "{listed}");

    env.ok(&["dispatch", "alpha:5"]);
    let detail = env.ok(&["review", "1"]);
    // The exit status decided, the tail is the summary, and the cost is
    // unknown rather than zero.
    assert!(detail.contains("plain, cost not reported"), "{detail}");
    assert!(detail.contains("wrote hello.txt in"), "{detail}");
    assert!(
        detail.contains("`make test`: base FAILED, head passed"),
        "{detail}"
    );
    assert!(
        detail.contains("accept: every recorded gate is clean"),
        "{detail}"
    );

    env.ok(&["review", "1", "--approve"]);
    assert!(env.ok(&["ship"]).contains("#1 alpha: pushed "), "shipped");
    assert_eq!(git_out(&origin, &["show", "main:hello.txt"]), "hi\n");
    // No cost to sum, and `--by agent` names the worker that did the work.
    let report = env.ok(&["report", "--by", "agent"]);
    assert!(report.contains("plain"), "{report}");
    assert!(report.contains("$0.00+1?"), "{report}");

    // A run whose worker was removed says so rather than running nothing.
    env.ok(&["agent", "rm", "plain"]);
    env.ok(&["dispatch", "alpha:7"]);
    let detail = env.ok(&["review", "2"]);
    assert!(detail.contains("unknown agent `plain`"), "{detail}");

    let (_, err, ok) = env.run(&["agent", "set", "x", "parse", "codex-json"]);
    assert!(!ok && err.contains("unknown parser `codex-json`"), "{err}");
    let (_, err, ok) = env.run(&["agent", "set", "x", "args", "not json"]);
    assert!(!ok && err.contains("JSON array"), "{err}");
}

/// A worker that reports which model it was given, so a route's choice can
/// be seen from outside.
const MODEL_CLAUDE: &str = r#"#!/bin/sh
model=unset
while [ $# -gt 0 ]; do
  case "$1" in --model) model="$2" ;; esac
  shift
done
echo hi > hello.txt
printf '{"type":"result","subtype":"success","is_error":false,"result":"ran as %s","total_cost_usd":0.1}\n' "$model"
"#;

/// A worker that adds the file a campaign asks for, and fails in one named
/// repository so a partial campaign can be restarted.
const CAMPAIGN_WORKER: &str = r#"#!/bin/sh
if [ "$(basename "$(dirname "$PWD")")" = "beta" ] && [ ! -e "$PMA_HOME/fixed" ]; then
  printf '{"type":"result","subtype":"error","is_error":true,"result":"gave up","total_cost_usd":0.1}
'
  exit 0
fi
mkdir -p .github/workflows
echo "on: push" > .github/workflows/ci.yml
printf '{"type":"result","subtype":"success","is_error":false,"result":"added the workflow","total_cost_usd":0.1}
'
"#;

/// One definition, three independent repositories, one worktree each,
/// verified separately, reviewed as a batch. A restart dispatches only the
/// members that have no live run.
#[test]
fn a_campaign_applies_one_definition_across_repositories() {
    let s = Scratch::new("campaign");
    let (env, _, _) = dispatch_env(&s, &[("claude", CAMPAIGN_WORKER)]);
    // Two more repositories from the same seed, independent of each other.
    let root = s.0.join("root");
    for name in ["beta", "gamma"] {
        git(&root, &["clone", "-q", "../origin.git", name], None);
        env.ok(&["tier", name, "3"]);
    }
    env.ok(&["scan", "--offline"]);
    // The seed's `make test` needs hello.txt, which a workflow campaign has
    // no business creating; a check that passes at both ends is what class
    // A- work is accepted against.
    for name in ["alpha", "beta", "gamma"] {
        env.ok(&["config", &format!("projects.{name}.verify"), "true"]);
    }

    assert!(env.ok(&["campaign"]).contains("no campaigns"), "empty");
    env.ok(&[
        "campaign",
        "add",
        "workflows",
        "add a workflow",
        "--projects",
        "alpha,beta,gamma",
        "--class",
        "A-",
        "--describe",
        "Create .github/workflows/ci.yml that runs on push.",
    ]);
    let listed = env.ok(&["campaign"]);
    assert!(
        listed.contains("class A-") && listed.contains("0/3 dispatched"),
        "{listed}"
    );

    // beta's agent gives up, so two of three produce a run to review.
    let out = env.ok(&["campaign", "run", "workflows"]);
    assert!(out.contains("2 ready, 1 failed"), "{out}");
    let show = env.ok(&["campaign", "show", "workflows"]);
    assert!(
        show.starts_with(
            "workflows: add a workflow
"
        ),
        "{show}"
    );
    assert!(show.contains("failed"), "{show}");

    // A- may edit `.github/**` and nothing else, so both are clean.
    let detail = env.ok(&["review", "1"]);
    assert!(detail.contains("A-, within .github/**"), "{detail}");
    assert!(detail.contains("1 files, all permitted"), "{detail}");
    assert!(detail.contains("base passed, head passed"), "{detail}");
    assert!(detail.contains("every recorded gate is clean"), "{detail}");

    // Batched review: one context across the repositories.
    let ready: Vec<String> = env
        .ok(&["review"])
        .lines()
        .filter(|l| l.contains(" ready "))
        .map(|l| l.split_whitespace().next().unwrap()[1..].to_string())
        .collect();
    assert_eq!(ready.len(), 2, "two runs to approve");
    let mut args = vec!["review"];
    args.extend(ready.iter().map(String::as_str));
    args.push("--approve");
    let approved = env.ok(&args);
    assert_eq!(approved.lines().count(), 2, "{approved}");

    // A member whose run failed is named, not dispatched over: its worktree
    // is still there and the reviewer decides what happens to it.
    let out = env.ok(&["campaign", "run", "workflows"]);
    assert!(
        out.contains("beta: #2 is failed; reject or rework it"),
        "{out}"
    );
    assert!(
        out.contains("every member of `workflows` has a run"),
        "{out}"
    );

    // Once it is rejected, a restart dispatches that member and no other.
    fs::write(env.home.join("fixed"), "").unwrap();
    env.ok(&["review", "2", "--reject"]);
    let out = env.ok(&["campaign", "run", "workflows"]);
    assert!(out.contains("1 ready, 0 failed"), "{out}");
    assert_eq!(out.matches(": add a workflow").count(), 1, "{out}");
    let show = env.ok(&["campaign", "show", "workflows"]);
    assert_eq!(show.matches("approved").count(), 2, "{show}");
    assert_eq!(show.matches("ready").count(), 1, "{show}");

    // Every member has a run, so there is nothing left to start.
    env.ok(&["review", "3", "--approve"]);
    let out = env.ok(&["campaign", "run", "workflows"]);
    assert!(
        out.contains("every member of `workflows` has a run"),
        "{out}"
    );
}

/// Approval names a tree. Ship publishes that tree or nothing, and rechecks
/// what the rebase produced rather than what was approved in isolation.
#[test]
fn an_approval_is_evidence_about_a_tree_not_a_state() {
    let s = Scratch::new("evidence");
    let (env, origin, alpha) = dispatch_env(&s, &[("claude", FAKE_CLAUDE)]);
    env.ok(&["config", "publish", "push"]);

    // A worktree edited after approval is not published.
    env.ok(&["dispatch", "alpha:5"]);
    env.ok(&["review", "1", "--approve"]);
    let worktree = env.home.join("worktrees/alpha/add-greeting");
    fs::write(worktree.join("sneaked.txt"), "later\n").unwrap();
    let (out, err, success) = env.run(&["ship"]);
    assert!(!success, "{out}{err}");
    assert!(
        out.contains("the worktree changed after it was approved"),
        "{out}"
    );
    assert_eq!(git_out(&origin, &["log", "--format=%s", "main"]), "init\n");

    // Reviewing it again approves the tree that is actually there.
    fs::remove_file(worktree.join("sneaked.txt")).unwrap();
    env.ok(&["review", "1", "--approve"]);
    assert!(env.ok(&["ship"]).contains("#1 alpha: pushed "), "shipped");

    // A rework withdraws an approval: the approver read another tree.
    env.ok(&["dispatch", "alpha:7"]);
    env.ok(&["review", "2", "--approve"]);
    env.ok(&["review", "2", "--rework", "add hello.txt too"]);
    let detail = env.ok(&["review", "2"]);
    assert!(!detail.contains("approved by"), "{detail}");

    // The integrated tree is checked, not the approved one in isolation:
    // another commit lands upstream that the approved change breaks.
    env.ok(&["review", "2", "--approve"]);
    let other = s.0.join("other");
    git(
        &s.0,
        &["clone", "-q", origin.to_str().unwrap(), "other"],
        None,
    );
    fs::write(other.join("Makefile"), "test:\n\ttest -f never.txt\n").unwrap();
    git(&other, &["commit", "-qam", "stricter test"], None);
    git(&other, &["push", "-q"], None);
    let (out, err, success) = env.run(&["ship"]);
    assert!(!success, "{out}{err}");
    assert!(
        out.contains("`make test` failed on the integrated tree"),
        "{out}"
    );
    assert_eq!(
        git_out(&origin, &["log", "--format=%s", "main"]),
        "stricter test\nadd greeting\ninit\n",
        "nothing of the run reached the branch"
    );
    let _ = alpha;
}

/// A batch approval is all or nothing, and only for runs nothing objects to.
#[test]
fn a_batch_approval_refuses_a_list_with_anything_to_read_in_it() {
    let s = Scratch::new("batch");
    let (env, _, _) = dispatch_env(&s, &[("claude", FAKE_CLAUDE)]);
    env.ok(&["dispatch", "--auto", "-n", "3"]);
    let list = env.ok(&["review"]);
    assert!(list.contains("clean"), "{list}");

    // #2 and #3 fail their checks, so the list is refused whole.
    let (_, err, success) = env.run(&["review", "1", "2", "--approve"]);
    assert!(!success && err.contains("#2 is not clean"), "{err}");
    assert!(err.contains("verify failed at the head"), "{err}");
    assert_eq!(
        env.ok(&["review"]).matches("ready").count(),
        3,
        "nothing was approved"
    );

    // A propose route publishes nothing, whatever the gates say.
    let doc = s.0.join("policy.json");
    fs::write(
        &doc,
        r#"{"route":[{"name":"draft-only","match":{},"approval":"propose"}]}"#,
    )
    .unwrap();
    env.ok(&["route", "propose", doc.to_str().unwrap()]);
    env.ok(&["route", "activate", "1"]);
    env.ok(&["review", "1", "--reject"]);
    env.ok(&["dispatch", "alpha:5", "--retry"]);
    let (_, err, success) = env.run(&["review", "4", "--approve"]);
    assert!(!success && err.contains("which is `propose`"), "{err}");
}

/// Fails its check at the first model and passes at the second, so a route's
/// escalation can be seen end to end.
const ESCALATING_CLAUDE: &str = r#"#!/bin/sh
model=unset
while [ $# -gt 0 ]; do
  case "$1" in --model) model="$2" ;; esac
  shift
done
if [ "$model" = "opus" ]; then echo hi > hello.txt; fi
printf '{"type":"result","subtype":"success","is_error":false,"result":"ran as %s","total_cost_usd":0.1}
' "$model"
"#;

/// A route may retry once at a stronger model where the check itself refused
/// the work. Each attempt is recorded with the model it ran.
#[test]
fn a_failed_check_escalates_once_and_records_both_attempts() {
    let s = Scratch::new("escalate");
    let (env, _, _) = dispatch_env(&s, &[("claude", ESCALATING_CLAUDE)]);
    let doc = s.0.join("policy.json");
    fs::write(
        &doc,
        r#"{"route":[{"name":"try-twice","match":{},"model":"haiku",
             "escalate":{"model":"opus","attempts":1},"approval":"each"}]}"#,
    )
    .unwrap();
    env.ok(&["route", "propose", doc.to_str().unwrap()]);
    env.ok(&["route", "activate", "1"]);

    env.ok(&["dispatch", "alpha:5"]);
    let detail = env.ok(&["review", "1"]);
    assert!(detail.contains("base FAILED, head passed"), "{detail}");
    let attempts = detail.split_once("attempts:\n").expect("two attempts").1;
    let lines: Vec<&str> = attempts.lines().take(2).collect();
    assert!(
        lines[0].contains("haiku") && lines[0].contains("verify FAILED"),
        "{detail}"
    );
    assert!(
        lines[1].contains("opus") && lines[1].contains("verify passed"),
        "{detail}"
    );
    // The refused check consumed one attempt; the one that passed did not.
    let (_, err, success) = env.run(&["dispatch", "alpha:5"]);
    assert!(!success && err.contains("already has a run"), "{err}");

    // The run's cost is both attempts. Its `model` stays what the route
    // chose at dispatch: the snapshot records the decision, and the attempt
    // records what actually ran.
    assert!(detail.contains("claude haiku, $0.20"), "{detail}");
}

/// A policy is an artifact: proposed, reviewed, activated, and applied
/// deterministically. Replaying it over recorded runs must reproduce what
/// they were routed to.
#[test]
fn a_policy_is_a_draft_until_activated_and_replays_exactly() {
    let s = Scratch::new("route");
    let (env, _, _) = dispatch_env(&s, &[("claude", MODEL_CLAUDE)]);
    assert!(env.ok(&["route"]).contains("no routing policy"), "empty");

    let doc = s.0.join("policy.json");
    fs::write(
        &doc,
        r#"{"route":[
             {"name":"specified","match":{"class":"B","complexity":"1-3"},
              "model":"haiku","approval":"batch"},
             {"name":"rest","match":{},"model":"opus","approval":"each"}
           ]}"#,
    )
    .unwrap();
    let out = env.ok(&["route", "propose", doc.to_str().unwrap(), "--by", "me"]);
    assert!(out.contains("revision 1 stored as a draft"), "{out}");
    assert!(env.ok(&["route"]).contains("draft"), "still a draft");

    // One task throughout: `add greeting` names hello.txt and carries a
    // description, so it estimates 2 and matches the first route.
    // A draft does not route: the run takes the settings, as before.
    env.ok(&["dispatch", "alpha:5"]);
    let detail = env.ok(&["review", "1"]);
    assert!(detail.contains("ran as unset"), "{detail}");
    assert!(!detail.contains("revision 1"), "{detail}");
    env.ok(&["review", "1", "--reject"]);

    // Shadow records the route without applying it.
    env.ok(&["route", "activate", "1", "--shadow", "--by", "me"]);
    env.ok(&["dispatch", "alpha:5", "--retry"]);
    let detail = env.ok(&["review", "2"]);
    assert!(detail.contains("specified in revision 1"), "{detail}");
    assert!(detail.contains("approval batch"), "{detail}");
    assert!(detail.contains("ran as unset"), "shadow applies nothing");
    env.ok(&["review", "2", "--reject"]);

    // Activated, the same task takes the route's model.
    env.ok(&["route", "activate", "1", "--by", "me"]);
    assert!(env.ok(&["route"]).contains("active, by me"), "activated");
    env.ok(&["dispatch", "alpha:5", "--retry"]);
    let detail = env.ok(&["review", "3"]);
    assert!(detail.contains("ran as haiku"), "{detail}");

    // The gate: replaying the active policy changes nothing it decided.
    // #1 predates it and #2 was shadowed, so neither took the route's model;
    // both are differences worth seeing rather than matches.
    let replay = env.ok(&["route", "replay", "1"]);
    assert!(
        replay.contains("3 runs replayed, 2 routed differently"),
        "{replay}"
    );
    assert!(replay.contains("#1"), "dispatched before it: {replay}");
    assert!(replay.contains("#2"), "shadowed, so not applied: {replay}");
    assert!(!replay.contains("#3"), "applied, so unchanged: {replay}");
    assert!(replay.contains("Cost is not projected"), "{replay}");

    // A candidate that narrows the first route moves runs onto the second.
    let other = s.0.join("other.json");
    fs::write(
        &other,
        r#"{"route":[
             {"name":"specified","match":{"class":"B","complexity":"1-1"},
              "model":"haiku","approval":"batch"},
             {"name":"rest","match":{},"model":"opus","approval":"each"}
           ]}"#,
    )
    .unwrap();
    let replay = env.ok(&["route", "replay", other.to_str().unwrap()]);
    assert!(
        replay.contains("3 runs replayed, 3 routed differently"),
        "{replay}"
    );
    assert!(replay.contains("rest claude/opus"), "{replay}");

    // A policy that matches nothing refuses the dispatch by name.
    let narrow = s.0.join("narrow.json");
    fs::write(
        &narrow,
        r#"{"route":[{"name":"only-a","match":{"class":"A"},"approval":"each"}]}"#,
    )
    .unwrap();
    env.ok(&["route", "propose", narrow.to_str().unwrap()]);
    env.ok(&["route", "activate", "2"]);
    env.ok(&["review", "3", "--reject"]);
    let (_, err, success) = env.run(&["dispatch", "alpha:5", "--retry"]);
    assert!(
        !success && err.contains("matches no route in policy revision 2"),
        "{err}"
    );

    // An unreadable document never becomes a revision.
    let bad = s.0.join("bad.json");
    fs::write(&bad, r#"{"route":[{"match":{},"approval":"whenever"}]}"#).unwrap();
    let (_, err, success) = env.run(&["route", "propose", bad.to_str().unwrap()]);
    assert!(
        !success && err.contains("unknown approval `whenever`"),
        "{err}"
    );
    assert_eq!(env.ok(&["route"]).lines().count(), 2, "still two revisions");
}

/// A stand-in for `claude -p` that finishes once `$PMA_HOME/release` exists,
/// or after about 60s.
const SLOW_CLAUDE: &str = r#"#!/bin/sh
n=0
while [ ! -e "$PMA_HOME/release" ] && [ $n -lt 1200 ]; do sleep 0.05; n=$((n + 1)); done
echo hi > hello.txt
echo '{"type":"result","subtype":"success","is_error":false,"result":"did it","total_cost_usd":0.1}'
"#;

#[test]
fn a_second_session_leaves_running_runs_alone() {
    let s = Scratch::new("session");
    let (env, _, _) = dispatch_env(&s, &[("claude", SLOW_CLAUDE)]);

    /// Releases the agent when the test ends, passing or not.
    struct Release(PathBuf);
    impl Drop for Release {
        fn drop(&mut self) {
            let _ = fs::write(&self.0, "");
        }
    }
    let release = Release(env.home.join("release"));

    // Piped, so a failed test does not wait on the child holding its output.
    let mut dispatch = env
        .command(&["dispatch", "alpha:5"])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .unwrap();
    let started = std::time::Instant::now();
    let mut last = String::new();
    while !last.contains("#1  running") {
        if dispatch.try_wait().unwrap().is_some() || started.elapsed().as_secs() >= 30 {
            let _ = dispatch.kill();
            let out = dispatch.wait_with_output().unwrap();
            panic!(
                "the run never started; review: {last}\ndispatch: {}{}",
                String::from_utf8_lossy(&out.stdout),
                String::from_utf8_lossy(&out.stderr)
            );
        }
        std::thread::sleep(std::time::Duration::from_millis(50));
        last = env.ok(&["review"]);
    }

    assert!(
        env.ok(&["review"]).contains("#1  running"),
        "review does not fail a live run"
    );
    for args in [
        &["dispatch", "alpha:6"][..],
        &["ship"],
        &["review", "1", "--reject"],
    ] {
        let (_, err, success) = env.run(args);
        assert!(
            !success && err.contains("another pma session (pid "),
            "{args:?}: {err}"
        );
    }

    drop(release);
    let out = dispatch.wait_with_output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        out.status.success() && stdout.contains("1 ready, 0 failed"),
        "{stdout}"
    );
    assert!(env.ok(&["review"]).contains("#1  ready"));
    env.ok(&["review", "1", "--reject"]);
}

/// A stand-in for `gh` backed by `issues.json`; mutating calls are logged.
const FAKE_GH: &str = r#"#!/usr/bin/env python3
import json, os, sys
state = os.environ["GH_STATE"]
issues = json.load(open(state))
args = sys.argv[1:]
def opt(name):
    return args[args.index(name) + 1] if name in args else None
def log(line):
    with open(state + ".log", "a") as f:
        f.write(line + "\n")
if args[:2] == ["api", "user"]:
    print("me")
elif args[:2] == ["issue", "list"]:
    print(json.dumps([dict(i, author={"login": i["author"]}, labels=[{"name": l} for l in i["labels"]]) for i in issues]))
elif args[:2] == ["label", "create"]:
    log("label create " + args[2])
elif args[:2] == ["issue", "create"]:
    n = max([i["number"] for i in issues] + [0]) + 1
    issues.append({"number": n, "title": opt("--title"), "state": "OPEN", "author": "me", "labels": [opt("--label")]})
    log("issue create %d %s | %s" % (n, opt("--title"), opt("--body")))
    print("https://github.com/me/alpha/issues/%d" % n)
elif args[:2] == ["issue", "edit"]:
    issue = next(i for i in issues if i["number"] == int(args[2]))
    if opt("--title"):
        issue["title"] = opt("--title")
    if opt("--add-label"):
        issue["labels"].append(opt("--add-label"))
    if opt("--remove-label"):
        issue["labels"].remove(opt("--remove-label"))
    log("issue edit " + " ".join(args[2:]))
else:
    sys.exit("fake gh: unexpected " + " ".join(args))
json.dump(issues, open(state, "w"))
"#;

#[test]
fn sync_plans_then_applies_and_settles() {
    use std::os::unix::fs::PermissionsExt;

    let s = Scratch::new("stage4");
    let bin = s.0.join("bin");
    fs::create_dir_all(&bin).unwrap();
    fs::write(bin.join("gh"), FAKE_GH).unwrap();
    fs::set_permissions(bin.join("gh"), fs::Permissions::from_mode(0o755)).unwrap();
    let state = s.0.join("issues.json");
    fs::write(
        &state,
        r#"[{"number": 1, "title": "fixed elsewhere", "state": "CLOSED", "author": "me", "labels": []},
            {"number": 2, "title": "old crash title", "state": "OPEN", "author": "me", "labels": ["pma:critical"]},
            {"number": 3, "title": "please add X", "state": "OPEN", "author": "alice", "labels": []}]"#,
    )
    .unwrap();
    let home = s.0.join("home");
    let root = s.0.join("root");
    let alpha = s.project(
        "root/alpha",
        "# TODO\n\n## Critical\n\n- [ ] segfault on empty input\n  when stdin is empty\n- [ ] renamed crash gh:2\n\n## High\n\n- [ ] fixed elsewhere gh:1\n",
    );
    git(&alpha, &["init", "-q"], None);
    git(
        &alpha,
        &["remote", "add", "origin", "https://github.com/me/alpha.git"],
        None,
    );
    let beta = s.project("root/beta", "## High\n");
    git(&beta, &["init", "-q"], None);

    let sync = |args: &[&str]| {
        let out = Command::new(env!("CARGO_BIN_EXE_pma"))
            .env("PMA_HOME", &home)
            .env(
                "PATH",
                format!("{}:{}", bin.display(), std::env::var("PATH").unwrap()),
            )
            .env("GH_STATE", &state)
            .args(args)
            .output()
            .unwrap();
        (
            String::from_utf8_lossy(&out.stdout).into_owned(),
            String::from_utf8_lossy(&out.stderr).into_owned(),
        )
    };
    sync(&["root", "add", root.to_str().unwrap()]);
    sync(&["scan", "--offline"]);

    let original = fs::read_to_string(alpha.join("TODO.md")).unwrap();
    let (out, err) = sync(&["sync"]);
    assert_eq!(
        out,
        "alpha:5: open an issue for `segfault on empty input`\n\
         alpha: retitle #2 to `renamed crash`\n\
         alpha:11: mark done, #1 is closed\n\
         alpha: untriaged #3 by alice: please add X\n\
         beta: skipped: TODO.md has lint errors; see `pma lint`\n\
         3 changes; run `pma sync --apply` to make them\n",
        "{err}"
    );
    assert_eq!(fs::read_to_string(alpha.join("TODO.md")).unwrap(), original);
    assert!(
        !s.0.join("issues.json.log").exists(),
        "a dry run changes nothing"
    );

    let (out, err) = sync(&["sync", "--apply", "alpha"]);
    assert!(
        out.ends_with(
            "3 changes made\nTODO.md changed, uncommitted, in: alpha; commit, then `pma scan`\n"
        ),
        "{out}{err}"
    );
    assert_eq!(
        fs::read_to_string(s.0.join("issues.json.log")).unwrap(),
        "label create pma:critical\n\
         issue create 4 segfault on empty input | when stdin is empty\n\n\
         Opened by pma from a `## Critical` item in TODO.md.\n\
         issue edit 2 -R me/alpha --title renamed crash\n"
    );
    assert_eq!(
        fs::read_to_string(alpha.join("TODO.md")).unwrap(),
        "# TODO\n\n## Critical\n\n- [ ] segfault on empty input gh:4\n  when stdin is empty\n- [ ] renamed crash gh:2\n\n## High\n\n- [x] fixed elsewhere gh:1\n"
    );

    let (out, _) = sync(&["sync", "alpha"]);
    assert_eq!(out, "alpha: untriaged #3 by alice: please add X\nin sync\n");
}

#[test]
fn notes_and_measured_dependencies() {
    use std::os::unix::fs::PermissionsExt;

    let s = Scratch::new("stage5");
    let home = s.0.join("home");
    let bin = s.0.join("bin");
    fs::create_dir_all(&bin).unwrap();
    fs::write(
        bin.join("uv"),
        "#!/bin/sh\nprintf 'alpha v1\\n|-- ruff v0.14.10 (group: dev) (latest: v0.16.7)\\n`-- ty v0.0.8 (latest: v0.0.81)\\n'\n",
    )
    .unwrap();
    fs::set_permissions(bin.join("uv"), fs::Permissions::from_mode(0o755)).unwrap();
    let run = |args: &[&str]| {
        let out = Command::new(env!("CARGO_BIN_EXE_pma"))
            .env("PMA_HOME", &home)
            .env(
                "PATH",
                format!("{}:{}", bin.display(), std::env::var("PATH").unwrap()),
            )
            .args(args)
            .output()
            .unwrap();
        (
            String::from_utf8_lossy(&out.stdout).into_owned(),
            String::from_utf8_lossy(&out.stderr).into_owned(),
            out.status.success(),
        )
    };
    let ok = |args: &[&str]| {
        let (out, err, success) = run(args);
        assert!(success, "pma {args:?}: {err}");
        out
    };

    assert_eq!(
        ok(&["note"]),
        "no notes; add one with `pma note add <text>`\n"
    );
    assert_eq!(
        ok(&["note", "add", "move", "CI", "to", "one", "workflow"]),
        "#1\n"
    );
    assert_eq!(ok(&["note", "add", "second"]), "#2\n");
    ok(&["note", "edit", "1", "move CI to reusable workflows"]);
    ok(&["note", "rm", "2"]);
    let (_, err, success) = run(&["note", "rm", "2"]);
    assert!(!success && err.contains("no note #2"), "{err}");
    let list = ok(&["note"]);
    assert!(list.starts_with("#1  20"), "{list}");
    assert!(
        list.ends_with("  move CI to reusable workflows\n"),
        "{list}"
    );

    let root = s.0.join("root");
    let alpha = s.project("root/alpha", "# TODO\n\n## High\n");
    git(&alpha, &["init", "-q"], None);
    fs::write(alpha.join("uv.lock"), "").unwrap();
    ok(&["root", "add", root.to_str().unwrap()]);
    ok(&["tier", "alpha", "1"]);
    ok(&["scan", "--offline"]);
    assert!(ok(&["status", "--explain"]).contains("not measured; `pma scan --deps`"));
    let (_, err, success) = run(&["dispatch", "alpha:deps"]);
    assert!(
        !success && err.contains("no outdated dependencies"),
        "{err}"
    );

    let scanned = ok(&["scan", "--deps"]);
    assert!(
        scanned.ends_with(", outdated dependencies in 1\n"),
        "{scanned}"
    );
    ok(&["scan", "--offline"]);
    let status = ok(&["status", "--explain"]);
    assert!(
        status.contains("2 outdated, measured today"),
        "kept: {status}"
    );
    assert!(
        ok(&["matrix", "--all"])
            .contains("alpha  T1  medium  open 0d  update dependencies: 2 outdated"),
        "the deps signal task"
    );
}

/// A worker that reports the model it was handed, so a test can see which one
/// dispatch chose. With no model the placeholder is dropped and `$4` is empty.
const MODEL_WORKER: &str = r#"#!/bin/sh
cd "$3" || exit 1
echo hi > hello.txt
echo "model=$4"
# Whatever a preset added arrives after the model, so the test can see it.
shift 4 2>/dev/null || shift $#
while [ $# -gt 0 ]; do
  case "$1" in --thinking) echo "thinking=$2"; shift ;; esac
  shift
done
"#;

/// One target can name a heading or a quadrant. A task that cannot run holds
/// up only itself, where a target naming one task is an error.
#[test]
fn a_target_can_name_a_heading_or_a_quadrant() {
    let s = Scratch::new("select");
    let (env, _, _) = dispatch_env(&s, &[("claude", FAKE_CLAUDE)]);

    let (_, err, success) = env.run(&["dispatch", "-a", "pi", "alpha:5"]);
    assert!(
        !success && err.contains("unknown agent `pi`; `pma agent` lists claude"),
        "{err}"
    );
    let (_, err, success) = env.run(&["dispatch", "alpha:soon"]);
    assert!(
        !success && err.contains("expected a TODO.md line, ci, deps, critical"),
        "{err}"
    );
    let (_, err, success) = env.run(&["dispatch", "alpha:critical"]);
    assert!(
        !success && err.contains("alpha: no open critical items at the last scan"),
        "{err}"
    );
    // A list needs a terminal; the test harness has none.
    let (_, err, success) = env.run(&["dispatch", "alpha"]);
    assert!(
        !success && err.contains("opens a list, which needs a terminal"),
        "{err}"
    );

    // Tier 1 high items are important and not urgent: the whole of Q2.
    let out = env.ok(&["dispatch", "alpha:q2"]);
    assert!(
        out.starts_with("#1 alpha: add greeting\n#2 alpha: second task\n#3 alpha: third task\n"),
        "{out}"
    );

    // The same three by heading now: each is passed over with its reason,
    // rather than the first one ending the batch.
    let (_, err, success) = env.run(&["dispatch", "alpha:high"]);
    assert!(
        !success && err.ends_with("pma: nothing to dispatch: every task named was passed over\n"),
        "{err}"
    );
    assert_eq!(err.matches("already has a run").count(), 3, "{err}");
    assert!(err.contains("warning: alpha:5: already has a run"), "{err}");

    // The one Low item is #manual, so the heading selects nothing runnable.
    let (_, err, success) = env.run(&["dispatch", "alpha:low"]);
    assert!(
        !success && err.contains("`guarded task` is class D and is not dispatched"),
        "{err}"
    );
}
/// A worker is how to run a program; which model it runs at is a preset. The
/// retired field says so rather than failing as unknown.
#[test]
fn a_worker_no_longer_names_a_model() {
    let s = Scratch::new("flags");
    let (env, _, _) = dispatch_env(&s, &[("mw", MODEL_WORKER)]);
    env.ok(&["agent", "set", "mw", "command", "mw"]);
    env.ok(&[
        "agent",
        "set",
        "mw",
        "args",
        r#"["--task","{prompt}","{dir}","{model}","{extra}"]"#,
    ]);
    let (_, err, ok) = env.run(&["agent", "set", "mw", "model", "haiku"]);
    assert!(!ok, "the field is gone");
    assert!(
        err.contains("pma preset set"),
        "it says where it went: {err}"
    );
    let (_, err, ok) = env.run(&["config", "model", "haiku"]);
    assert!(!ok && err.contains("pma agent set"), "{err}");

    // With no preset and no flag, the worker is run without a model at all and
    // uses its own.
    env.ok(&["config", "agent", "mw"]);
    env.ok(&["dispatch", "alpha:5"]);
    assert!(
        env.ok(&["review", "1"]).contains("model=\n"),
        "no model named"
    );

    // A flag names one for the invocation.
    env.ok(&["dispatch", "-m", "sonnet", "alpha:7"]);
    assert!(
        env.ok(&["review", "2"]).contains("model=sonnet"),
        "the flag"
    );

    // The listing is about the program, not the model.
    let listed = env.ok(&["agent"]);
    assert!(listed.contains("* mw"), "{listed}");
    assert!(!listed.contains("sonnet"), "no model column: {listed}");
    assert!(
        env.ok(&["agent", "show", "mw"]).contains("{extra}"),
        "args shown"
    );
}

/// A preset names a worker, a model and the configuration that goes with them,
/// so a combination worth returning to has a name. Effort is arguments rather
/// than a field, because what expresses it differs per agent.
#[test]
fn a_preset_names_a_worker_a_model_and_its_configuration() {
    let s = Scratch::new("presets");
    let (env, _, _) = dispatch_env(&s, &[("mw", MODEL_WORKER)]);
    env.ok(&["agent", "set", "mw", "command", "mw"]);
    // `{extra}` is where this worker wants a preset's arguments.
    env.ok(&[
        "agent",
        "set",
        "mw",
        "args",
        r#"["--task","{prompt}","{dir}","{model}","{extra}"]"#,
    ]);

    assert!(env.ok(&["preset"]).contains("no presets"), "empty");
    // A preset may not name a worker that does not exist: it would name a
    // combination nothing could run.
    let (_, err, ok) = env.run(&["preset", "set", "bad", "nosuch", "haiku"]);
    assert!(!ok && err.contains("no worker `nosuch`"), "{err}");

    env.ok(&["preset", "set", "plain", "mw"]);
    env.ok(&["preset", "set", "cheap", "mw", "haiku"]);
    env.ok(&[
        "preset",
        "set",
        "cheap-high",
        "mw",
        "haiku",
        "--thinking",
        "high",
    ]);
    let listed = env.ok(&["preset"]);
    assert!(
        listed.contains("its own default"),
        "a preset may name no model"
    );
    assert!(listed.contains("--thinking high"), "{listed}");

    // `-p` runs one command with that preset, and its arguments reach the
    // worker where its record puts them.
    env.ok(&["dispatch", "-p", "cheap-high", "alpha:5"]);
    let detail = env.ok(&["review", "1"]);
    assert!(detail.contains("model=haiku"), "{detail}");
    assert!(
        detail.contains("thinking=high"),
        "the effort reached it: {detail}"
    );

    // A flag beside it is the more specific statement, so it wins.
    env.ok(&["dispatch", "-p", "cheap-high", "-m", "sonnet", "alpha:7"]);
    let detail = env.ok(&["review", "2"]);
    assert!(detail.contains("model=sonnet"), "{detail}");
    assert!(
        detail.contains("thinking=high"),
        "the rest of the preset stands"
    );

    // `use` makes it the default, and then no flag is needed.
    env.ok(&["preset", "use", "cheap"]);
    assert!(env.ok(&["preset"]).contains("* cheap"), "marked default");
    env.ok(&["dispatch", "alpha:8"]);
    let detail = env.ok(&["review", "3"]);
    assert!(detail.contains("model=haiku"), "{detail}");
    assert!(
        !detail.contains("thinking=high"),
        "a different preset: {detail}"
    );

    // Forgetting the default clears the setting rather than leaving a name
    // nothing resolves.
    env.ok(&["preset", "rm", "cheap"]);
    let listed = env.ok(&["preset"]);
    assert!(!listed.contains("* cheap"), "the default is gone: {listed}");
    let settings = env.ok(&["config"]);
    let preset_line = settings
        .lines()
        .find(|l| l.starts_with("preset ="))
        .unwrap_or_default();
    assert_eq!(
        preset_line.trim_end_matches("  (set)").trim(),
        "preset =",
        "the setting is cleared with it"
    );
}

/// A workflow document, in both its forms, through the store: a script and the
/// JSON it generates are one revision, and the worst case is what `activate`
/// weighs against the budget.
#[test]
fn a_workflow_document_is_a_draft_until_its_cost_is_accepted() {
    let s = Scratch::new("workflow");
    let home = s.0.join("home");
    fs::create_dir_all(&home).unwrap();
    let run = |args: &[&str]| {
        let out = Command::new(env!("CARGO_BIN_EXE_pma"))
            .env("PMA_HOME", &home)
            .args(args)
            .output()
            .unwrap();
        (
            String::from_utf8_lossy(&out.stdout).into_owned(),
            String::from_utf8_lossy(&out.stderr).into_owned(),
            out.status.success(),
        )
    };

    let script = s.0.join("lib.rhai");
    fs::write(
        &script,
        r#"
        fn reviewer(node, what) {
            |g| g.expand(node, "finding", "{$breadth}",
                         "Review `{name}` for " + what + ". Write findings to {out}.")
        }
        let graph = source("project")
            .fan([reviewer("bugs", "correctness"), reviewer("tests", "coverage")])
            .join("merge", ["title"])
            .filter("confirm", ["reason"], "Confirm each unit in {in}.")
            .output();
        document(#{ finding: #{ fields: #{
            title: req(unique(line(200))),
            reason: line(200),
        }}}, [
            workflow("look", graph, #{
                params: #{ breadth: bounded("int", 4, 6) },
                caps: #{ max_units: 40, max_edits: 0 },
            }),
        ])
        "#,
    )
    .unwrap();

    assert!(run(&["workflow"]).0.contains("no workflow revisions"));

    // The script's document is checked and costed like any other: two
    // reviewers at the parameter's maximum, then one confirm per finding.
    let (out, err, ok) = run(&["workflow", "check", script.to_str().unwrap()]);
    assert!(ok, "{err}");
    assert!(
        out.contains("look(in: [project], breadth = 4) -> [finding]  pure"),
        "{out}"
    );
    assert!(
        out.contains("worst case: 14 agent runs, 0 edits, $14.00"),
        "{out}"
    );

    // The same document, emitted as JSON, is the same document.
    let (json, err, ok) = run(&["workflow", "check", script.to_str().unwrap(), "--emit-json"]);
    assert!(ok, "{err}");
    let from_json = s.0.join("lib.json");
    fs::write(&from_json, &json).unwrap();
    let (a, _, _) = run(&["workflow", "check", from_json.to_str().unwrap()]);
    assert_eq!(a, out, "the generated document estimates the same");

    // Proposing stores it as a draft, with its cost per unit of input.
    let (out, err, ok) = run(&[
        "workflow",
        "propose",
        script.to_str().unwrap(),
        "--by",
        "me",
    ]);
    assert!(ok, "{err}");
    assert!(
        out.contains("revision 1 stored as a draft: at most $14.00"),
        "{out}"
    );
    let listed = run(&["workflow"]).0;
    assert!(
        listed.contains("draft") && listed.contains("look"),
        "{listed}"
    );

    // A budget below the worst case refuses activation, naming both numbers.
    run(&["config", "workflow_budget", "10"]);
    let (_, err, ok) = run(&["workflow", "activate", "1", "--by", "me"]);
    assert!(!ok, "a revision over budget must not activate");
    assert!(err.contains("$14.00") && err.contains("$10.00"), "{err}");
    assert!(run(&["workflow"]).0.contains("draft"), "still a draft");

    run(&["config", "workflow_budget", "20"]);
    let (out, err, ok) = run(&["workflow", "activate", "1", "--by", "me"]);
    assert!(ok, "{err}");
    assert!(out.contains("in effect"), "{out}");
    assert!(run(&["workflow"]).0.contains("active, by me"));

    // The stored form is the document, whichever form wrote it, so a script's
    // revision reads back without the script.
    let shown = run(&["workflow", "show"]).0;
    assert!(shown.contains("\"name\": \"look\""), "{shown}");
    assert!(shown.contains("\"max_units\": \"{$breadth}\""), "{shown}");
    assert!(!shown.contains("fan("), "the script is not the document");
}

/// A pass over a workflow whose every node is a rule: it runs, it writes what
/// `pma` owns, and it spends nothing. A second pass advances nothing, because
/// what has run is derived from the units rather than from a cursor.
#[test]
fn a_pass_runs_the_free_nodes_and_never_spends_without_approval() {
    let s = Scratch::new("pass");
    let home = s.0.join("home");
    let root = s.0.join("root");
    let alpha = root.join("alpha");
    fs::create_dir_all(&alpha).unwrap();
    git(&alpha, &["init", "-q"], None);
    fs::write(
        alpha.join("TODO.md"),
        "# TODO\n\n## Critical\n\n## High\n\n- [ ] first thing\n- [x] done thing\n\n## Medium\n\n## Low\n",
    )
    .unwrap();
    git(&alpha, &["add", "."], None);
    git(&alpha, &["commit", "-qm", "init"], None);

    ok(&home, &["root", "add", root.to_str().unwrap()]);
    ok(&home, &["scan", "--offline"]);

    // Every node here is a rule or a check, so the worst case is $0.00.
    let free = s.0.join("free.rhai");
    fs::write(
        &free,
        r#"
        let graph = source("project")
            .check("lint", "lint-todo")
            .rule_expand("items", "item", "todo-items", 100)
            .rule_filter("open", "where:done=false")
            .emit_note("record", #{ text: "open: {text}" })
            .output();
        document(#{}, [
            workflow("stocktake", graph, #{ caps: #{ max_units: 200, max_edits: 0 }}),
        ])
        "#,
    )
    .unwrap();
    let out = ok(&home, &["workflow", "propose", free.to_str().unwrap()]);
    assert!(
        out.contains("at most $0.00"),
        "a graph of rules is free: {out}"
    );
    ok(&home, &["workflow", "activate", "1"]);

    // A dry run plans and prices, and writes no note.
    let out = ok(
        &home,
        &["workflow", "run", "stocktake", "alpha", "--dry-run"],
    );
    assert!(out.contains("instance 1"), "{out}");
    assert!(
        out.contains("would run: lint") && out.contains("a rule, free"),
        "{out}"
    );
    assert!(
        ok(&home, &["note"]).contains("no notes"),
        "a dry run writes nothing"
    );

    // The pass runs every rule node to exhaustion, in one invocation.
    let out = ok(&home, &["workflow", "run", "stocktake", "--instance", "1"]);
    assert!(out.contains("nothing left to run"), "{out}");
    let notes = ok(&home, &["note"]);
    assert!(notes.contains("open: first thing"), "{notes}");
    assert!(
        !notes.contains("done thing"),
        "the filter dropped it: {notes}"
    );

    // Again: the frontier is re-derived, and everything has been consumed.
    let out = ok(&home, &["workflow", "run", "stocktake", "--instance", "1"]);
    assert!(out.contains("nothing left to run"), "{out}");
    assert_eq!(
        ok(&home, &["note"]).lines().count(),
        notes.lines().count(),
        "a second pass writes no second note"
    );
}

/// A pass that reaches a node an agent decides stops, prices it, and spends
/// nothing until the developer says so.
#[test]
fn an_agent_node_is_priced_and_left_for_approval() {
    let s = Scratch::new("gate");
    let home = s.0.join("home");
    let root = s.0.join("root");
    let alpha = root.join("alpha");
    fs::create_dir_all(&alpha).unwrap();
    git(&alpha, &["init", "-q"], None);
    fs::write(
        alpha.join("TODO.md"),
        "# TODO\n\n## High\n\n- [ ] a thing\n",
    )
    .unwrap();
    git(&alpha, &["add", "."], None);
    git(&alpha, &["commit", "-qm", "init"], None);

    // A worker that records every invocation, so "nothing was spent" is a
    // fact about the filesystem rather than a claim.
    let bin = s.0.join("bin");
    fs::create_dir_all(&bin).unwrap();
    let log = s.0.join("spend.log");
    fs::write(
        bin.join("claude"),
        format!(
            "#!/bin/sh\necho invoked >> {}\nprintf '{{\"type\":\"result\",\"subtype\":\"success\",\"is_error\":false,\"result\":\"ok\",\"total_cost_usd\":0.1}}\\n'\n",
            log.display()
        ),
    )
    .unwrap();
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(bin.join("claude"), fs::Permissions::from_mode(0o755)).unwrap();
    }
    let run = |args: &[&str]| {
        let path = format!(
            "{}:{}",
            bin.display(),
            std::env::var("PATH").unwrap_or_default()
        );
        let out = Command::new(env!("CARGO_BIN_EXE_pma"))
            .env("PMA_HOME", &home)
            .env("PATH", path)
            .args(args)
            .output()
            .unwrap();
        (
            String::from_utf8_lossy(&out.stdout).into_owned(),
            String::from_utf8_lossy(&out.stderr).into_owned(),
            out.status.success(),
        )
    };
    run(&["root", "add", root.to_str().unwrap()]);
    run(&["scan", "--offline"]);

    let wf = s.0.join("review.rhai");
    fs::write(
        &wf,
        r#"
        let graph = source("project")
            .expand("review", "finding", 3, "Review `{name}`. Write findings to {out}.")
            .output();
        document(#{ finding: #{ fields: #{ title: req(line(200)) }}}, [
            workflow("review", graph, #{ caps: #{ max_units: 10, max_edits: 0 }}),
        ])
        "#,
    )
    .unwrap();
    let (out, err, success) = run(&["workflow", "propose", wf.to_str().unwrap()]);
    assert!(success, "{err}");
    // One review run over one project; `max_units` bounds the findings it may
    // produce, not the runs it takes.
    assert!(out.contains("at most $1.00"), "{out}");
    run(&["workflow", "activate", "1"]);

    // The pass names the node, its worker and model, and its ceiling, and
    // stops without running it.
    let (out, err, success) = run(&["workflow", "run", "review", "alpha", "-m", "haiku"]);
    assert!(success, "{err}");
    assert!(out.contains("next: review"), "{out}");
    assert!(
        out.contains("claude/haiku"),
        "the cheap model it would use: {out}"
    );
    assert!(out.contains("Nothing was spent"), "{out}");
    assert!(out.contains("--yes"), "it says how to approve: {out}");
    assert!(!log.exists(), "the worker must not have run");

    // Approval is what unlocks it, and agent execution is the next step.
    let (_, err, success) = run(&["workflow", "run", "review", "--instance", "1", "--yes"]);
    assert!(!success && err.contains("not executable yet"), "{err}");
    assert!(!log.exists(), "still nothing spent");
}