githttp-fs 1.14.0

A git-backed content management database served over HTTP
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
// githttp-fs
//
// Git-based Content Management System
// Copyright: 2026, Valerian Saliou <valerian@valeriansaliou.name>
// License: Mozilla Public License v2.0 (MPL v2.0)

//! Integration tests for the `/files` routes: write, read, delete, move,
//! list, count, batch read, and existence.

use axum::http::StatusCode;
use serde_json::json;

use crate::tests::harness::{author, TestServer};

const TENANT: &str = "/docs/acme";

/// Leaf names of a listing level, in the order the server returned them.
fn names(nodes: &serde_json::Value) -> Vec<String> {
    nodes
        .as_array()
        .expect("listing level is not an array")
        .iter()
        .map(|node| node["name"].as_str().unwrap_or_default().to_string())
        .collect()
}

/// The children of a named directory node in a listing level.
fn children<'a>(nodes: &'a serde_json::Value, name: &str) -> &'a serde_json::Value {
    nodes
        .as_array()
        .expect("listing level is not an array")
        .iter()
        .find(|node| node["name"] == name)
        .unwrap_or_else(|| panic!("no directory named {} in {}", name, nodes))
        .get("children")
        .unwrap_or_else(|| panic!("{} has no children", name))
}

// --- Write and read ------------------------------------------------------

#[tokio::test]
async fn a_first_write_initialises_the_repository_and_reads_back() {
    // Repositories are auto-initialised on first write — no provisioning
    // step exists in the API.
    let server = TestServer::start().await;

    assert!(!server.repo_path("docs", "acme").exists());

    let sha = server.write_file(TENANT, "docs/intro.md", "# Hello").await;

    assert!(!sha.is_empty());
    assert!(server.repo_path("docs", "acme").join(".git").is_dir());

    let response = server.get(&format!("{}/files/docs/intro.md", TENANT)).await;

    response.expect_status(StatusCode::OK);

    assert_eq!(response.json()["path"], "docs/intro.md");
    assert_eq!(response.json()["content"], "# Hello");
    // No order index anywhere, so the file is unlisted.
    assert_eq!(response.json()["position"], -1);
}

#[tokio::test]
async fn content_round_trips_byte_for_byte() {
    let server = TestServer::start().await;

    let content =
        "---\ntitle: Ünicode ✓\n---\r\n\r\nline with trailing spaces   \nno final newline";

    server.write_file(TENANT, "a.md", content).await;

    assert_eq!(
        server.read_file(TENANT, "a.md").await.as_deref(),
        Some(content)
    );
}

#[tokio::test]
async fn rewriting_identical_content_is_a_no_op_that_returns_head() {
    // Documented: clients that blindly re-write unchanged files cannot
    // pollute history with empty commits.
    let server = TestServer::start().await;

    let first = server.write_file(TENANT, "a.md", "same").await;
    let second = server.write_file(TENANT, "a.md", "same").await;

    assert_eq!(first, second, "an unchanged write must not create a commit");

    let commits = server.get(&format!("{}/commits", TENANT)).await;

    // Only the initialisation commit and the one write.
    assert_eq!(
        commits.json()["commits"].as_array().unwrap().len(),
        2,
        "an unchanged write created a commit"
    );
}

#[tokio::test]
async fn updating_content_creates_a_new_commit() {
    let server = TestServer::start().await;

    let first = server.write_file(TENANT, "a.md", "one").await;
    let second = server.write_file(TENANT, "a.md", "two").await;

    assert_ne!(first, second);
    assert_eq!(
        server.read_file(TENANT, "a.md").await.as_deref(),
        Some("two")
    );
}

#[tokio::test]
async fn a_write_requires_an_author() {
    let server = TestServer::start().await;

    let response = server
        .put(
            &format!("{}/files/a.md", TENANT),
            json!({ "content": "no author" }),
        )
        .await;

    assert_eq!(response.status, StatusCode::UNPROCESSABLE_ENTITY);
}

#[tokio::test]
async fn reading_a_missing_file_or_tenant_is_not_found() {
    let server = TestServer::start().await;

    server
        .get(&format!("{}/files/missing.md", TENANT))
        .await
        .expect_status(StatusCode::NOT_FOUND);

    server
        .get("/docs/no-such-tenant/files/a.md")
        .await
        .expect_status(StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn a_folder_path_is_not_a_file_on_the_read_route() {
    let server = TestServer::start().await;

    server.write_file(TENANT, "docs/intro.md", "x").await;

    server
        .get(&format!("{}/files/docs", TENANT))
        .await
        .expect_status(StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn path_traversal_is_refused_at_the_route() {
    let server = TestServer::start().await;

    server.write_file(TENANT, "a.md", "x").await;

    // Percent-encoded, because a URL parser resolves `..` segments on the
    // client side — these have to reach the server spelled as traversal.
    for path in [
        "%2E%2E%2Fescape.md",
        "docs%2F%2E%2E%2F%2E%2E%2Fescape.md",
        ".git/config",
        "docs%2F.git%2Fconfig",
    ] {
        let response = server
            .put(
                &format!("{}/files/{}", TENANT, path),
                json!({ "author": author(), "content": "x" }),
            )
            .await;

        assert_eq!(
            response.status,
            StatusCode::BAD_REQUEST,
            "traversal accepted: {}",
            path
        );
    }
}

#[tokio::test]
async fn an_invalid_tenant_id_is_refused_before_anything_is_touched() {
    let server = TestServer::start().await;

    let response = server.get("/docs/bad..tenant/files/a.md").await;

    response.expect_status(StatusCode::BAD_REQUEST);

    assert!(response.error_message().contains("invalid tenant"));
}

#[tokio::test]
async fn the_extension_whitelist_applies_to_writes_and_move_destinations() {
    let server = TestServer::builder()
        .allowed_extensions(&["md", "mdx"])
        .start()
        .await;

    server.write_file(TENANT, "a.md", "x").await;

    server
        .put(
            &format!("{}/files/a.txt", TENANT),
            json!({ "author": author(), "content": "x" }),
        )
        .await
        .expect_status(StatusCode::BAD_REQUEST);

    // A move destination is checked; the source is not, so files written
    // before a whitelist was configured stay movable.
    server
        .post(
            &format!("{}/files/a.md/move", TENANT),
            json!({ "author": author(), "destination": "b.txt" }),
        )
        .await
        .expect_status(StatusCode::BAD_REQUEST);

    server
        .post(
            &format!("{}/files/a.md/move", TENANT),
            json!({ "author": author(), "destination": "b.mdx" }),
        )
        .await
        .expect_status(StatusCode::OK);
}

// --- Existence check -----------------------------------------------------

#[tokio::test]
async fn head_answers_existence_without_a_body() {
    let server = TestServer::start().await;

    server.write_file(TENANT, "docs/intro.md", "x").await;

    let response = server
        .head(&format!("{}/files/docs/intro.md", TENANT))
        .await;

    response.expect_status(StatusCode::OK);

    assert!(response.text.is_empty(), "HEAD must carry no body");

    server
        .head(&format!("{}/files/docs/missing.md", TENANT))
        .await
        .expect_status(StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn check_prefix_path_widens_existence_to_folders() {
    let server = TestServer::start().await;

    server.write_file(TENANT, "docs/guides/intro.md", "x").await;

    // Without the flag, a folder is simply "not a file".
    server
        .head(&format!("{}/files/docs/guides", TENANT))
        .await
        .expect_status(StatusCode::NOT_FOUND);

    server
        .head(&format!(
            "{}/files/docs/guides?check_prefix_path=true",
            TENANT
        ))
        .await
        .expect_status(StatusCode::OK);

    // With the parameter on, a trailing slash is tolerated.
    server
        .head(&format!(
            "{}/files/docs/guides/?check_prefix_path=true",
            TENANT
        ))
        .await
        .expect_status(StatusCode::OK);

    server
        .head(&format!(
            "{}/files/docs/nope?check_prefix_path=true",
            TENANT
        ))
        .await
        .expect_status(StatusCode::NOT_FOUND);
}

// --- Delete and move -----------------------------------------------------

#[tokio::test]
async fn deleting_a_file_removes_it() {
    let server = TestServer::start().await;

    server.write_file(TENANT, "a.md", "x").await;

    server
        .delete(
            &format!("{}/files/a.md", TENANT),
            json!({ "author": author() }),
        )
        .await
        .expect_status(StatusCode::OK);

    assert!(server.read_file(TENANT, "a.md").await.is_none());

    // Deleting it again is a 404 rather than a silent success.
    server
        .delete(
            &format!("{}/files/a.md", TENANT),
            json!({ "author": author() }),
        )
        .await
        .expect_status(StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn moving_a_file_relocates_its_content() {
    let server = TestServer::start().await;

    server.write_file(TENANT, "docs/old.md", "# Hello").await;

    server
        .post(
            &format!("{}/files/docs/old.md/move", TENANT),
            json!({ "author": author(), "destination": "docs/new.md" }),
        )
        .await
        .expect_status(StatusCode::OK);

    assert!(server.read_file(TENANT, "docs/old.md").await.is_none());
    assert_eq!(
        server.read_file(TENANT, "docs/new.md").await.as_deref(),
        Some("# Hello")
    );
}

#[tokio::test]
async fn post_dispatches_on_the_url_suffix_never_on_the_body() {
    // Documented: the suffix — never the body's shape — decides which
    // operation runs, so a mistyped field cannot silently turn one into
    // the other.
    let server = TestServer::start().await;

    server.write_file(TENANT, "a.md", "x").await;

    let response = server
        .post(
            &format!("{}/files/a.md", TENANT),
            json!({ "author": author(), "destination": "b.md" }),
        )
        .await;

    response.expect_status(StatusCode::BAD_REQUEST);

    server
        .post(
            &format!("{}/files/a.md/unknown", TENANT),
            json!({ "author": author(), "destination": "b.md" }),
        )
        .await
        .expect_status(StatusCode::BAD_REQUEST);
}

// --- Listing -------------------------------------------------------------

/// Writes a small tree used by several listing tests.
async fn seed_tree(server: &TestServer) {
    for path in [
        "README.md",
        "docs/intro.md",
        "docs/guides/advanced.md",
        "docs/guides/basics.md",
        "notes/todo.md",
        ".hidden/secret.md",
        ".dotfile.md",
    ] {
        server.write_file(TENANT, path, "x").await;
    }
}

#[tokio::test]
async fn listing_sorts_directories_before_files_then_alphabetically() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    let response = server.get(&format!("{}/files", TENANT)).await;

    response.expect_status(StatusCode::OK);

    let body = response.json();

    assert_eq!(body["page"], 1);
    assert_eq!(body["per_page"], 100);
    assert_eq!(body["has_more"], false);

    // Hidden entries are excluded by default, so neither `.hidden/` nor
    // `.dotfile.md` shows.
    assert_eq!(names(&body["files"]), vec!["docs", "notes", "README.md"]);

    assert_eq!(
        names(children(&body["files"], "docs")),
        vec!["guides", "intro.md"]
    );
}

#[tokio::test]
async fn include_hidden_files_reveals_dot_entries_and_their_subtrees() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    let body = server
        .get(&format!("{}/files?include_hidden_files=true", TENANT))
        .await
        .json();

    assert_eq!(
        names(&body["files"]),
        vec![".hidden", "docs", "notes", ".dotfile.md", "README.md"]
    );

    assert_eq!(
        names(children(&body["files"], ".hidden")),
        vec!["secret.md"]
    );
}

#[tokio::test]
async fn prefix_path_scopes_the_listing_to_a_subdirectory() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    let body = server
        .get(&format!("{}/files?prefix_path=/docs", TENANT))
        .await
        .json();

    assert_eq!(names(&body["files"]), vec!["guides", "intro.md"]);

    // A non-existent folder is an empty tree, not an error.
    let empty = server
        .get(&format!("{}/files?prefix_path=/nope", TENANT))
        .await
        .json();

    assert_eq!(names(&empty["files"]), Vec::<String>::new());

    // A hidden folder named explicitly lists its contents — the hidden
    // filter applies to entry names, not to prefix_path resolution.
    let hidden = server
        .get(&format!("{}/files?prefix_path=/.hidden", TENANT))
        .await
        .json();

    assert_eq!(names(&hidden["files"]), vec!["secret.md"]);
}

#[tokio::test]
async fn prefix_path_rejects_traversal() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    for prefix in ["/../etc", "/docs/../..", "/.git"] {
        server
            .get(&format!("{}/files?prefix_path={}", TENANT, prefix))
            .await
            .expect_status(StatusCode::BAD_REQUEST);
    }
}

#[tokio::test]
async fn maximum_depth_bounds_the_listing_and_leaves_childless_stubs() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    let body = server
        .get(&format!("{}/files?maximum_depth=1", TENANT))
        .await
        .json();

    assert_eq!(names(&body["files"]), vec!["docs", "notes", "README.md"]);

    // Directories deeper than the limit appear as stubs with no children.
    assert_eq!(
        children(&body["files"], "docs").as_array().unwrap().len(),
        0
    );

    server
        .get(&format!("{}/files?maximum_depth=0", TENANT))
        .await
        .expect_status(StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn pagination_windows_over_root_level_entries() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    let first = server
        .get(&format!("{}/files?page=1&per_page=2", TENANT))
        .await
        .json();

    assert_eq!(names(&first["files"]), vec!["docs", "notes"]);
    assert_eq!(first["has_more"], true);

    let second = server
        .get(&format!("{}/files?page=2&per_page=2", TENANT))
        .await
        .json();

    assert_eq!(names(&second["files"]), vec!["README.md"]);
    assert_eq!(second["has_more"], false);
}

#[tokio::test]
async fn file_name_starts_with_matches_leaf_names_case_insensitively() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    let body = server
        .get(&format!("{}/files?file_name_starts_with=Intro", TENANT))
        .await
        .json();

    // The match is nested, so its ancestor directory is present purely as
    // structure — and a directory holding no match is pruned entirely.
    assert_eq!(names(&body["files"]), vec!["docs"]);
    assert_eq!(names(children(&body["files"], "docs")), vec!["intro.md"]);
}

#[tokio::test]
async fn file_name_starts_with_accepts_an_array_of_prefixes() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    let body = server
        .get(&format!(
            "{}/files?file_name_starts_with=%5B%22intro%22%2C%20%22readme%22%5D",
            TENANT
        ))
        .await
        .json();

    assert_eq!(names(&body["files"]), vec!["docs", "README.md"]);
}

#[tokio::test]
async fn a_matched_directory_brings_its_whole_subtree() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    let body = server
        .get(&format!("{}/files?file_name_starts_with=guid", TENANT))
        .await
        .json();

    assert_eq!(names(&body["files"]), vec!["docs"]);

    // Every descendant shows, whether or not its own name matches.
    assert_eq!(
        names(children(children(&body["files"], "docs"), "guides")),
        vec!["advanced.md", "basics.md"]
    );
}

#[tokio::test]
async fn file_name_starts_with_rejects_empty_and_malformed_values() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    for value in ["", "%5B%5D", "%5B%22%22%5D", "%5B1%5D", "%5B"] {
        server
            .get(&format!("{}/files?file_name_starts_with={}", TENANT, value))
            .await
            .expect_status(StatusCode::BAD_REQUEST);
    }
}

// --- Exact-path selection ------------------------------------------------

/// URL-encodes a JSON array of paths for the `file_paths` query parameter, so
/// the tests below read as the paths they select rather than as percent escapes.
fn file_paths_query(paths: &[&str]) -> String {
    let json = serde_json::to_string(paths).expect("paths are serialisable");

    json.bytes()
        .map(|byte| match byte {
            b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => {
                (byte as char).to_string()
            }
            other => format!("%{:02X}", other),
        })
        .collect()
}

#[tokio::test]
async fn file_paths_selects_exactly_the_named_paths_and_skips_missing_ones() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    let body = server
        .get(&format!(
            "{}/files?file_paths={}",
            TENANT,
            file_paths_query(&["docs/intro.md", "nowhere.md", "README.md"])
        ))
        .await
        .json();

    // Documented: "a path HEAD does not hold is left out of the result rather
    // than erroring" — so `nowhere.md` costs the request nothing.
    assert_eq!(names(&body["files"]), vec!["docs", "README.md"]);

    // A named file is a leaf, its ancestor directory present purely as the
    // structure leading to it — the same shape `file_name_starts_with` returns.
    assert_eq!(names(children(&body["files"], "docs")), vec!["intro.md"]);

    // Naming nothing that exists is an empty listing, not a 404.
    let empty = server
        .get(&format!(
            "{}/files?file_paths={}",
            TENANT,
            file_paths_query(&["nowhere.md"])
        ))
        .await;

    empty.expect_status(StatusCode::OK);

    assert_eq!(names(&empty.json()["files"]), Vec::<String>::new());
}

#[tokio::test]
async fn file_paths_accepts_a_bare_path_and_tolerates_a_trailing_slash() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    // The bare-string spelling, exactly as `file_name_starts_with` accepts one.
    let bare = server
        .get(&format!("{}/files?file_paths=README.md", TENANT))
        .await
        .json();

    assert_eq!(names(&bare["files"]), vec!["README.md"]);

    // A folder spelled with a trailing slash is the same folder.
    let folder = server
        .get(&format!(
            "{}/files?file_paths={}",
            TENANT,
            file_paths_query(&["notes/"])
        ))
        .await
        .json();

    assert_eq!(names(&folder["files"]), vec!["notes"]);
    assert_eq!(names(children(&folder["files"], "notes")), vec!["todo.md"]);
}

#[tokio::test]
async fn file_paths_are_relative_to_prefix_path() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    let body = server
        .get(&format!(
            "{}/files?prefix_path=/docs&file_paths={}",
            TENANT,
            file_paths_query(&["intro.md", "guides/basics.md"])
        ))
        .await
        .json();

    // Paths are spelled against the listing root, and reported against it.
    assert_eq!(names(&body["files"]), vec!["guides", "intro.md"]);
    assert_eq!(names(children(&body["files"], "guides")), vec!["basics.md"]);

    // A path spelled from the repository root therefore selects nothing under
    // a prefix.
    let root_spelling = server
        .get(&format!(
            "{}/files?prefix_path=/docs&file_paths={}",
            TENANT,
            file_paths_query(&["docs/intro.md"])
        ))
        .await
        .json();

    assert_eq!(names(&root_spelling["files"]), Vec::<String>::new());
}

#[tokio::test]
async fn a_named_directory_brings_its_whole_subtree() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    let body = server
        .get(&format!(
            "{}/files?file_paths={}",
            TENANT,
            file_paths_query(&["docs/guides"])
        ))
        .await
        .json();

    assert_eq!(names(&body["files"]), vec!["docs"]);

    // Every descendant shows, exactly as a name-matched directory expands.
    assert_eq!(
        names(children(children(&body["files"], "docs"), "guides")),
        vec!["advanced.md", "basics.md"]
    );
}

#[tokio::test]
async fn file_paths_excludes_hidden_paths_unless_they_are_asked_for() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    // Hidden entries are gated by path, not just by leaf name: naming a file
    // inside a hidden directory is not a way around the flag.
    let hidden = server
        .get(&format!(
            "{}/files?file_paths={}",
            TENANT,
            file_paths_query(&[".dotfile.md", ".hidden/secret.md"])
        ))
        .await
        .json();

    assert_eq!(names(&hidden["files"]), Vec::<String>::new());

    let shown = server
        .get(&format!(
            "{}/files?include_hidden_files=true&file_paths={}",
            TENANT,
            file_paths_query(&[".dotfile.md", ".hidden/secret.md"])
        ))
        .await
        .json();

    assert_eq!(names(&shown["files"]), vec![".hidden", ".dotfile.md"]);
    assert_eq!(
        names(children(&shown["files"], ".hidden")),
        vec!["secret.md"]
    );
}

#[tokio::test]
async fn file_paths_never_selects_an_order_index() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    server
        .put(
            &format!("{}/order", TENANT),
            json!({ "author": author(), "order": ["README.md", "docs/"] }),
        )
        .await
        .expect_status(StatusCode::OK);

    // Documented: the order index "is invisible to every `/files` route",
    // whatever `include_hidden_files` says — so it is not selectable by path
    // either.
    let body = server
        .get(&format!(
            "{}/files?include_hidden_files=true&file_paths={}",
            TENANT,
            file_paths_query(&[".order.json"])
        ))
        .await
        .json();

    assert_eq!(names(&body["files"]), Vec::<String>::new());
}

#[tokio::test]
async fn file_paths_is_bounded_by_maximum_depth() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    // A named path deeper than the limit is not returned at all — a name
    // search would never have walked to it either.
    let bounded = server
        .get(&format!(
            "{}/files?maximum_depth=1&file_paths={}",
            TENANT,
            file_paths_query(&["README.md", "docs/intro.md"])
        ))
        .await
        .json();

    assert_eq!(names(&bounded["files"]), vec!["README.md"]);

    // A named directory sitting *at* the limit renders as a childless stub,
    // exactly as the plain listing stubs it.
    let stub = server
        .get(&format!(
            "{}/files?maximum_depth=1&file_paths={}",
            TENANT,
            file_paths_query(&["docs"])
        ))
        .await
        .json();

    assert_eq!(names(&stub["files"]), vec!["docs"]);
    assert_eq!(
        children(&stub["files"], "docs").as_array().unwrap().len(),
        0
    );

    // One level further down, the expansion is itself depth-bounded.
    let nested = server
        .get(&format!(
            "{}/files?maximum_depth=2&file_paths={}",
            TENANT,
            file_paths_query(&["docs"])
        ))
        .await
        .json();

    assert_eq!(
        names(children(&nested["files"], "docs")),
        vec!["guides", "intro.md"]
    );
    assert_eq!(
        children(children(&nested["files"], "docs"), "guides")
            .as_array()
            .unwrap()
            .len(),
        0
    );
}

#[tokio::test]
async fn a_date_window_intersects_an_exact_path_selection() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    let query = format!(
        "file_paths={}&include_date_from=2000-01-01T00:00:00Z",
        file_paths_query(&["docs/intro.md"])
    );

    let kept = server
        .get(&format!("{}/files?{}", TENANT, query))
        .await
        .json();

    assert_eq!(names(&kept["files"]), vec!["docs"]);

    let dropped = server
        .get(&format!(
            "{}/files?{}&include_date_to=2001-01-01T00:00:00Z",
            TENANT, query
        ))
        .await
        .json();

    assert_eq!(names(&dropped["files"]), Vec::<String>::new());
}

#[tokio::test]
async fn file_paths_and_file_name_starts_with_must_not_be_combined() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    // Two selections over the same tree: one request carries at most one, so a
    // caller cannot be left guessing which one shaped an empty result.
    server
        .get(&format!(
            "{}/files?file_name_starts_with=intro&file_paths={}",
            TENANT,
            file_paths_query(&["README.md"])
        ))
        .await
        .expect_status(StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn file_paths_rejects_empty_and_unsafe_values() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    for value in [
        // An empty value, an empty array, and an empty path.
        "",
        "%5B%5D",
        "%5B%22%22%5D",
        // Malformed array spellings.
        "%5B1%5D",
        "%5B",
        // Paths are sanitised exactly as the read route's `*path` is.
        "docs/../../etc/passwd",
        "%5B%22..%2Fetc%22%5D",
    ] {
        server
            .get(&format!("{}/files?file_paths={}", TENANT, value))
            .await
            .expect_status(StatusCode::BAD_REQUEST);
    }
}

#[tokio::test]
async fn date_bounds_are_validated_strictly() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    for query in [
        "include_date_from=2026-06-16",
        "include_date_from=nonsense",
        "include_date_to=2026-13-01T00:00:00Z",
        // Equal bounds select nothing, so they are a 400 rather than an
        // empty listing.
        "include_date_from=2026-06-16T10:00:00Z&include_date_to=2026-06-16T10:00:00Z",
        // `from` must be strictly before `to`.
        "include_date_from=2026-06-17T10:00:00Z&include_date_to=2026-06-16T10:00:00Z",
        "include_date_type=whenever",
    ] {
        server
            .get(&format!("{}/files?{}", TENANT, query))
            .await
            .expect_status(StatusCode::BAD_REQUEST);
    }
}

#[tokio::test]
async fn a_date_window_around_now_keeps_every_file() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    let body = server
        .get(&format!(
            "{}/files?include_date_from=2000-01-01T00:00:00Z&include_date_to=2999-01-01T00:00:00Z",
            TENANT
        ))
        .await
        .json();

    assert_eq!(names(&body["files"]), vec!["docs", "notes", "README.md"]);

    // A window entirely in the past keeps nothing, and directories left
    // holding no surviving file are pruned rather than shown as stubs.
    let empty = body_of_past_window(&server).await;

    assert_eq!(names(&empty["files"]), Vec::<String>::new());
}

async fn body_of_past_window(server: &TestServer) -> serde_json::Value {
    server
        .get(&format!(
            "{}/files?include_date_from=2000-01-01T00:00:00Z&include_date_to=2001-01-01T00:00:00Z",
            TENANT
        ))
        .await
        .json()
}

// --- Count ---------------------------------------------------------------

#[tokio::test]
async fn counting_walks_the_same_tree_as_the_listing() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    let body = server.get(&format!("{}/count/files", TENANT)).await.json();

    // Visible files: README.md, docs/intro.md, docs/guides/{advanced,basics}.md,
    // notes/todo.md. Visible directories: docs, docs/guides, notes.
    assert_eq!(body["files"], 5);
    assert_eq!(body["directories"], 3);

    let with_hidden = server
        .get(&format!("{}/count/files?include_hidden_files=true", TENANT))
        .await
        .json();

    assert_eq!(with_hidden["files"], 7);
    assert_eq!(with_hidden["directories"], 4);
}

#[tokio::test]
async fn counting_honours_prefix_path_and_maximum_depth() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    let scoped = server
        .get(&format!("{}/count/files?prefix_path=/docs", TENANT))
        .await
        .json();

    assert_eq!(scoped["files"], 3);
    assert_eq!(scoped["directories"], 1);

    // A directory sitting at the depth limit is counted — it exists at a
    // visible level — but its contents are not.
    let bounded = server
        .get(&format!(
            "{}/count/files?prefix_path=/docs&maximum_depth=1",
            TENANT
        ))
        .await
        .json();

    assert_eq!(bounded["files"], 1);
    assert_eq!(bounded["directories"], 1);

    server
        .get(&format!("{}/count/files?maximum_depth=0", TENANT))
        .await
        .expect_status(StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn restrict_file_extensions_narrows_files_but_never_directories() {
    let server = TestServer::start().await;

    server.write_file(TENANT, "docs/intro.md", "x").await;
    server.write_file(TENANT, "docs/page.mdx", "x").await;
    server.write_file(TENANT, "docs/notes.txt", "x").await;
    server.write_file(TENANT, "docs/LICENSE", "x").await;

    let body = server
        .get(&format!(
            "{}/count/files?restrict_file_extensions=%5B%22md%22%5D",
            TENANT
        ))
        .await
        .json();

    assert_eq!(body["files"], 1);
    assert_eq!(body["directories"], 1);

    // Leading dots are trimmed and matching is case-insensitive.
    let both = server
        .get(&format!(
            "{}/count/files?restrict_file_extensions=%5B%22.MD%22%2C%22mdx%22%5D",
            TENANT
        ))
        .await
        .json();

    assert_eq!(both["files"], 2);

    for value in ["%5B%5D", "%22md%22", "%5B%22%22%5D"] {
        server
            .get(&format!(
                "{}/count/files?restrict_file_extensions={}",
                TENANT, value
            ))
            .await
            .expect_status(StatusCode::BAD_REQUEST);
    }
}

// --- Seeked reads --------------------------------------------------------

#[tokio::test]
async fn a_seeked_read_narrows_content_to_the_window() {
    let server = TestServer::start().await;

    server
        .write_file(TENANT, "a.md", "---\ntitle: Hello\n---\n# Heading\nBody\n")
        .await;

    let body = server
        .get(&format!(
            "{}/files/a.md?seek_from_line_starts_with=%5B%22---%22%5D\
             &seek_to_line_starts_with=%24seek_from_line_starts_with",
            TENANT
        ))
        .await
        .json();

    assert_eq!(body["content"], "---\ntitle: Hello\n---\n");
    // The response shape is unchanged — only `content` narrows.
    assert_eq!(body["path"], "a.md");
}

#[tokio::test]
async fn a_seek_that_matches_nothing_is_an_empty_body_not_an_error() {
    let server = TestServer::start().await;

    server.write_file(TENANT, "a.md", "# Heading\n").await;

    let response = server
        .get(&format!(
            "{}/files/a.md?seek_from_line_starts_with=%5B%22@@@%22%5D",
            TENANT
        ))
        .await;

    response.expect_status(StatusCode::OK);

    assert_eq!(response.json()["content"], "");
}

#[tokio::test]
async fn malformed_seek_parameters_are_rejected() {
    let server = TestServer::start().await;

    server.write_file(TENANT, "a.md", "x\n").await;

    for query in [
        "seek_from_line_starts_with=---",
        "seek_from_line_starts_with=%5B%5D",
        "seek_lines_maximum=0",
        "seek_to_line_starts_with=%24seek_from_line_starts_with",
    ] {
        server
            .get(&format!("{}/files/a.md?{}", TENANT, query))
            .await
            .expect_status(StatusCode::BAD_REQUEST);
    }
}

// --- Batch read ----------------------------------------------------------

#[tokio::test]
async fn a_batch_read_is_index_aligned_with_its_request() {
    let server = TestServer::start().await;

    server.write_file(TENANT, "a.md", "# A").await;
    server.write_file(TENANT, "docs/b.md", "# B").await;

    let response = server
        .post(
            &format!("{}/batch/files/read", TENANT),
            json!({ "files": ["a.md", "missing.md", "docs/b.md"] }),
        )
        .await;

    response.expect_status(StatusCode::OK);

    let files = response.json()["files"].clone();

    assert_eq!(files[0]["path"], "a.md");
    assert_eq!(files[0]["content"], "# A");
    // `null` strictly means "not found".
    assert!(files[1].is_null());
    assert_eq!(files[2]["path"], "docs/b.md");

    // No `position` field: a batch spans arbitrary directories, so ordering
    // information would cost one index read per distinct parent.
    assert!(files[0].get("position").is_none());
}

#[tokio::test]
async fn a_folder_reads_as_null_in_a_batch() {
    let server = TestServer::start().await;

    server.write_file(TENANT, "docs/b.md", "# B").await;

    let body = server
        .post(
            &format!("{}/batch/files/read", TENANT),
            json!({ "files": ["docs"] }),
        )
        .await
        .json();

    assert!(body["files"][0].is_null());
}

#[tokio::test]
async fn an_entry_seek_replaces_the_request_level_one_entirely() {
    // Documented: no field-by-field merge.
    let server = TestServer::start().await;

    let content = "---\ntitle: T\n---\nbody\nmore\n";

    server.write_file(TENANT, "a.md", content).await;
    server.write_file(TENANT, "b.md", content).await;

    let body = server
        .post(
            &format!("{}/batch/files/read", TENANT),
            json!({
                "files": ["a.md", { "path": "b.md", "seek": { "lines_maximum": 2 } }],
                "seek": {
                    "from_line_starts_with": ["---"],
                    "to_line_starts_with": "$seek_from_line_starts_with"
                }
            }),
        )
        .await
        .json();

    assert_eq!(body["files"][0]["content"], "---\ntitle: T\n---\n");
    // The entry seek carries no from/to filters even though the shared one
    // sets them, so the window starts at line 0.
    assert_eq!(body["files"][1]["content"], "---\ntitle: T\n");
}

#[tokio::test]
async fn a_batch_is_validated_before_the_repository_is_touched() {
    let server = TestServer::builder()
        .batch_read_maximum_files(2)
        .start()
        .await;

    server.write_file(TENANT, "a.md", "# A").await;

    // Over the cap.
    server
        .post(
            &format!("{}/batch/files/read", TENANT),
            json!({ "files": ["a.md", "b.md", "c.md"] }),
        )
        .await
        .expect_status(StatusCode::BAD_REQUEST);

    // Empty list.
    server
        .post(
            &format!("{}/batch/files/read", TENANT),
            json!({ "files": [] }),
        )
        .await
        .expect_status(StatusCode::BAD_REQUEST);

    // Duplicate after sanitisation — `/a.md` and `a.md` are one path.
    let duplicate = server
        .post(
            &format!("{}/batch/files/read", TENANT),
            json!({ "files": ["a.md", "/a.md"] }),
        )
        .await;

    duplicate.expect_status(StatusCode::BAD_REQUEST);

    // Invalid path.
    server
        .post(
            &format!("{}/batch/files/read", TENANT),
            json!({ "files": ["../escape.md"] }),
        )
        .await
        .expect_status(StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn a_batch_read_on_a_missing_tenant_is_not_found() {
    let server = TestServer::start().await;

    server
        .post(
            "/docs/no-such-tenant/batch/files/read",
            json!({ "files": ["a.md"] }),
        )
        .await
        .expect_status(StatusCode::NOT_FOUND);
}

// --- Tenant deletion -----------------------------------------------------

#[tokio::test]
async fn deleting_a_tenant_removes_the_whole_repository() {
    let server = TestServer::start().await;

    server.write_file(TENANT, "a.md", "x").await;

    assert!(server.repo_path("docs", "acme").exists());

    server
        .request(reqwest::Method::DELETE, TENANT, None, true)
        .await
        .expect_status(StatusCode::OK);

    assert!(!server.repo_path("docs", "acme").exists());

    server
        .get(&format!("{}/files/a.md", TENANT))
        .await
        .expect_status(StatusCode::NOT_FOUND);

    // Deleting it again is a 404.
    server
        .request(reqwest::Method::DELETE, TENANT, None, true)
        .await
        .expect_status(StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn a_directory_holding_no_commit_reads_as_no_tenant() {
    // A store can hold a tenant directory that is not a repository yet (an
    // operator removed `.git` by hand) or a repository with no commit (a
    // replica's first import interrupted by an older build). Neither holds
    // anything a caller could read, so neither is a server error.
    let server = TestServer::start().await;

    std::fs::create_dir_all(server.repo_path("docs", "empty")).unwrap();
    git2::Repository::init(server.repo_path("docs", "unborn")).unwrap();

    for tenant in ["/docs/empty", "/docs/unborn"] {
        server
            .get(&format!("{}/files/a.md", tenant))
            .await
            .expect_status(StatusCode::NOT_FOUND);

        server
            .get(&format!("{}/files", tenant))
            .await
            .expect_status(StatusCode::NOT_FOUND);

        server
            .get(&format!("{}/commits", tenant))
            .await
            .expect_status(StatusCode::NOT_FOUND);
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_tenant_being_created_or_deleted_never_reads_as_a_server_error() {
    // Reads never take the tenant write lock, so a read racing a tenant's
    // creation or deletion must find either no tenant or a whole one —
    // never a directory half-way to being a repository.
    let server = TestServer::start().await;

    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));

    let reader = {
        let stop = stop.clone();
        let client = reqwest::Client::new();
        let url = format!("{}{}/files/a.md", server.base_url, TENANT);
        let api_key = server.api_key.clone();

        tokio::spawn(async move {
            let mut unexpected = Vec::new();
            let mut reads = 0_usize;

            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
                let response = client
                    .get(&url)
                    .bearer_auth(&api_key)
                    .send()
                    .await
                    .expect("read failed");

                reads += 1;

                let status = response.status();

                if status != StatusCode::OK && status != StatusCode::NOT_FOUND {
                    unexpected.push(format!(
                        "{}: {}",
                        status,
                        response.text().await.unwrap_or_default()
                    ));
                }
            }

            (reads, unexpected)
        })
    };

    for _ in 0..25 {
        server.write_file(TENANT, "a.md", "x").await;

        server
            .request(reqwest::Method::DELETE, TENANT, None, true)
            .await
            .expect_status(StatusCode::OK);
    }

    stop.store(true, std::sync::atomic::Ordering::Relaxed);

    let (reads, unexpected) = reader.await.expect("reader panicked");

    assert!(reads > 0, "the reader never ran");
    assert!(unexpected.is_empty(), "unexpected reads: {:?}", unexpected);

    // Nothing of the staging it went through is left beside the tenants.
    let leftovers: Vec<_> = std::fs::read_dir(server.repos_path.join("docs"))
        .unwrap()
        .flatten()
        .map(|entry| entry.file_name())
        .collect();

    assert!(leftovers.is_empty(), "left behind: {:?}", leftovers);
}

#[tokio::test]
async fn two_collections_holding_the_same_tenant_id_are_separate_repositories() {
    // `collection_id` and `tenant_id` together are the repository identity —
    // this is why a hook receiver must key on both.
    let server = TestServer::start().await;

    server.write_file("/docs/acme", "a.md", "docs copy").await;
    server.write_file("/blog/acme", "a.md", "blog copy").await;

    assert_eq!(
        server.read_file("/docs/acme", "a.md").await.as_deref(),
        Some("docs copy")
    );
    assert_eq!(
        server.read_file("/blog/acme", "a.md").await.as_deref(),
        Some("blog copy")
    );

    server
        .request(reqwest::Method::DELETE, "/docs/acme", None, true)
        .await
        .expect_status(StatusCode::OK);

    assert!(server.read_file("/blog/acme", "a.md").await.is_some());
}

// --- Date-range filtering ------------------------------------------------

/// Builds a repository whose files have distinct, widely separated git
/// dates — which no sequence of API calls can produce, since every write is
/// stamped `now`.
///
/// The resulting dates:
///
/// | file     | created    | updated    |
/// |----------|------------|------------|
/// | `a.md`   | 2020-01-01 | 2022-01-01 |
/// | `b.md`   | 2021-01-01 | 2021-01-01 |
async fn seed_dated_tree(server: &TestServer) {
    use crate::tests::fixture::{at, commit_files_at};

    // One ordinary write so the repository exists with its root commit.
    server.write_file(TENANT, "seed.md", "seed").await;

    let repo = server.repo_path("docs", "acme");

    commit_files_at(
        &repo,
        at("2020-01-01T00:00:00Z"),
        "add a",
        &[("a.md", b"one")],
    );
    commit_files_at(
        &repo,
        at("2021-01-01T00:00:00Z"),
        "add b",
        &[("b.md", b"one")],
    );
    commit_files_at(
        &repo,
        at("2022-01-01T00:00:00Z"),
        "edit a",
        &[("a.md", b"two")],
    );
}

#[tokio::test]
async fn the_date_window_is_half_open_on_the_updated_date_by_default() {
    let server = TestServer::start().await;

    seed_dated_tree(&server).await;

    // `updated` is the most recent commit that touched the file.
    let body = server
        .get(&format!(
            "{}/files?include_date_from=2021-06-01T00:00:00Z",
            TENANT
        ))
        .await
        .json();

    // a.md was last touched in 2022, and the seed file is stamped now —
    // both are after the bound. b.md's last touch (2021-01) is not.
    assert_eq!(names(&body["files"]), vec!["a.md", "seed.md"]);

    let body = server
        .get(&format!(
            "{}/files?include_date_to=2021-06-01T00:00:00Z",
            TENANT
        ))
        .await
        .json();

    // b.md (2021-01) is in; a.md (2022) is out; the seed file is stamped now
    // and so is out too.
    assert_eq!(names(&body["files"]), vec!["b.md"]);
}

#[tokio::test]
async fn include_date_type_created_selects_a_different_set_from_the_same_window() {
    let server = TestServer::start().await;

    seed_dated_tree(&server).await;

    // Same bound, different date: by `created`, a.md belongs to 2020 rather
    // than to 2022, so it falls inside a window that excludes it by
    // `updated`.
    let body = server
        .get(&format!(
            "{}/files?include_date_to=2021-06-01T00:00:00Z&include_date_type=created",
            TENANT
        ))
        .await
        .json();

    assert_eq!(names(&body["files"]), vec!["a.md", "b.md"]);
}

#[tokio::test]
async fn a_date_filter_prunes_directories_left_holding_nothing() {
    use crate::tests::fixture::{at, commit_files_at};

    let server = TestServer::start().await;

    server.write_file(TENANT, "seed.md", "seed").await;

    let repo = server.repo_path("docs", "acme");

    commit_files_at(
        &repo,
        at("2020-01-01T00:00:00Z"),
        "old",
        &[("old/a.md", b"x")],
    );
    commit_files_at(
        &repo,
        at("2022-01-01T00:00:00Z"),
        "new",
        &[("new/b.md", b"x")],
    );

    let body = server
        .get(&format!(
            "{}/files?include_date_from=2021-01-01T00:00:00Z&include_date_to=2023-01-01T00:00:00Z",
            TENANT
        ))
        .await
        .json();

    // Directories survive only as the structure leading to a surviving file.
    assert_eq!(names(&body["files"]), vec!["new"]);
    assert_eq!(names(children(&body["files"], "new")), vec!["b.md"]);
}

#[tokio::test]
async fn a_depth_limited_date_filter_keeps_the_directories_holding_a_match() {
    use crate::tests::fixture::{at, commit_files_at};

    let server = TestServer::start().await;

    server.write_file(TENANT, "seed.md", "seed").await;

    let repo = server.repo_path("docs", "acme");

    commit_files_at(
        &repo,
        at("2020-01-01T00:00:00Z"),
        "old",
        &[("old/deep/a.md", b"x")],
    );
    commit_files_at(
        &repo,
        at("2022-01-01T00:00:00Z"),
        "new",
        &[("new/deep/b.md", b"x")],
    );

    let body = server
        .get(&format!(
            "{}/files?maximum_depth=1&include_date_from=2021-01-01T00:00:00Z&include_date_to=2023-01-01T00:00:00Z",
            TENANT
        ))
        .await
        .json();

    // "`maximum_depth` bounds what is *returned* rather than what is looked
    // at: a directory sitting at the limit comes back as the same childless
    // stub the plain listing returns, but only when the subtree below it holds
    // an in-window file." Both directories hold their file below the limit;
    // only `new`'s is inside the window, and `seed.md` is stamped now.
    assert_eq!(names(&body["files"]), vec!["new"]);
    assert_eq!(children(&body["files"], "new").as_array().unwrap().len(), 0);
}

#[tokio::test]
async fn a_date_filter_intersects_with_a_name_search() {
    let server = TestServer::start().await;

    seed_dated_tree(&server).await;

    // A file must match both the name prefix and the date window.
    let body = server
        .get(&format!(
            "{}/files?file_name_starts_with=a&include_date_to=2021-06-01T00:00:00Z",
            TENANT
        ))
        .await
        .json();

    assert_eq!(names(&body["files"]), Vec::<String>::new());

    let body = server
        .get(&format!(
            "{}/files?file_name_starts_with=b&include_date_to=2021-06-01T00:00:00Z",
            TENANT
        ))
        .await
        .json();

    assert_eq!(names(&body["files"]), vec!["b.md"]);
}

#[tokio::test]
async fn a_name_matched_directory_at_the_depth_limit_still_needs_an_in_window_file() {
    use crate::tests::fixture::{at, commit_files_at};

    let server = TestServer::start().await;

    let repo = server.repo_path("docs", "acme");

    server.write_file(TENANT, "seed.md", "seed").await;

    commit_files_at(
        &repo,
        at("2020-01-01T00:00:00Z"),
        "old",
        &[("guides-old/deep/a.md", b"x")],
    );
    commit_files_at(
        &repo,
        at("2022-01-01T00:00:00Z"),
        "new",
        &[("guides-new/deep/b.md", b"x")],
    );

    let body = server
        .get(&format!(
            "{}/files?file_name_starts_with=guides&maximum_depth=1&include_date_from=2021-01-01T00:00:00Z&include_date_to=2023-01-01T00:00:00Z",
            TENANT
        ))
        .await
        .json();

    // Both directories match the name and sit at the depth limit, so the
    // date window is what separates them — the stub rule is the same one the
    // plain date-filtered listing follows.
    assert_eq!(names(&body["files"]), vec!["guides-new"]);
    assert_eq!(
        children(&body["files"], "guides-new")
            .as_array()
            .unwrap()
            .len(),
        0
    );
}

// --- The date filter's safety timer ---------------------------------------

/// A tenant whose history is long enough that dating every one of its files
/// takes real time: one commit per file, so the `updated` walk cannot stop
/// early — the oldest file is only dated by the oldest commit.
async fn seed_long_history(server: &TestServer) -> usize {
    use crate::tests::fixture::{at, commit_files_at};

    const COMMITS: usize = 500;

    server.write_file(TENANT, "seed.md", "seed").await;

    let repo = server.repo_path("docs", "acme");
    let when = at("2020-01-01T00:00:00Z");

    for index in 0..COMMITS {
        let path = format!("file-{:04}.md", index);

        commit_files_at(&repo, when, "add one", &[(path.as_str(), b"x")]);
    }

    COMMITS
}

#[tokio::test]
async fn a_date_filter_that_spends_its_budget_answers_with_what_it_dated() {
    // `limits.date_filter_maximum_ms` is a safety timer, not a deadline the
    // request fails on: the walk stops, the entries dated so far are the
    // answer, and `partial` says so.
    let server = TestServer::builder()
        .date_filter_maximum_ms(1)
        .start()
        .await;

    let commits = seed_long_history(&server).await;

    let body = server
        .get(&format!(
            "{}/files?include_date_from=2019-01-01T00:00:00Z&include_date_to=2021-01-01T00:00:00Z&per_page=500",
            TENANT
        ))
        .await
        .json();

    assert_eq!(body["partial"], true);

    // Every file is inside the window, so a complete answer would hold all of
    // them — the short one holds fewer, and nothing that was not asked for.
    let returned = body["files"].as_array().unwrap().len();

    assert!(
        returned < commits,
        "a budget of 1ms dated all {} files",
        commits
    );

    for name in names(&body["files"]) {
        assert!(name.starts_with("file-"), "unexpected entry {}", name);
    }
}

#[tokio::test]
async fn a_date_filter_answers_in_full_under_the_default_budget() {
    // The same history under the shipped ten-second timer, which no walk of
    // this size comes close to spending: the answer is complete, and says so.
    // The default is only a guard against the pathological case, never
    // something an ordinary listing notices.
    let server = TestServer::start().await;

    let commits = seed_long_history(&server).await;

    let body = server
        .get(&format!(
            "{}/files?include_date_from=2019-01-01T00:00:00Z&include_date_to=2021-01-01T00:00:00Z&per_page=500",
            TENANT
        ))
        .await
        .json();

    assert_eq!(body["partial"], false);
    assert_eq!(body["has_more"], false);

    // Every commit of the fixture, and only those: the tenant's seed file is
    // stamped now and sits outside the window.
    assert_eq!(body["files"].as_array().unwrap().len(), commits);
}

#[tokio::test]
async fn a_listing_without_a_date_filter_is_never_partial() {
    // No date filter walks no history, so the timer has nothing to cut short
    // — the field is there whatever the listing did, so a client can read it
    // without knowing which mode produced the answer.
    let server = TestServer::builder()
        .date_filter_maximum_ms(1)
        .start()
        .await;

    seed_tree(&server).await;

    let body = server.get(&format!("{}/files", TENANT)).await.json();

    assert_eq!(body["partial"], false);
}

// --- Search and depth composition ----------------------------------------

#[tokio::test]
async fn a_matched_directory_at_the_depth_limit_renders_as_a_childless_stub() {
    // `maximum_depth` bounds the descent uniformly: a directory sitting *at*
    // the limit shows because it matched, but nothing below it is walked.
    let server = TestServer::start().await;

    seed_tree(&server).await;

    let body = server
        .get(&format!(
            "{}/files?file_name_starts_with=docs&maximum_depth=1",
            TENANT
        ))
        .await
        .json();

    assert_eq!(names(&body["files"]), vec!["docs"]);
    assert_eq!(
        children(&body["files"], "docs").as_array().unwrap().len(),
        0
    );
}

#[tokio::test]
async fn a_match_below_the_depth_limit_is_never_found() {
    let server = TestServer::start().await;

    seed_tree(&server).await;

    // `advanced.md` lives at depth 3 and is invisible to a depth-2 listing.
    let body = server
        .get(&format!(
            "{}/files?file_name_starts_with=advanced&maximum_depth=2",
            TENANT
        ))
        .await
        .json();

    assert_eq!(names(&body["files"]), Vec::<String>::new());
}

// --- Content that cannot be represented ----------------------------------

#[tokio::test]
async fn a_file_that_is_not_utf8_fails_the_read_rather_than_reading_as_missing() {
    use crate::tests::fixture::commit_files_at;

    let server = TestServer::start().await;

    server.write_file(TENANT, "ok.md", "fine").await;

    // A blob the write route could never have accepted — its `content` is a
    // JSON string — but which a hand-made commit can hold.
    commit_files_at(
        &server.repo_path("docs", "acme"),
        1_780_000_000,
        "binary",
        &[("binary.md", &[0xff, 0xfe, 0x00])],
    );

    let single = server.get(&format!("{}/files/binary.md", TENANT)).await;

    single.expect_status(StatusCode::UNPROCESSABLE_ENTITY);

    assert!(
        single.error_message().contains("binary.md"),
        "{}",
        single.text
    );

    // In a batch it is a hard failure too, naming the path: `null` must
    // strictly mean "not found", never "unreadable".
    let batch = server
        .post(
            &format!("{}/batch/files/read", TENANT),
            json!({ "files": ["ok.md", "binary.md"] }),
        )
        .await;

    batch.expect_status(StatusCode::UNPROCESSABLE_ENTITY);

    assert!(
        batch.error_message().contains("binary.md"),
        "{}",
        batch.text
    );
}

// --- Seeking a packed object ---------------------------------------------

#[tokio::test]
async fn seeking_works_the_same_on_a_packed_object_as_on_a_loose_one() {
    // Loose objects are seeked through a streaming ODB read that stops
    // inflating early; libgit2 cannot stream a packed object, so those fall
    // back to a cursor over the blob. Both must return the same window.
    let server = TestServer::start().await;

    let content = "---\ntitle: T\n---\n# Heading\nbody\n";

    server.write_file(TENANT, "a.md", content).await;

    let query = format!(
        "{}/files/a.md?seek_from_line_starts_with=%5B%22---%22%5D\
         &seek_to_line_starts_with=%24seek_from_line_starts_with",
        TENANT
    );

    let loose = server.get(&query).await.json()["content"].clone();

    assert_eq!(loose, "---\ntitle: T\n---\n");

    // Consolidate every loose object into a packfile, then read again.
    crate::git::GitMaintenance::run(&server.repo_path("docs", "acme"), false, true)
        .expect("maintenance failed");

    assert_eq!(
        crate::git::GitMaintenance::pack_count(&server.repo_path("docs", "acme")),
        1
    );

    let packed = server.get(&query).await.json()["content"].clone();

    assert_eq!(packed, loose);

    // And a whole-file read is unaffected too.
    assert_eq!(
        server.read_file(TENANT, "a.md").await.as_deref(),
        Some(content)
    );
}