rigger 0.20.0

One seat for all your projects and tasks: a local record of what is done, what is next and when it ships - read by you and your coding assistant
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
//! The binary surface as a user meets it, against a throwaway data directory.

use std::path::Path;

use assert_cmd::Command;
use predicates::prelude::*;

fn rigger(data: &Path) -> Command {
    let mut cmd = Command::cargo_bin("rigger").unwrap();
    cmd.env("RIGGER_DATA_DIR", data);
    cmd
}

fn repo(root: &Path) {
    std::fs::create_dir_all(root).unwrap();
    std::fs::write(root.join("Cargo.toml"), "[package]\nname = \"declared-elsewhere\"\nversion = \"0.1.0\"\n").unwrap();
}

#[test]
fn version_prints_the_crate_version() {
    Command::cargo_bin("rigger")
        .unwrap()
        .arg("--version")
        .assert()
        .success()
        .stdout(predicate::str::contains(env!("CARGO_PKG_VERSION")));
}

#[test]
fn help_describes_the_product() {
    Command::cargo_bin("rigger")
        .unwrap()
        .arg("--help")
        .assert()
        .success()
        .stdout(predicate::str::contains("One seat for all your projects and tasks"));
}

#[test]
fn init_creates_the_database_and_is_idempotent() {
    let data = tempfile::tempdir().unwrap();
    rigger(data.path())
        .arg("init")
        .assert()
        .success()
        .stdout(predicate::str::contains("Created").and(predicate::str::contains("schema version")));
    assert!(data.path().join("profiles").join("line").join("rigger.db").exists());
    assert!(data.path().join("config.toml").exists(), "init writes the config with the default profile");

    rigger(data.path())
        .arg("init")
        .assert()
        .success()
        .stdout(predicate::str::contains("Already initialised"));
}

#[test]
fn commands_before_init_point_at_init() {
    let data = tempfile::tempdir().unwrap();
    rigger(data.path())
        .args(["project", "list"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("run `rigger init` first"));
}

#[test]
fn project_add_names_the_project_after_its_directory() {
    // The manifest declares another name on purpose: the crate or package
    // name is the publishing name, not the one the owner calls the project.
    let data = tempfile::tempdir().unwrap();
    let root = data.path().join("repos").join("folder-name");
    repo(&root);
    rigger(data.path()).arg("init").assert().success();

    rigger(data.path())
        .args(["project", "add"])
        .arg(&root)
        .assert()
        .success()
        .stdout(predicate::str::contains("Recorded 'folder-name'").and(predicate::str::contains("remote: none")));

    rigger(data.path())
        .args(["project", "list"])
        .assert()
        .success()
        .stdout(predicate::str::starts_with("folder-name"));
}

#[test]
fn project_add_reads_the_origin_remote() {
    let data = tempfile::tempdir().unwrap();
    let root = data.path().join("remoted");
    repo(&root);
    std::fs::create_dir(root.join(".git")).unwrap();
    std::fs::write(
        root.join(".git").join("config"),
        "[remote \"origin\"]\n\turl = https://example.com/remoted.git\n",
    )
    .unwrap();
    rigger(data.path()).arg("init").assert().success();

    rigger(data.path())
        .args(["project", "add"])
        .arg(&root)
        .assert()
        .success()
        .stdout(predicate::str::contains("remote: https://example.com/remoted.git"));

    rigger(data.path())
        .args(["project", "show", "remoted", "--json"])
        .assert()
        .success()
        .stdout(predicate::str::contains("\"remote\": \"https://example.com/remoted.git\""));
}

#[test]
fn name_can_be_overridden_and_must_be_unique() {
    let data = tempfile::tempdir().unwrap();
    let first = data.path().join("a").join("same");
    let second = data.path().join("b").join("same");
    repo(&first);
    repo(&second);
    rigger(data.path()).arg("init").assert().success();

    rigger(data.path()).args(["project", "add"]).arg(&first).assert().success();
    rigger(data.path())
        .args(["project", "add"])
        .arg(&second)
        .assert()
        .failure()
        .stderr(predicate::str::contains("a project named 'same' already exists"));
    rigger(data.path())
        .args(["project", "add", "--name", "other"])
        .arg(&second)
        .assert()
        .success()
        .stdout(predicate::str::contains("Recorded 'other'"));
}

#[test]
fn the_same_path_is_not_recorded_twice() {
    let data = tempfile::tempdir().unwrap();
    let root = data.path().join("once");
    repo(&root);
    rigger(data.path()).arg("init").assert().success();

    rigger(data.path()).args(["project", "add"]).arg(&root).assert().success();
    rigger(data.path())
        .args(["project", "add"])
        .arg(&root)
        .assert()
        .failure()
        .stderr(predicate::str::contains("already recorded as project 'once'"));
}

#[test]
fn show_of_an_unknown_project_fails_with_a_pointer() {
    let data = tempfile::tempdir().unwrap();
    rigger(data.path()).arg("init").assert().success();
    rigger(data.path())
        .args(["project", "show", "ghost"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("no project named 'ghost'"));
}

/// A hub in the shape the real ones have: a plan with open stages and
/// questions, a changelog of shipped ones, a dated decision log.
fn hub(dir: &Path) {
    std::fs::create_dir_all(dir).unwrap();
    std::fs::write(
        dir.join("План.md"),
        "# План разработки\n\n## Ждёт решения владельца\n\n1. Pick a colour.\n2. Sign the binary.\n\n## v0.3.0 · Third stage\n\n- [ ] first task\n- [ ] second task\n\n## Бэклог без версии\n\n- [ ] someday, not a task of a stage\n",
    )
    .unwrap();
    std::fs::write(
        dir.join("Изменения.md"),
        "# Изменения\n\n## v0.2.0 · Second stage — выпущена 2026-09-03\n\n- Something shipped.\n\n## v0.1.0 · First stage — выпущен 2026-09-01\n",
    )
    .unwrap();
    std::fs::write(
        dir.join("Решения.md"),
        "# Журнал решений\n\n---\n\n## 2026-09-03 · The record is the database\n\nBecause prose cannot be filtered.\n",
    )
    .unwrap();
}

/// A database with one project named `proj`, whose repository carries a hub.
fn imported_project(data: &Path) -> std::path::PathBuf {
    let root = data.join("proj");
    repo(&root);
    hub(&root.join("hub"));
    rigger(data).arg("init").assert().success();
    rigger(data).args(["project", "add"]).arg(&root).assert().success();
    root
}

#[test]
fn import_reads_stages_tasks_decisions_and_questions() {
    let data = tempfile::tempdir().unwrap();
    let root = imported_project(data.path());

    rigger(data.path())
        .args(["import", "proj", "--hub"])
        .arg(root.join("hub"))
        .assert()
        .success()
        .stdout(
            predicate::str::contains("versions   3 added")
                .and(predicate::str::contains("tasks      2 added"))
                .and(predicate::str::contains("decisions  1 added"))
                .and(predicate::str::contains("questions  2 added")),
        );

    rigger(data.path()).arg("doctor").assert().success().stdout(
        predicate::str::contains("versions:  3")
            .and(predicate::str::contains("tasks:     2"))
            .and(predicate::str::contains("events:    3")),
    );
}

#[test]
fn importing_an_unchanged_hub_again_changes_nothing() {
    let data = tempfile::tempdir().unwrap();
    let root = imported_project(data.path());
    let hub_dir = root.join("hub");

    rigger(data.path()).args(["import", "proj", "--hub"]).arg(&hub_dir).assert().success();
    rigger(data.path())
        .args(["import", "proj", "--hub"])
        .arg(&hub_dir)
        .assert()
        .success()
        .stdout(predicate::str::contains("nothing changed"));

    // And the record did not grow behind the report.
    rigger(data.path())
        .arg("doctor")
        .assert()
        .success()
        .stdout(predicate::str::contains("versions:  3").and(predicate::str::contains("events:    3")));
}

#[test]
fn a_stage_that_shipped_is_updated_rather_than_duplicated() {
    let data = tempfile::tempdir().unwrap();
    let root = imported_project(data.path());
    let hub_dir = root.join("hub");
    rigger(data.path()).args(["import", "proj", "--hub"]).arg(&hub_dir).assert().success();

    // The stage moves from the plan to the changelog, as it does when a
    // version ships: same version, now with a date.
    std::fs::write(hub_dir.join("План.md"), "# План\n\n## Ждёт решения владельца\n\n- (пусто)\n").unwrap();
    std::fs::write(
        hub_dir.join("Изменения.md"),
        "# Изменения\n\n## v0.3.0 · Third stage — выпущена 2026-09-05\n\n## v0.2.0 · Second stage — выпущена 2026-09-03\n\n## v0.1.0 · First stage — выпущен 2026-09-01\n",
    )
    .unwrap();

    // Nothing is added: the stage that moved is the same stage, found by its
    // version. How many rows an update touches is not the claim - the claim
    // is that a stage moving between files does not become two stages, and
    // `doctor` below counts them.
    rigger(data.path())
        .args(["import", "proj", "--hub"])
        .arg(&hub_dir)
        .assert()
        .success()
        .stdout(predicate::str::contains("versions   0 added"));

    // And a second import of the same hub is quiet, so the record settles
    // rather than reporting an update for ever.
    rigger(data.path())
        .args(["import", "proj", "--hub"])
        .arg(&hub_dir)
        .assert()
        .success()
        .stdout(predicate::str::contains("nothing changed"));

    rigger(data.path())
        .arg("doctor")
        .assert()
        .success()
        .stdout(predicate::str::contains("versions:  3"));
}

/// A stage whose heading numbers it one way and its release another - kasl
/// writes `v1.9 · Title — closed, released **v1.9.0**` - is recorded under
/// the number git will carry. And a database that already held it under the
/// old number is corrected rather than left with two rows for one stage.
#[test]
fn a_stage_renumbered_by_its_release_replaces_the_old_row() {
    let data = tempfile::tempdir().unwrap();
    let root = imported_project(data.path());
    let hub_dir = root.join("hub");

    std::fs::write(hub_dir.join("Изменения.md"), "# Изменения\n\n## v1.9 · Очередь — закрыт 2026-09-03\n").unwrap();
    rigger(data.path()).args(["import", "proj", "--hub"]).arg(&hub_dir).assert().success();

    // The heading now names the release the stage shipped as.
    std::fs::write(
        hub_dir.join("Изменения.md"),
        "# Изменения\n\n## v1.9 · Очередь — закрыт 2026-09-03, выпущен **v1.9.0**\n",
    )
    .unwrap();
    rigger(data.path()).args(["import", "proj", "--hub"]).arg(&hub_dir).assert().success();

    rigger(data.path())
        .args(["context", "proj"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Last shipped: v1.9.0"));

    // One stage, one row. Two versions in total: the plan's open stage and
    // this one - a twin left behind would make it three.
    rigger(data.path())
        .arg("doctor")
        .assert()
        .success()
        .stdout(predicate::str::contains("versions:  2"));
}

/// The packet names the newest release, and versions are numbered, not
/// lettered: v0.10.0 comes after v0.9.0. Hubs list their changelog
/// newest-first, so ordering by row put the oldest entry on top.
#[test]
fn the_newest_release_is_the_highest_number_not_the_last_row() {
    let data = tempfile::tempdir().unwrap();
    let root = imported_project(data.path());
    let hub_dir = root.join("hub");

    // Written the way a hub writes it: newest at the top, one date for all.
    std::fs::write(
        hub_dir.join("Изменения.md"),
        "# Изменения\n\n## v0.10.0 · Tenth — выпущена 2026-09-02\n\n## v0.9.0 · Ninth — выпущена 2026-09-02\n\n## v0.1.0 · First — выпущена 2026-09-02\n",
    )
    .unwrap();
    rigger(data.path()).args(["import", "proj", "--hub"]).arg(&hub_dir).assert().success();

    rigger(data.path())
        .args(["context", "proj"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Last shipped: v0.10.0"));
}

/// A hub that is not there is refused, not read as an empty one.
///
/// It used to report the files it had wanted and succeed, having changed
/// nothing - which was true only because the project was empty. With
/// versions in the record an empty reading names no stage, and what no
/// reading names is struck: a mistyped path arrived as an instruction to
/// strike every version of the project, and said so while exiting zero.
#[test]
fn import_of_a_missing_hub_is_refused() {
    let data = tempfile::tempdir().unwrap();
    let root = imported_project(data.path());

    rigger(data.path())
        .args(["import", "proj", "--hub"])
        .arg(root.join("no-such-hub"))
        .assert()
        .failure()
        .stderr(predicate::str::contains("is not there"));
}

#[test]
fn import_of_an_unknown_project_fails() {
    let data = tempfile::tempdir().unwrap();
    let root = imported_project(data.path());
    rigger(data.path())
        .args(["import", "ghost", "--hub"])
        .arg(root.join("hub"))
        .assert()
        .failure()
        .stderr(predicate::str::contains("no project named 'ghost'"));
}

#[test]
fn context_shows_where_the_project_stands_and_what_is_next() {
    let data = tempfile::tempdir().unwrap();
    let root = imported_project(data.path());
    rigger(data.path()).args(["import", "proj", "--hub"]).arg(root.join("hub")).assert().success();

    rigger(data.path()).args(["context", "proj"]).assert().success().stdout(
        // The state line, the stage in progress with its open tasks, the
        // owner's queue and the decision - in that order.
        predicate::str::contains("Last shipped: v0.2.0 on 2026-09-03")
            .and(predicate::str::contains("## Current stage: v0.3.0 · Third stage"))
            .and(predicate::str::contains("- first task"))
            .and(predicate::str::contains("## Waiting for the owner"))
            .and(predicate::str::contains("Pick a colour."))
            .and(predicate::str::contains("The record is the database")),
    );
}

#[test]
fn a_recorded_note_reaches_the_packet_and_a_next_step_stands_alone() {
    let data = tempfile::tempdir().unwrap();
    imported_project(data.path());

    rigger(data.path())
        .args(["note", "proj", "The parser must take hubs as they are.", "--kind", "finding"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Recorded a finding for proj"));
    rigger(data.path())
        .args(["note", "proj", "Ship the importer next.", "--kind", "next"])
        .assert()
        .success();
    rigger(data.path()).args(["wish", "proj", "Show days without a commit."]).assert().success();

    rigger(data.path()).args(["context", "proj"]).assert().success().stdout(
        predicate::str::contains("finding · The parser must take hubs as they are.")
            .and(predicate::str::contains("## Wishes, not yet sorted"))
            .and(predicate::str::contains("Show days without a commit."))
            .and(predicate::str::contains("## Next step\nShip the importer next."))
            // A next step is not repeated among the recent events.
            .and(predicate::str::contains("next · Ship").not()),
    );
}

/// The budget is a gate, not a hope: a project with a long history must still
/// produce a packet that fits, and say what it left out.
/// The token cost of a packet, from its own `--explain` line.
fn packet_cost(data: &Path, args: &[&str]) -> (usize, String) {
    let mut cmd = rigger(data);
    cmd.args(["context", "proj", "--explain"]).args(args);
    let text = String::from_utf8(cmd.output().unwrap().stdout).unwrap();
    let total = text
        .lines()
        .find(|l| l.starts_with("total"))
        .and_then(|l| l.split_whitespace().nth(1))
        .and_then(|n| n.parse().ok())
        .unwrap_or_else(|| panic!("no total line in:\n{text}"));
    (total, text)
}

#[test]
fn the_packet_holds_the_budget_and_reports_what_it_dropped() {
    let data = tempfile::tempdir().unwrap();
    let root = imported_project(data.path());
    rigger(data.path()).args(["import", "proj", "--hub"]).arg(root.join("hub")).assert().success();

    // Enough decisions, each as long as the real hubs carry, that no budget
    // could hold them all - the packet must choose and say so.
    let body = "**A decision that took a paragraph.**\n\n".to_string() + &"Reasoning that runs on and on. ".repeat(40);
    for i in 0..60 {
        rigger(data.path())
            .args(["note", "proj", &format!("{body} number {i} of sixty"), "--kind", "decision"])
            .assert()
            .success();
    }

    let (total, text) = packet_cost(data.path(), &[]);
    assert!(total <= 3000, "packet is {total} tokens, over the budget:\n{text}");

    // Under a budget that cannot hold them, the packet says how many it left
    // out - the silent truncation this command exists to avoid.
    let (total, text) = packet_cost(data.path(), &["--budget", "600"]);
    assert!(total <= 600, "packet is {total} tokens, over the 600 asked for:\n{text}");
    assert!(
        text.contains("older events left out by the budget"),
        "the packet did not say what it dropped:\n{text}"
    );
}

/// A budget too small even for the fixed sections still produces a usable
/// packet: state, the current stage and the owner's queue are never dropped.
#[test]
fn the_essentials_survive_an_impossible_budget() {
    let data = tempfile::tempdir().unwrap();
    let root = imported_project(data.path());
    rigger(data.path()).args(["import", "proj", "--hub"]).arg(root.join("hub")).assert().success();

    let (_, text) = packet_cost(data.path(), &["--budget", "1"]);
    assert!(text.contains("## Current stage: v0.3.0"), "{text}");
    assert!(text.contains("## Waiting for the owner"), "{text}");
    assert!(text.contains("left out by the budget"), "{text}");
}

#[test]
fn context_as_json_carries_the_same_facts() {
    let data = tempfile::tempdir().unwrap();
    let root = imported_project(data.path());
    rigger(data.path()).args(["import", "proj", "--hub"]).arg(root.join("hub")).assert().success();

    rigger(data.path()).args(["context", "proj", "--json"]).assert().success().stdout(
        predicate::str::contains("\"project\": \"proj\"")
            .and(predicate::str::contains("\"version\": \"v0.3.0\""))
            .and(predicate::str::contains("\"events_omitted\": 0")),
    );
}

#[test]
fn open_print_shows_the_message_the_assistant_would_receive() {
    let data = tempfile::tempdir().unwrap();
    let root = imported_project(data.path());
    rigger(data.path()).args(["import", "proj", "--hub"]).arg(root.join("hub")).assert().success();

    rigger(data.path()).args(["open", "proj", "--print"]).assert().success().stdout(
        // The instruction first, so the packet is read as state rather
        // than as something to summarise; then the packet itself.
        predicate::str::contains("This is where the project stands")
            .and(predicate::str::contains("rigger note"))
            .and(predicate::str::contains("## Current stage: v0.3.0 · Third stage")),
    );
}

/// `open` runs whatever assistant the owner uses. Here that is a script that
/// records its arguments, which proves three things at once: the packet
/// arrives as one argument, the working directory is the project, and the
/// assistant's exit status becomes ours.
#[test]
fn open_runs_the_assistant_in_the_project_with_the_packet() {
    let data = tempfile::tempdir().unwrap();
    let root = imported_project(data.path());
    let log = data.path().join("assistant.log");

    let (stub, args) = stub_assistant(data.path(), &log, 0);
    let mut cmd = rigger(data.path());
    cmd.env(open_env(), format!("{stub} {args}"));
    cmd.args(["open", "proj"]).assert().success();

    let recorded = std::fs::read_to_string(&log).unwrap();
    assert!(
        recorded.contains("This is where the project stands"),
        "the packet did not reach the assistant: {recorded}"
    );
    // The tail of the path, not the whole of it: macOS reports a temporary
    // directory through its /private symlink, and Windows shells report the
    // drive letter in their own case.
    let cwd = recorded
        .lines()
        // PowerShell writes a byte-order mark at the head of the file, so the
        // first line does not start with the text it appears to start with.
        .find_map(|l| l.trim_start_matches('\u{feff}').strip_prefix("cwd="))
        .unwrap_or_else(|| panic!("the assistant did not report where it ran: {recorded}"));
    assert!(
        cwd.to_lowercase().ends_with("proj"),
        "the assistant did not run in the project: ran in {cwd}, expected {}",
        root.display()
    );
}

/// Every Windows install of an npm CLI is a `.cmd` shim, and the process API
/// refuses to hand one an argument. `open` runs it the way a shell does, or
/// it cannot start the assistant the owner actually has.
#[cfg(windows)]
#[test]
fn open_can_launch_a_batch_file_assistant() {
    let data = tempfile::tempdir().unwrap();
    imported_project(data.path());
    let log = data.path().join("batch.log");
    let script = data.path().join("assistant.cmd");
    // The packet arrives on stdin, not as an argument: a batch file cannot
    // receive a multi-line argument at all. `findstr` copies stdin through.
    std::fs::write(
        &script,
        format!(
            "@echo off\r\necho cwd=%CD%>\"{}\"\r\nfindstr /n \"^\">>\"{}\"\r\n",
            log.display(),
            log.display()
        ),
    )
    .unwrap();

    let mut cmd = rigger(data.path());
    cmd.env(open_env(), script.display().to_string());
    cmd.args(["open", "proj"]).assert().success();

    let recorded = std::fs::read_to_string(&log).unwrap();
    assert!(
        recorded.contains("This is where the project stands"),
        "a .cmd assistant did not receive the packet: {recorded}"
    );
}

/// The packet is many lines and quotes plans that contain `<`, `>`, `&` and
/// `|`. As an argument to a batch file it cannot survive: Rust refuses a
/// multi-line one outright, and through `cmd /c` the newline ends the command
/// line and the metacharacters redirect it. On stdin it arrives whole.
#[cfg(windows)]
#[test]
fn a_batch_assistant_receives_every_line_of_the_packet() {
    let data = tempfile::tempdir().unwrap();
    let root = imported_project(data.path());
    rigger(data.path()).args(["import", "proj", "--hub"]).arg(root.join("hub")).assert().success();
    rigger(data.path())
        .args(["note", "proj", "Runs `open <project>` & pipes a|b, then ^ escapes.", "--kind", "finding"])
        .assert()
        .success();

    let log = data.path().join("meta.log");
    let script = data.path().join("assistant.cmd");
    // `findstr /n` numbers the lines, which keeps the blank ones a plain
    // copy would drop - and makes it visible that the whole packet arrived,
    // not just its first paragraph.
    std::fs::write(&script, format!("@echo off\r\nfindstr /n \"^\">\"{}\"\r\n", log.display())).unwrap();

    let mut cmd = rigger(data.path());
    cmd.env(open_env(), script.display().to_string());
    cmd.args(["open", "proj"]).assert().success();

    let recorded = std::fs::read_to_string(&log).unwrap();
    assert!(
        recorded.contains("`open <project>` & pipes a|b, then ^ escapes."),
        "the packet did not arrive whole: {recorded}"
    );
    // The last section proves the whole packet came through, not its head.
    assert!(recorded.contains("## Current stage"), "the packet was cut short: {recorded}");
    // Nothing was redirected into a stray file named after the next word.
    let strays: Vec<_> = std::fs::read_dir(data.path())
        .unwrap()
        .filter_map(|e| e.ok())
        .map(|e| e.file_name().to_string_lossy().into_owned())
        .filter(|n| n.contains("project") || n.contains("pipes"))
        .collect();
    assert!(strays.is_empty(), "cmd redirected into {strays:?}");
}

#[test]
fn open_passes_on_the_assistants_exit_status() {
    let data = tempfile::tempdir().unwrap();
    imported_project(data.path());
    let log = data.path().join("assistant.log");

    let (stub, args) = stub_assistant(data.path(), &log, 3);
    let mut cmd = rigger(data.path());
    cmd.env(open_env(), format!("{stub} {args}"));
    cmd.args(["open", "proj"]).assert().code(3);
}

#[test]
fn open_reports_a_missing_assistant_by_name() {
    let data = tempfile::tempdir().unwrap();
    imported_project(data.path());

    let mut cmd = rigger(data.path());
    cmd.env(open_env(), "no-such-assistant-binary");
    cmd.args(["open", "proj"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("cannot run `no-such-assistant-binary`"));
}

fn open_env() -> &'static str {
    "RIGGER_ASSISTANT"
}

/// Writes a script that appends its working directory and arguments to `log`
/// and exits with `code`. Returns the interpreter and its leading arguments,
/// so the caller can build the command line rigger will run.
fn stub_assistant(dir: &Path, log: &Path, code: i32) -> (String, String) {
    let log = log.display().to_string().replace('\\', "/");
    if cfg!(windows) {
        let script = dir.join("stub.ps1");
        std::fs::write(
            &script,
            format!("\"cwd=$((Get-Location).Path)\" | Out-File -Append -Encoding utf8 '{log}'\n$args | Out-File -Append -Encoding utf8 '{log}'\nexit {code}\n"),
        )
        .unwrap();
        (
            "powershell.exe".to_string(),
            format!("-NoProfile -ExecutionPolicy Bypass -File {}", script.display()),
        )
    } else {
        let script = dir.join("stub.sh");
        std::fs::write(
            &script,
            format!("#!/bin/sh\necho \"cwd=$(pwd)\" >> '{log}'\necho \"$@\" >> '{log}'\nexit {code}\n"),
        )
        .unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
        ("sh".to_string(), script.display().to_string())
    }
}

#[test]
fn backup_copies_the_database_beside_itself() {
    let data = tempfile::tempdir().unwrap();
    rigger(data.path()).arg("init").assert().success();
    rigger(data.path())
        .arg("backup")
        .assert()
        .success()
        .stdout(predicate::str::contains("Copied to"));

    // Beside the database, which is the profile's.
    let copies: Vec<_> = std::fs::read_dir(data.path().join("profiles").join("line"))
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().ends_with(".bak"))
        .collect();
    assert_eq!(copies.len(), 1, "expected one backup, found {copies:?}");
    // Stamped with the schema it holds, so a restore says what it restores.
    let name = copies[0].file_name().to_string_lossy().to_string();
    assert!(
        name.starts_with("rigger.v") && name.contains('-'),
        "a backup must name the schema it holds: {name}"
    );
}

/// The copies directory, newest first, as the product sorts them.
fn copies(data: &Path) -> Vec<String> {
    let mut found: Vec<String> = std::fs::read_dir(data.join("profiles").join("line"))
        .unwrap()
        .filter_map(|e| e.ok())
        .map(|e| e.file_name().to_string_lossy().to_string())
        .filter(|n| n.ends_with(".bak"))
        .collect();
    // Sorted the way the product sorts: by the moment in the name, then by
    // the suffix as a number, so a text sort here cannot mask one there.
    found.sort_by_key(|name| {
        let stem = name.strip_suffix(".bak").unwrap_or(name);
        let tail = stem.rsplit_once(".v").map(|(_, t)| t).unwrap_or("");
        let mut parts = tail.split('-');
        let moment = format!("{}{}", parts.nth(1).unwrap_or(""), parts.next().unwrap_or(""));
        let seq: u32 = parts.next().map(|n| n.parse().unwrap_or(0)).unwrap_or(1);
        (moment, seq, name.clone())
    });
    found.reverse();
    found
}

/// Writes a copy whose name says it was taken `days` ago.
///
/// The age is read from the name, so a test can age one without waiting.
fn copy_aged(data: &Path, days: i64) -> String {
    let at = jiff::Timestamp::now().as_second() - days * 86_400;
    let stamp = jiff::Timestamp::from_second(at).unwrap().to_string();
    let (date, time) = stamp.split_once('T').unwrap();
    let name = format!(
        "rigger.v1-{}-{}.bak",
        date.replace('-', ""),
        time.chars().filter(char::is_ascii_digit).take(6).collect::<String>()
    );
    std::fs::write(data.join("profiles").join("line").join(&name), b"not a database, only a name").unwrap();
    name
}

#[test]
fn backup_keeps_the_newest_copies_and_deletes_the_rest() {
    let data = tempfile::tempdir().unwrap();
    rigger(data.path()).arg("init").assert().success();

    // Four copies, taken inside one second: the stamp is second-resolution,
    // so this is also the check that they do not overwrite one another.
    for _ in 0..4 {
        rigger(data.path()).arg("backup").arg("--keep").arg("10").assert().success();
    }
    assert_eq!(copies(data.path()).len(), 4, "four copies must be four files: {:?}", copies(data.path()));

    rigger(data.path())
        .arg("backup")
        .arg("--keep")
        .arg("2")
        .assert()
        .success()
        .stdout(predicate::str::contains("deleted"));

    // The fifth copy plus the one kept beside it.
    let left = copies(data.path());
    assert_eq!(left.len(), 2, "--keep 2 must leave two copies, found {left:?}");
}

/// The defect a text sort hides: `...-2.bak` sorts BEFORE the unsuffixed
/// name it was taken after, so "newest first" was backwards inside one
/// second - and rotation, which deletes from the end, would have thrown
/// away the copy it had just taken.
#[test]
fn a_copy_taken_in_the_same_second_is_the_newer_of_the_two() {
    let data = tempfile::tempdir().unwrap();
    rigger(data.path()).arg("init").assert().success();
    for _ in 0..4 {
        rigger(data.path()).arg("backup").arg("--keep").arg("10").assert().success();
    }

    // Whatever the names came out as, the last one taken must head the list.
    let listed = rigger(data.path()).arg("backup").arg("--list").arg("--keep").arg("10").assert().success();
    let out = String::from_utf8(listed.get_output().stdout.clone()).unwrap();
    let first = out.lines().nth(1).unwrap().split_whitespace().next().unwrap().to_string();
    let newest = copies(data.path()).first().unwrap().clone();
    assert_eq!(
        first, newest,
        "the list must open with the newest copy
{out}"
    );

    // And rotation must keep that one rather than delete it.
    rigger(data.path()).arg("backup").arg("--keep").arg("1").assert().success();
    let left = copies(data.path());
    assert_eq!(left.len(), 1, "expected one copy, found {left:?}");
    rigger(data.path())
        .arg("backup")
        .arg("--list")
        .assert()
        .success()
        .stdout(predicate::str::contains("unknown").not());
}

/// Rotation must never delete every copy, whatever it is asked for.
#[test]
fn keeping_none_still_keeps_the_copy_just_taken() {
    let data = tempfile::tempdir().unwrap();
    rigger(data.path()).arg("init").assert().success();
    rigger(data.path()).arg("backup").assert().success();
    rigger(data.path()).arg("backup").arg("--keep").arg("0").assert().success();

    let left = copies(data.path());
    assert_eq!(left.len(), 1, "`--keep 0` must keep the copy it just took, found {left:?}");
}

#[test]
fn doctor_reports_the_age_of_the_newest_copy() {
    let data = tempfile::tempdir().unwrap();
    rigger(data.path()).arg("init").assert().success();

    // No copy at all is the state worth naming loudest: one file, no insurance.
    rigger(data.path())
        .arg("doctor")
        .assert()
        .success()
        .stdout(predicate::str::contains("backup:    none"));

    copy_aged(data.path(), 3);
    rigger(data.path())
        .arg("doctor")
        .assert()
        .success()
        .stdout(predicate::str::contains("3 days ago").and(predicate::str::contains("older than a day")));

    // A week is the point where the copy stops resembling the record. The
    // fresher copy goes first: what is reported is the age of the NEWEST,
    // and adding an older one beside it must not change that.
    let newer = copy_aged(data.path(), 3);
    copy_aged(data.path(), 9);
    rigger(data.path())
        .arg("doctor")
        .assert()
        .success()
        .stdout(predicate::str::contains("3 days ago"));
    // Every copy of that day, not the one name just made. A stamp has
    // second resolution, so the two `copy_aged(3)` calls above are the same
    // file only when they land in the same second - and when they do not,
    // removing one name leaves a three-day copy behind, the week-old one is
    // never the newest, and the test passes or fails on how busy the
    // machine is. Caught by a full run under a gate, not by running this
    // file alone.
    let day = newer.split('-').nth(1).expect("a copy's name carries the day it was taken").to_string();
    for name in copies(data.path()).into_iter().filter(|n| n.contains(&day)) {
        std::fs::remove_file(data.path().join("profiles").join("line").join(&name)).unwrap();
    }
    rigger(data.path())
        .arg("doctor")
        .assert()
        .success()
        .stdout(predicate::str::contains("older than a week"));

    // And a copy from today is not advice at all.
    copy_aged(data.path(), 0);
    rigger(data.path())
        .arg("doctor")
        .assert()
        .success()
        .stdout(predicate::str::contains("backup:    today").and(predicate::str::contains("older than").not()));
}

/// The age is read from the name, not from the file's own mtime: a copied
/// or restored file carries a time that says when it was moved.
#[test]
fn a_copy_whose_name_holds_no_moment_is_not_given_an_age() {
    let data = tempfile::tempdir().unwrap();
    rigger(data.path()).arg("init").assert().success();
    // Right shape, impossible day: a month 13 must not be read as a date.
    std::fs::write(data.path().join("profiles").join("line").join("rigger.v1-20261345-080501.bak"), b"x").unwrap();

    rigger(data.path())
        .arg("doctor")
        .assert()
        .success()
        .stdout(predicate::str::contains("backup:    none"));

    // `doctor` alone cannot say WHICH layer refused it - the name parser or
    // the clock behind it - and a test that cannot fail for the reason it
    // names proves nothing. `--list` prints the age of each copy, so it
    // shows the name parser itself refusing to turn month 13 into a date,
    // while a well-formed neighbour on the same screen still gets one.
    copy_aged(data.path(), 2);
    rigger(data.path())
        .arg("backup")
        .arg("--list")
        .assert()
        .success()
        .stdout(predicate::str::contains("20261345").and(predicate::str::contains("unknown")))
        .stdout(predicate::str::contains("2 days ago"));
}

#[test]
fn ending_a_session_insures_the_record_when_the_newest_copy_is_a_day_old() {
    let data = tempfile::tempdir().unwrap();
    let root = data.path().join("here");
    repo(&root);
    rigger(data.path()).arg("init").assert().success();
    rigger(data.path())
        .arg("project")
        .arg("add")
        .arg(&root)
        .arg("--name")
        .arg("here")
        .assert()
        .success();

    // No copy yet: the first close must take one.
    rigger(data.path()).arg("session").arg("start").arg("here").assert().success();
    rigger(data.path())
        .arg("session")
        .arg("end")
        .arg("here")
        .assert()
        .success()
        .stdout(predicate::str::contains("copied the database"));
    assert_eq!(copies(data.path()).len(), 1, "the close must leave a copy: {:?}", copies(data.path()));

    // A second sitting on the same day does not: today's copy is insurance enough.
    rigger(data.path()).arg("session").arg("start").arg("here").assert().success();
    rigger(data.path())
        .arg("session")
        .arg("end")
        .arg("here")
        .assert()
        .success()
        .stdout(predicate::str::contains("copied the database").not());
    assert_eq!(copies(data.path()).len(), 1, "a fresh copy must not be taken twice a day");

    // Age the only copy past a day, and the next close insures again.
    for name in copies(data.path()) {
        std::fs::remove_file(data.path().join("profiles").join("line").join(name)).unwrap();
    }
    copy_aged(data.path(), 2);
    rigger(data.path()).arg("session").arg("start").arg("here").assert().success();
    rigger(data.path())
        .arg("session")
        .arg("end")
        .arg("here")
        .assert()
        .success()
        .stdout(predicate::str::contains("copied the database"));
    assert_eq!(copies(data.path()).len(), 2, "a stale copy must be joined by a fresh one");
}

/// A data directory with one project in it, for the document tests.
fn with_project(data: &Path, name: &str) {
    let root = data.join(name);
    repo(&root);
    rigger(data).arg("init").assert().success();
    rigger(data).arg("project").arg("add").arg(&root).arg("--name").arg(name).assert().success();
}

#[test]
fn a_document_is_written_read_back_and_listed() {
    let data = tempfile::tempdir().unwrap();
    with_project(data.path(), "demo");

    rigger(data.path())
        .arg("doc")
        .arg("list")
        .arg("demo")
        .assert()
        .success()
        .stdout(predicate::str::contains("no documents yet"));

    rigger(data.path())
        .args(["doc", "add", "demo", "Vision", "--kind", "vision", "--body", "# Vision\n\nBecause."])
        .assert()
        .success()
        .stdout(predicate::str::contains("Wrote vision"));

    // `show` prints the body and nothing else, so it can be redirected into
    // a file without a header glued to the top.
    let shown = rigger(data.path()).args(["doc", "show", "demo", "vision"]).assert().success();
    let out = String::from_utf8(shown.get_output().stdout.clone()).unwrap();
    assert_eq!(out.trim(), "# Vision\n\nBecause.", "show prints the body alone, got: {out:?}");

    rigger(data.path())
        .args(["doc", "list", "demo"])
        .assert()
        .success()
        .stdout(predicate::str::contains("vision").and(predicate::str::contains("today")));
}

/// A project has one vision. A second one is refused by name rather than
/// made, because two visions means nobody reads either.
#[test]
fn a_second_document_of_a_singular_kind_is_refused() {
    let data = tempfile::tempdir().unwrap();
    with_project(data.path(), "demo");
    rigger(data.path())
        .args(["doc", "add", "demo", "Vision", "--kind", "vision", "--body", "one"])
        .assert()
        .success();

    rigger(data.path())
        .args(["doc", "add", "demo", "Another", "--kind", "vision", "--body", "two"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("already has a vision").and(predicate::str::contains("doc edit demo vision")));

    // Research notes are many, and must not be caught by the same rule.
    rigger(data.path())
        .args(["doc", "add", "demo", "First", "--kind", "research", "--body", "a"])
        .assert()
        .success();
    rigger(data.path())
        .args(["doc", "add", "demo", "Second", "--kind", "research", "--body", "b"])
        .assert()
        .success();
}

/// The owner's hub is in Russian, and a title with no ASCII in it slugs to
/// nothing. An empty address is no address, so one is made from the kind.
#[test]
fn a_title_with_no_ascii_still_gets_an_address_that_can_be_typed() {
    let data = tempfile::tempdir().unwrap();
    with_project(data.path(), "demo");

    rigger(data.path())
        .args(["doc", "add", "demo", "Исследование", "--kind", "research", "--body", "текст"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Wrote research"));

    // A second one cannot take the same address, and is numbered.
    rigger(data.path())
        .args(["doc", "add", "demo", "Ещё одно", "--kind", "research", "--body", "ещё"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Wrote research-2"));

    rigger(data.path())
        .args(["doc", "show", "demo", "research"])
        .assert()
        .success()
        .stdout(predicate::str::contains("текст"));
}

#[test]
fn editing_replaces_the_body_and_keeps_the_day_it_was_started() {
    let data = tempfile::tempdir().unwrap();
    with_project(data.path(), "demo");
    rigger(data.path())
        .args(["doc", "add", "demo", "Vision", "--kind", "vision", "--body", "first"])
        .assert()
        .success();

    let before = rigger(data.path()).args(["doc", "show", "demo", "vision", "--json"]).assert().success();
    let before: serde_json::Value = serde_json::from_slice(&before.get_output().stdout).unwrap();

    rigger(data.path())
        .args(["doc", "edit", "demo", "vision", "--body", "second"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Wrote vision"));

    let after = rigger(data.path()).args(["doc", "show", "demo", "vision", "--json"]).assert().success();
    let after: serde_json::Value = serde_json::from_slice(&after.get_output().stdout).unwrap();

    assert_eq!(after["body"], "second");
    assert_eq!(after["created_at"], before["created_at"], "a rewrite must not restart the document's life");
    // The kind survives an edit that did not mention it.
    assert_eq!(after["kind"], "vision");

    // A title given alone changes the title and leaves the body be, without
    // opening an editor there is no terminal for.
    rigger(data.path())
        .args(["doc", "edit", "demo", "vision", "--title", "The vision"])
        .assert()
        .success();
    let renamed = rigger(data.path()).args(["doc", "show", "demo", "vision", "--json"]).assert().success();
    let renamed: serde_json::Value = serde_json::from_slice(&renamed.get_output().stdout).unwrap();
    assert_eq!(renamed["title"], "The vision");
    assert_eq!(renamed["body"], "second", "a rename must not touch the body");
}

#[test]
fn a_wrong_address_is_answered_with_the_addresses_there_are() {
    let data = tempfile::tempdir().unwrap();
    with_project(data.path(), "demo");

    rigger(data.path())
        .args(["doc", "show", "demo", "vision"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("none at all yet"));

    rigger(data.path())
        .args(["doc", "add", "demo", "Vision", "--kind", "vision", "--body", "x"])
        .assert()
        .success();
    rigger(data.path())
        .args(["doc", "show", "demo", "visoin"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("it has vision"));
}

/// A kind outside the vocabulary is refused with the list, rather than
/// quietly making a document nothing will ever look for.
#[test]
fn a_kind_rigger_does_not_know_is_refused_with_the_list() {
    let data = tempfile::tempdir().unwrap();
    with_project(data.path(), "demo");
    rigger(data.path())
        .args(["doc", "add", "demo", "Plan", "--kind", "plan", "--body", "x"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("vision").and(predicate::str::contains("research")));
}

#[test]
fn a_document_can_be_removed() {
    let data = tempfile::tempdir().unwrap();
    with_project(data.path(), "demo");
    rigger(data.path()).args(["doc", "add", "demo", "Notes", "--body", "x"]).assert().success();
    rigger(data.path())
        .args(["doc", "remove", "demo", "notes"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Removed notes"));
    rigger(data.path())
        .args(["doc", "list", "demo"])
        .assert()
        .success()
        .stdout(predicate::str::contains("no documents yet"));
}

/// A new document does not start blank: it starts from the questions its
/// kind exists to answer.
#[test]
fn a_new_document_is_seeded_with_the_skeleton_of_its_kind() {
    let data = tempfile::tempdir().unwrap();
    with_project(data.path(), "demo");

    rigger(data.path())
        .args(["doc", "template", "vision"])
        .assert()
        .success()
        .stdout(predicate::str::contains("## Why").and(predicate::str::contains("built-in skeleton")));

    // What the editor is handed is that skeleton, with the title in it.
    let shown = rigger(data.path())
        .args(["doc", "add", "demo", "Vision of demo", "--kind", "vision"])
        .env("RIGGER_EDITOR", editor_that_prints(data.path()))
        .assert()
        .success();
    let seed = String::from_utf8(shown.get_output().stdout.clone()).unwrap();
    assert!(seed.contains("# Vision of demo"), "the skeleton carries the title: {seed}");
    assert!(seed.contains("## Why"), "the skeleton carries its questions: {seed}");

    // Each kind asks its own.
    let research = rigger(data.path())
        .args(["doc", "add", "demo", "A question", "--kind", "research"])
        .env("RIGGER_EDITOR", editor_that_prints(data.path()))
        .assert()
        .success();
    let seed = String::from_utf8(research.get_output().stdout.clone()).unwrap();
    assert!(seed.contains("## The question"), "a research note asks its own questions: {seed}");
}

/// What rigger ships is in English, because everything it ships is. The
/// headings a person writes under are their own, and a file is how they say
/// so without patching the binary - the owner's hubs are in Russian.
#[test]
fn a_skeleton_of_your_own_replaces_the_one_that_ships() {
    let data = tempfile::tempdir().unwrap();
    with_project(data.path(), "demo");

    rigger(data.path())
        .args(["doc", "template", "vision", "--write"])
        .assert()
        .success()
        .stdout(predicate::str::contains("doc.vision.md"));

    // Written where the next run looks for it, and refused twice over so an
    // edited skeleton is never silently replaced.
    let written = data.path().join("profiles").join("line").join("doc.vision.md");
    assert!(written.is_file(), "the skeleton must be written where it is read from");
    rigger(data.path())
        .args(["doc", "template", "vision", "--write"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("already exists"));

    std::fs::write(&written, "# Видение {{title}}\n\n## 1. Зачем\n\n\n## 2. Главная идея\n").unwrap();
    rigger(data.path())
        .args(["doc", "template", "vision"])
        .assert()
        .success()
        .stdout(predicate::str::contains("## 1. Зачем").and(predicate::str::contains("doc.vision.md")));

    let shown = rigger(data.path())
        .args(["doc", "add", "demo", "kilna", "--kind", "vision"])
        .env("RIGGER_EDITOR", editor_that_prints(data.path()))
        .assert()
        .success();
    let seed = String::from_utf8(shown.get_output().stdout.clone()).unwrap();
    assert!(seed.contains("# Видение kilna"), "the placeholder becomes the title: {seed}");
    assert!(!seed.contains("## Why"), "the built-in skeleton must be gone: {seed}");

    // A kind without a file of its own still gets what ships.
    let research = rigger(data.path())
        .args(["doc", "add", "demo", "A question", "--kind", "research"])
        .env("RIGGER_EDITOR", editor_that_prints(data.path()))
        .assert()
        .success();
    let seed = String::from_utf8(research.get_output().stdout.clone()).unwrap();
    assert!(seed.contains("## The question"), "an unoverridden kind keeps its skeleton: {seed}");
}

/// Two rigger processes editing a document of the same name - two projects
/// each with a `vision`, or two sittings at once - must not share one
/// scratch file. They did: the name was `rigger-<project>-<slug>.md` in the
/// shared temporary directory, so the process that saved second won and the
/// other's prose vanished. Found by two tests colliding in parallel.
#[test]
fn two_processes_editing_the_same_document_name_do_not_share_a_scratch_file() {
    let a = tempfile::tempdir().unwrap();
    let b = tempfile::tempdir().unwrap();
    with_project(a.path(), "demo");
    with_project(b.path(), "demo");

    // An editor that takes its time, so the two overlap for certain.
    let slow = editor_script(a.path(), "slow", "sleep 1; cat \"$1\"", "ping -n 2 127.0.0.1 >nul & type %1");

    let mut first = std::process::Command::new(assert_cmd::cargo::cargo_bin("rigger"));
    first
        .env("RIGGER_DATA_DIR", a.path())
        .env("RIGGER_EDITOR", slow)
        .args(["doc", "add", "demo", "Vision", "--kind", "vision"])
        .stdout(std::process::Stdio::piped());
    let first = first.spawn().unwrap();

    // Both must go through an editor: `--body` never opens a scratch file,
    // so a test where one takes that path cannot collide at all.
    let overwrite = editor_script(
        b.path(),
        "overwrite",
        "echo written by the other process > \"$1\"",
        "echo written by the other process> %1",
    );
    rigger(b.path())
        .args(["doc", "add", "demo", "Vision", "--kind", "vision"])
        .env("RIGGER_EDITOR", overwrite)
        .assert()
        .success();

    let out = first.wait_with_output().unwrap();
    assert!(out.status.success(), "the first process must survive the second");

    // Each kept its own text.
    rigger(b.path())
        .args(["doc", "show", "demo", "vision"])
        .assert()
        .success()
        .stdout(predicate::str::contains("written by the other process"));
    rigger(a.path())
        .args(["doc", "show", "demo", "vision"])
        .assert()
        .success()
        .stdout(predicate::str::contains("## Why").and(predicate::str::contains("written by the other process").not()));
}

/// An "editor" as a script on disk, and the path that runs it.
///
/// Not a one-liner with quotes in it: `RIGGER_EDITOR` is split on
/// whitespace and quoting is deliberately unsupported, so `sh -c '...'`
/// arrives at the shell in pieces. That is the product's documented
/// behaviour, and a test has to live with it the way a person would - by
/// putting the script in a file. Found by CI: the quoted form passed on
/// Windows and failed on Linux and macOS.
fn editor_script(dir: &Path, name: &str, unix_body: &str, windows_body: &str) -> String {
    if cfg!(windows) {
        let script = dir.join(format!("{name}.cmd"));
        std::fs::write(&script, format!("@echo off\r\n{windows_body}\r\n")).unwrap();
        script.display().to_string()
    } else {
        let script = dir.join(format!("{name}.sh"));
        std::fs::write(&script, format!("#!/bin/sh\n{unix_body}\n")).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
        script.display().to_string()
    }
}

/// An "editor" that prints the file it is given and leaves it alone, so a
/// test can see what a person would have been shown.
fn editor_that_prints(dir: &Path) -> String {
    editor_script(dir, "print", "cat \"$1\"", "type %1")
}

/// A plan the record wrote cannot overrule the record.
///
/// Its empty boxes are a picture of how things stood at the last export,
/// not a decision about the work. Three tasks closed minutes earlier were
/// silently reopened by importing this project's own generated hub - the
/// version had not shipped, so the guard that protects a shipped stage's
/// tasks did not cover them.
#[test]
fn a_generated_plan_does_not_reopen_a_task_the_record_closed() {
    let data = tempfile::tempdir().unwrap();
    with_project(data.path(), "demo");
    let hub = data.path().join("hub");
    std::fs::create_dir_all(&hub).unwrap();
    let plan = "# План\n\n## v0.9.0 · Stage\n\n- [ ] first\n- [ ] second\n";

    // By hand first: an empty box there really does mean "not done".
    std::fs::write(hub.join("План.md"), plan).unwrap();
    rigger(data.path()).args(["import", "demo", "--hub"]).arg(&hub).assert().success();
    let by_hand = open_task_id(data.path(), "first");
    rigger(data.path()).args(["task", "status", &by_hand, "done"]).assert().success();
    rigger(data.path()).args(["import", "demo", "--hub"]).arg(&hub).assert().success();
    assert!(
        !task_is_done(data.path(), &by_hand),
        "a hub kept by hand is the owner's pen: its empty box reopens the task"
    );

    // The same file, marked as written by the record: now it cannot.
    std::fs::write(
        hub.join("План.md"),
        format!("<!-- generated by rigger; edits here are overwritten -->\n\n{plan}"),
    )
    .unwrap();
    // The same task throughout: an id does not move, and looking it up in
    // the packet again would fail exactly when it is closed.
    let generated = by_hand;
    rigger(data.path()).args(["task", "status", &generated, "done"]).assert().success();
    rigger(data.path()).args(["import", "demo", "--hub"]).arg(&hub).assert().success();
    assert!(task_is_done(data.path(), &generated), "a generated plan must not reopen what the record closed");
}

/// The id of a task by the words in its title, as the packet lists it.
fn open_task_id(data: &Path, title: &str) -> String {
    let out = rigger(data).args(["context", "demo", "--json"]).assert().success();
    let packet: serde_json::Value = serde_json::from_slice(&out.get_output().stdout).unwrap();
    packet["current"]["tasks"]
        .as_array()
        .unwrap()
        .iter()
        .find(|t| t["title"].as_str().unwrap().contains(title))
        .map(|t| t["id"].as_i64().unwrap().to_string())
        .unwrap_or_else(|| panic!("no task titled {title} in {packet}"))
}

/// Whether a task is closed in the record.
///
/// Asked of the record, not of the packet. A closed task leaves the packet,
/// because the stage in view is the earliest unshipped one, so reading its
/// absence there as "not done" is exactly the confusion this project has a
/// rule about. `task status` says what the status was before it set it.
fn task_is_done(data: &Path, id: &str) -> bool {
    let out = rigger(data).args(["task", "status", id, "done"]).assert().success();
    let said = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    said.contains("was already done")
}

/// A hub kept five files the record could not rebuild - the vision, the
/// rituals, the preamble of the decisions journal and the research notes.
/// Those are the reason a hub had to exist; `import` brings them in.
#[test]
fn importing_a_hub_takes_in_its_handwritten_texts() {
    let data = tempfile::tempdir().unwrap();
    with_project(data.path(), "demo");
    let hub = data.path().join("hub");
    std::fs::create_dir_all(hub.join("Исследования")).unwrap();
    std::fs::write(hub.join("Видение.md"), "# Видение demo\n\n## 1. Зачем\n\nЗатем.\n").unwrap();
    std::fs::write(hub.join("Ритуалы.md"), "# Ритуалы demo\n\nПравила.\n").unwrap();
    std::fs::write(
        hub.join("Решения.md"),
        "# Журнал решений\n\nappend-only, новые сверху.\n\n---\n\n## 2026-09-11 · Что-то\n\nТекст решения.\n",
    )
    .unwrap();
    std::fs::write(hub.join("Исследования").join("2026-09-04 — Инструмент.md"), "# Инструмент\n\nЧто?\n").unwrap();

    rigger(data.path())
        .args(["import", "demo", "--hub"])
        .arg(&hub)
        .assert()
        .success()
        .stdout(predicate::str::contains("documents  4 added"));

    // Each kind is there, under an address that can be typed.
    let listed = rigger(data.path()).args(["doc", "list", "demo"]).assert().success();
    let out = String::from_utf8(listed.get_output().stdout.clone()).unwrap();
    for slug in ["vision", "rituals", "decisions", "2026-09-04"] {
        assert!(out.contains(slug), "{slug} must be in the list:\n{out}");
    }

    // The decisions journal is split: its preamble is a document, while the
    // entries below it are events the record already holds.
    let shown = rigger(data.path()).args(["doc", "show", "demo", "decisions"]).assert().success();
    let preamble = String::from_utf8(shown.get_output().stdout.clone()).unwrap();
    assert!(preamble.contains("append-only"), "the preamble is the document: {preamble}");
    assert!(
        !preamble.contains("Текст решения"),
        "an entry is an event, not part of the document: {preamble}"
    );
}

/// Re-reading an unchanged hub must change nothing: a document edited with
/// `doc edit` and not yet exported must not be silently replaced by the
/// older file it came from.
#[test]
fn importing_the_same_hub_twice_changes_nothing_the_second_time() {
    let data = tempfile::tempdir().unwrap();
    with_project(data.path(), "demo");
    let hub = data.path().join("hub");
    std::fs::create_dir_all(&hub).unwrap();
    std::fs::write(hub.join("Видение.md"), "# Видение demo\n\nТекст.\n").unwrap();

    rigger(data.path()).args(["import", "demo", "--hub"]).arg(&hub).assert().success();
    rigger(data.path())
        .args(["import", "demo", "--hub"])
        .arg(&hub)
        .assert()
        .success()
        .stdout(predicate::str::contains("nothing changed"));

    // A file that really changed is taken in.
    std::fs::write(hub.join("Видение.md"), "# Видение demo\n\nДругой текст.\n").unwrap();
    rigger(data.path())
        .args(["import", "demo", "--hub"])
        .arg(&hub)
        .assert()
        .success()
        .stdout(predicate::str::contains("documents  0 added, 1 updated"));
}

/// `2026-09-04 — Инструмент` slugs to `2026-09-04`, because slugify keeps
/// only ASCII and these titles are Russian after the date. Two notes from
/// one day then shared an address and the second overwrote the first - a
/// research note lost without a word.
#[test]
fn two_research_notes_from_one_day_both_survive_the_import() {
    let data = tempfile::tempdir().unwrap();
    with_project(data.path(), "demo");
    let notes = data.path().join("hub").join("Исследования");
    std::fs::create_dir_all(&notes).unwrap();
    std::fs::write(notes.join("2026-09-04 — Первое.md"), "# Первое\n\nA\n").unwrap();
    std::fs::write(notes.join("2026-09-04 — Второе.md"), "# Второе\n\nB\n").unwrap();
    std::fs::write(notes.join("2026-09-05 — Третье.md"), "# Третье\n\nC\n").unwrap();

    rigger(data.path())
        .args(["import", "demo", "--hub"])
        .arg(data.path().join("hub"))
        .assert()
        .success()
        .stdout(predicate::str::contains("documents  3 added"));

    let listed = rigger(data.path()).args(["doc", "list", "demo", "--json"]).assert().success();
    let docs: serde_json::Value = serde_json::from_slice(&listed.get_output().stdout).unwrap();
    let titles: Vec<&str> = docs.as_array().unwrap().iter().map(|d| d["title"].as_str().unwrap()).collect();
    assert_eq!(titles.len(), 3, "every note must survive: {titles:?}");
    for title in ["Первое", "Второе", "Третье"] {
        assert!(titles.contains(&title), "{title} was lost: {titles:?}");
    }
}

/// `- (пусто)` under an empty queue is the template saying "nothing here",
/// and it read as a question. Two of them sat in the owner's inbox for four
/// days - as "пусто)", the display having eaten the opening bracket.
#[test]
fn a_placeholder_under_an_empty_queue_is_not_a_question() {
    let data = tempfile::tempdir().unwrap();
    with_project(data.path(), "demo");
    let hub = data.path().join("hub");
    std::fs::create_dir_all(&hub).unwrap();
    // Bare, and with the explanation a hub writes after it - which is the
    // form that got through.
    std::fs::write(
        hub.join("План.md"),
        "# План\n\n## Ждёт решения владельца\n\n- (пусто) — модель решается замером (v0.6).\n",
    )
    .unwrap();

    rigger(data.path()).args(["import", "demo", "--hub"]).arg(&hub).assert().success();
    rigger(data.path())
        .args(["inbox"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Nothing is waiting on you").or(predicate::str::contains("пусто").not()));
}

/// The subject of a question keeps an opening bracket: stripping every
/// non-alphanumeric leader turned `(пусто) — ...` into `пусто) — ...`.
#[test]
fn a_question_that_opens_with_a_bracket_keeps_it() {
    let data = tempfile::tempdir().unwrap();
    with_project(data.path(), "demo");
    let hub = data.path().join("hub");
    std::fs::create_dir_all(&hub).unwrap();
    std::fs::write(
        hub.join("План.md"),
        "# План\n\n## Ждёт решения владельца\n\n- (в работе) стоит ли поднимать мажор\n",
    )
    .unwrap();

    rigger(data.path()).args(["import", "demo", "--hub"]).arg(&hub).assert().success();
    rigger(data.path())
        .args(["inbox"])
        .assert()
        .success()
        .stdout(predicate::str::contains("(в работе)"));
}

/// `--check` named the files that would change and left the person to
/// guess what was in them - no use at all when the question is "have I
/// written something here the record would throw away".
#[test]
fn checking_an_export_shows_what_would_be_lost() {
    let data = tempfile::tempdir().unwrap();
    with_project(data.path(), "demo");
    let hub = data.path().join("hub");
    std::fs::create_dir_all(&hub).unwrap();
    std::fs::write(hub.join("План.md"), "# План\n\n## v0.9.0 · Stage\n\n- [ ] first\n").unwrap();
    rigger(data.path()).args(["import", "demo", "--hub"]).arg(&hub).assert().success();
    rigger(data.path()).args(["export", "demo", "--adopt", "--hub"]).arg(&hub).assert().success();

    let mut plan = std::fs::read_to_string(hub.join("План.md")).unwrap();
    plan.push_str("\nРукописная строка.\n");
    std::fs::write(hub.join("План.md"), plan).unwrap();

    rigger(data.path())
        .args(["export", "demo", "--check", "--hub"])
        .arg(&hub)
        .assert()
        .success()
        .stdout(predicate::str::contains("would change").and(predicate::str::contains("- Рукописная строка.")));

    // A check writes nothing.
    assert!(
        std::fs::read_to_string(hub.join("План.md")).unwrap().contains("Рукописная строка."),
        "--check must not write"
    );
}

/// The handwritten texts go back out as files when asked, and come back in
/// unchanged: a research note keeps the date its filename is addressed by.
#[test]
fn exporting_documents_writes_files_that_import_reads_back_unchanged() {
    let data = tempfile::tempdir().unwrap();
    with_project(data.path(), "demo");
    let hub = data.path().join("hub");
    std::fs::create_dir_all(hub.join("Исследования")).unwrap();
    std::fs::write(hub.join("Видение.md"), "# Видение demo\n\nТекст.\n").unwrap();
    std::fs::write(hub.join("Ритуалы.md"), "# Ритуалы demo\n\nПравила.\n").unwrap();
    // A title that is not the filename, which is the case that broke: the
    // export composed a name from the title and wrote a second file beside
    // the one the note came from, so one note became two.
    std::fs::write(hub.join("Исследования").join("2026-09-04 — Заметка.md"), "# Заметка о другом\n\nТело.\n").unwrap();
    rigger(data.path()).args(["import", "demo", "--hub"]).arg(&hub).assert().success();

    let out = data.path().join("out");
    std::fs::create_dir_all(&out).unwrap();
    rigger(data.path())
        .args(["export", "demo", "--adopt", "--docs", "--hub"])
        .arg(&out)
        .assert()
        .success();

    assert!(out.join("Видение.md").is_file(), "the vision must be written");
    assert!(out.join("Ритуалы.md").is_file(), "the rituals must be written");
    assert!(
        out.join("Исследования").join("2026-09-04 — Заметка.md").is_file(),
        "a research note keeps the date it is addressed by: {:?}",
        std::fs::read_dir(out.join("Исследования"))
            .unwrap()
            .flatten()
            .map(|e| e.file_name())
            .collect::<Vec<_>>()
    );

    // One note, one file: written back under the name it came in as.
    let names: Vec<String> = std::fs::read_dir(out.join("Исследования"))
        .unwrap()
        .flatten()
        .map(|e| e.file_name().to_string_lossy().to_string())
        .collect();
    assert_eq!(names.len(), 1, "one note must not become two files: {names:?}");

    // Read back, they say the same thing: nothing changed.
    rigger(data.path())
        .args(["import", "demo", "--hub"])
        .arg(&out)
        .assert()
        .success()
        .stdout(predicate::str::contains("nothing changed"));

    // Without --docs they are not written at all: they are a cache, and
    // four more files in every diff serve nobody.
    let bare = data.path().join("bare");
    std::fs::create_dir_all(&bare).unwrap();
    rigger(data.path()).args(["export", "demo", "--adopt", "--hub"]).arg(&bare).assert().success();
    assert!(!bare.join("Видение.md").exists(), "documents are written only when asked for");
}

/// The command tree is deep enough that clap's derived parser overflowed
/// the 1 MB stack Windows gives the main thread, in debug builds only -
/// `rigger --version` died before reaching any code of ours, and every
/// test runs a debug binary. The work runs on a thread with room now.
#[test]
fn the_command_tree_is_walked_without_overflowing_the_stack() {
    Command::cargo_bin("rigger").unwrap().arg("--version").assert().success();
    Command::cargo_bin("rigger").unwrap().arg("--help").assert().success();
    // The deepest branch of the tree, which is what actually walks it.
    Command::cargo_bin("rigger").unwrap().args(["doc", "add", "--help"]).assert().success();
}

/// rigger never exits 2, whatever it is asked.
///
/// 2 is clap's own code for a usage error, and it is also the code an
/// assistant's Stop hook uses to refuse the stop and hold the turn open. A
/// hook is written once into a settings file and never looked at again, so
/// a typo in it - or an older rigger on the PATH without the subcommand -
/// would wedge every session it fired in. Found by installing the hook for
/// real: the rigger on PATH was one release behind, and the command exited
/// 2 rather than being ignored.
#[test]
fn a_usage_error_never_exits_with_the_code_that_blocks_a_hook() {
    let data = tempfile::tempdir().unwrap();
    for args in [vec!["no-such-command"], vec!["session", "end", "--no-such-flag"], vec!["project"]] {
        let out = rigger(data.path()).args(&args).assert().failure();
        let code = out.get_output().status.code();
        assert_eq!(code, Some(1), "{args:?} exited {code:?}, and 2 blocks a Stop hook");
    }

    // Help and version are answers, not failures.
    for args in [vec!["--help"], vec!["--version"]] {
        rigger(data.path()).args(&args).assert().success();
    }
}

#[test]
fn doctor_reports_the_database_before_and_after_init() {
    let data = tempfile::tempdir().unwrap();
    rigger(data.path())
        .arg("doctor")
        .assert()
        .success()
        .stdout(predicate::str::contains("missing - run `rigger init`"));

    let root = data.path().join("one");
    repo(&root);
    rigger(data.path()).arg("init").assert().success();
    rigger(data.path()).args(["project", "add"]).arg(&root).assert().success();

    rigger(data.path())
        .arg("doctor")
        .assert()
        .success()
        .stdout(predicate::str::contains("schema:    version").and(predicate::str::contains("projects:  1")));
    rigger(data.path())
        .args(["doctor", "--json"])
        .assert()
        .success()
        .stdout(predicate::str::contains("\"schema_version\":"));
}