vivac 0.17.2

Provenance tree for work: every node knows which node it was born from
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
//! `vivac web` — the defenses, proved over a real socket.
//!
//! `d149` put the rules in `src/web/gate.rs` as a pure function so every
//! denial could be a unit test with no server at all. This is the other
//! half: the same rules, read off a `TcpStream` a browser would actually
//! open, so a header that never reaches `Gate::admit` -- wrong case, wrong
//! name, dropped by the socket layer -- would still show up here.
//!
//! There is no HTTP client in the dependency tree and this does not add one:
//! the client is ours to write, and a request is four lines and a blank one.

mod common;
use common::Sandbox;
use std::io::{BufRead, BufReader, Write};
use std::net::TcpStream;
use std::process::{Child, Command, Stdio};
use std::time::Duration;

const BIN: &str = env!("CARGO_BIN_EXE_vivac");

/// The port out of a boot url's authority.
///
/// The test does not pick the port: `--port 0` lets the operating system
/// pick, and the server prints the address it bound. So the number arrives
/// from the process that is holding the socket, and there is no instant in
/// which it is free for something else to take -- which is the point. This
/// used to bind a port here, read its number, release it, and hand that
/// number to the child; on a runner with tests in parallel another test
/// took it in the gap and the server died at startup (`f385`).
fn port_of(url: &str) -> u16 {
    let authority = url.trim_start_matches("http://");
    let authority = authority.split('/').next().unwrap_or(authority);
    authority
        .rsplit(':')
        .next()
        .and_then(|p| p.parse().ok())
        .unwrap_or_else(|| panic!("no port in the boot url: {url}"))
}

struct Server {
    child: Child,
    port: u16,
    /// The URL printed at startup, key and all. Good for exactly one call.
    boot_url: String,
    /// What is left of the child's stdout once `start_serving` has read the
    /// two lines every boot prints. Kept rather than dropped so a test that
    /// needs a line printed after those two -- `d810`'s unreachable-projects
    /// sentence, the only one there is -- can still read it.
    stdout: BufReader<std::process::ChildStdout>,
}

impl Server {
    fn start(sandbox: &Sandbox) -> Server {
        Server::start_serving(&sandbox.0, sandbox.global_home(), &[])
    }

    /// Like `start`, but naming the roots to serve with one `--project` per
    /// directory, so a server can be asked to serve more than the one it
    /// starts in. `dir` is still the working directory, and since `d199`
    /// that is all it is: `vivac web` no longer needs a tree at or above its
    /// cwd, and what the cwd decides now is only where `/` lands.
    fn start_serving(
        dir: &std::path::Path,
        home: &std::path::Path,
        roots: &[&std::path::Path],
    ) -> Server {
        let mut args: Vec<std::ffi::OsString> = vec![
            "web".into(),
            // Zero, and never a number of ours: see `port_of`.
            "--port".into(),
            "0".into(),
            "--no-open".into(),
        ];
        for r in roots {
            args.push("--project".into());
            args.push((*r).into());
        }
        let mut child = Command::new(BIN)
            .current_dir(dir)
            .env("VIVAC_HOME", home)
            .env("TZ", "UTC")
            .args(&args)
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .spawn()
            .unwrap();
        let stdout = child.stdout.take().unwrap();
        let mut reader = BufReader::new(stdout);
        let mut boot_url = None;
        // Two lines are printed before the server ever blocks in `recv()`,
        // and both contain `http://`: the first names the address it bound,
        // the second is the boot url. Only the second carries the key -- and
        // it names the same address, so it is the one datum the test needs
        // and the port comes out of it too.
        for _ in 0..10 {
            let mut line = String::new();
            let n = reader.read_line(&mut line).unwrap();
            assert!(n > 0, "the server exited before printing a boot url");
            if let Some(at) = line.find("http://") {
                if line.contains("?k=") {
                    boot_url = Some(line[at..].trim().to_string());
                    break;
                }
            }
        }
        let boot_url = boot_url.expect("no boot url in the server's startup lines");
        Server {
            child,
            port: port_of(&boot_url),
            boot_url,
            stdout: reader,
        }
    }

    /// The path and query of the boot url, with the scheme and address
    /// stripped: what `call` below needs, since it addresses the port
    /// itself.
    fn boot_path(&self) -> String {
        let after_scheme = self.boot_url.trim_start_matches("http://");
        let slash = after_scheme
            .find('/')
            .expect("the boot url has no path at all");
        after_scheme[slash..].to_string()
    }

    fn host(&self) -> String {
        format!("127.0.0.1:{}", self.port)
    }

    /// One more line of startup output, beyond the two `start_serving`
    /// already consumed finding the boot url. Blocks until the child writes
    /// one, so only a scenario that is guaranteed to print a third line --
    /// `d810`'s unreachable-projects sentence -- may call this; anywhere
    /// else, nothing after the boot url is ever printed, and this would
    /// hang forever.
    fn next_startup_line(&mut self) -> String {
        let mut line = String::new();
        self.stdout.read_line(&mut line).unwrap();
        line.trim().to_string()
    }
}

impl Drop for Server {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

/// A running server over a sandbox it does not outlive.
///
/// Field order matters here: Rust drops a struct's fields in the order they
/// are declared, and `server` has to go first. Killing the process before
/// the sandbox removes its directory is what keeps the cleanup from racing
/// a process that still has files in it open.
struct Up {
    server: Server,
    _sandbox: Sandbox,
}

impl Up {
    fn port(&self) -> u16 {
        self.server.port
    }

    fn boot_path(&self) -> String {
        self.server.boot_path()
    }

    fn host(&self) -> String {
        self.server.host()
    }
}

struct Answer {
    status: u16,
    headers: Vec<(String, String)>,
    body: String,
}

impl Answer {
    fn header(&self, name: &str) -> Option<&str> {
        self.headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case(name))
            .map(|(_, v)| v.as_str())
    }
}

/// The body, however the server chose to frame it.
///
/// `tiny_http` answers with `Content-Length` while it can and switches to
/// `Transfer-Encoding: chunked` once a response outgrows its buffer. Every
/// page was small enough for the first branch until the map arrived at
/// rather more than a megabyte, and a client that only knew lengths read
/// every one of those pages as empty -- with a `200` in hand, which is the
/// worst way to be wrong. The client is ours, so it learns the other
/// framing rather than the pages staying small enough to avoid it.
fn read_body(reader: &mut impl BufRead, content_length: usize, chunked: bool) -> Vec<u8> {
    if !chunked {
        let mut body = vec![0u8; content_length];
        reader.read_exact(&mut body).unwrap();
        return body;
    }
    let mut body = Vec::new();
    loop {
        let mut header = String::new();
        reader.read_line(&mut header).unwrap();
        // A chunk size is hex, and may carry extensions after a semicolon
        // that nothing here needs.
        let size = usize::from_str_radix(
            header
                .trim_end_matches(['\r', '\n'])
                .split(';')
                .next()
                .unwrap_or("")
                .trim(),
            16,
        )
        .unwrap_or_else(|_| panic!("not a chunk size: {header:?}"));
        if size == 0 {
            break;
        }
        let mut chunk = vec![0u8; size];
        reader.read_exact(&mut chunk).unwrap();
        body.extend_from_slice(&chunk);
        // The CRLF that closes the chunk.
        let mut end = [0u8; 2];
        reader.read_exact(&mut end).unwrap();
    }
    body
}

/// One request, written by hand: a request line, whatever headers the test
/// passes, and a blank line. `Connection: close` is added on every call so
/// the response can be read to its end without trusting keep-alive.
fn call(port: u16, path: &str, headers: &[(&str, String)]) -> Answer {
    let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
    stream
        .set_read_timeout(Some(Duration::from_secs(5)))
        .unwrap();

    let mut request = format!("GET {path} HTTP/1.1\r\n");
    for (k, v) in headers {
        request.push_str(&format!("{k}: {v}\r\n"));
    }
    request.push_str("Connection: close\r\n\r\n");
    stream.write_all(request.as_bytes()).unwrap();

    let mut reader = BufReader::new(stream);
    let mut status_line = String::new();
    reader.read_line(&mut status_line).unwrap();
    let status: u16 = status_line
        .split_whitespace()
        .nth(1)
        .and_then(|s| s.parse().ok())
        .unwrap_or_else(|| panic!("not a status line: {status_line:?}"));

    let mut headers_out = Vec::new();
    let mut content_length = 0usize;
    let mut chunked = false;
    loop {
        let mut line = String::new();
        reader.read_line(&mut line).unwrap();
        let trimmed = line.trim_end_matches(['\r', '\n']);
        if trimmed.is_empty() {
            break;
        }
        let (k, v) = trimmed
            .split_once(':')
            .unwrap_or_else(|| panic!("not a header line: {trimmed:?}"));
        let (k, v) = (k.trim().to_string(), v.trim().to_string());
        if k.eq_ignore_ascii_case("content-length") {
            content_length = v.parse().unwrap_or(0);
        }
        if k.eq_ignore_ascii_case("transfer-encoding") && v.eq_ignore_ascii_case("chunked") {
            chunked = true;
        }
        headers_out.push((k, v));
    }

    let body = read_body(&mut reader, content_length, chunked);
    Answer {
        status,
        headers: headers_out,
        body: String::from_utf8_lossy(&body).into_owned(),
    }
}

/// The session token, off the `Set-Cookie` the boot key hands back.
///
/// It used to be read out of a `<meta>` in the boot page. `d190` replaced
/// that page with a redirect, so the token now arrives where a browser
/// picks it up on its own -- which was the whole point of `f189`.
fn token_from(a: &Answer) -> String {
    let raw = a.header("Set-Cookie").unwrap_or_else(|| {
        panic!(
            "no Set-Cookie on the boot answer:
{}",
            a.body
        )
    });
    let after = raw
        .split(';')
        .next()
        .and_then(|pair| pair.split_once('='))
        .unwrap_or_else(|| panic!("no name=value in {raw}"));
    assert_eq!(after.0.trim(), "vivac_session", "in {raw}");
    after.1.trim().to_string()
}

/// Every `href="..."` value in the page, in the order they appear.
fn hrefs_in(body: &str) -> Vec<String> {
    let marker = "href=\"";
    let mut out = Vec::new();
    let mut rest = body;
    while let Some(start) = rest.find(marker) {
        let after = &rest[start + marker.len()..];
        let Some(end) = after.find('"') else {
            break;
        };
        // The tab's icon rides in the head as a `data:` image, and it is
        // not a link anybody follows.
        if !after[..end].starts_with("data:") {
            out.push(after[..end].to_string());
        }
        rest = &after[end + 1..];
    }
    out
}

fn up(name: &str) -> Up {
    let sandbox = Sandbox::new_seeded(name);
    let server = Server::start(&sandbox);
    Up {
        server,
        _sandbox: sandbox,
    }
}

/// A running server over more than one sandbox, none of which it outlives.
/// Field order matters here for the same reason it does in `Up`.
struct UpMany {
    server: Server,
    _sandboxes: Vec<Sandbox>,
}

impl UpMany {
    fn port(&self) -> u16 {
        self.server.port
    }

    fn boot_path(&self) -> String {
        self.server.boot_path()
    }

    fn host(&self) -> String {
        self.server.host()
    }
}

/// Started from a directory that is not any of them, so spending the boot
/// key lands on the index rather than on one of the projects (`d809`).
fn up_many(names: &[&str]) -> UpMany {
    let sandboxes: Vec<Sandbox> = names.iter().map(|n| Sandbox::new_seeded(n)).collect();
    let roots: Vec<&std::path::Path> = sandboxes.iter().map(|s| s.0.as_path()).collect();
    let server = Server::start_serving(&std::env::temp_dir(), sandboxes[0].global_home(), &roots);
    UpMany {
        server,
        _sandboxes: sandboxes,
    }
}

#[test]
fn the_boot_key_hands_over_a_session_cookie_and_redirects() {
    let s = up("boot");
    let a = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    // `d190`: it lands you where the work is, instead of on a page whose
    // whole content was "vivac is listening". `d809`: where the work is
    // means the project the working directory sat inside when the server
    // started -- `/` itself always answers the index now, landing or not.
    assert_eq!(a.status, 302, "{}", a.body);
    let id = first_event_id(&s._sandbox.0);
    assert_eq!(
        a.header("Location"),
        Some(format!("/p/{id}/")).as_deref(),
        "{}",
        a.body
    );
    assert_eq!(token_from(&a).len(), 64, "{}", a.body);
    let jar = a.header("Set-Cookie").unwrap();
    // The flags are the defence, so they are asserted and not assumed.
    assert!(jar.contains("HttpOnly"), "{jar}");
    assert!(jar.contains("SameSite=Strict"), "{jar}");
    assert!(jar.contains("Path=/"), "{jar}");
    // A session cookie: it dies with the browser, and the server forgets
    // the token when the process does.
    assert!(!jar.contains("Max-Age"), "{jar}");
    assert!(!jar.contains("Expires"), "{jar}");
}

#[test]
fn the_same_boot_url_a_second_time_is_refused() {
    let s = up("boot-twice");
    let path = s.boot_path();
    let first = call(s.port(), &path, &[("Host", s.host())]);
    assert_eq!(first.status, 302, "{}", first.body);
    let second = call(s.port(), &path, &[("Host", s.host())]);
    assert_eq!(
        second.status, 401,
        "a spent boot key still unlocked something:\n{}",
        second.body
    );
}

/// The gate is what this proves: a good token in the header, rather than
/// the cookie a browser would carry, still reaches the router. `d809`
/// changed what the router does with `/` -- a 302 before, a 200 now -- and
/// not whether it does anything at all.
#[test]
fn a_good_token_in_the_header_serves() {
    let s = up("good-token");
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let a = call(
        s.port(),
        "/",
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);
}

/// `d809`: `/` always answers the index, even with exactly one project --
/// the index does not make anybody click through it any more either, since
/// the boot key already landed them on it (`d190`).
#[test]
fn a_single_project_index_lists_it_rather_than_redirecting() {
    let s = up("index-one");
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let a = call(
        s.port(),
        "/",
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);
    // `f721`: `new_seeded` now plants with a founding lane declared, which
    // registers the project under its real first-event id (`d201`) at
    // plant time -- not the folder's own name, which only ever stood in
    // for an id the registry had none of.
    let id = first_event_id(&s._sandbox.0);
    assert!(
        a.body.contains(&format!("/p/{id}/")),
        "the index does not link to the only project:\n{}",
        a.body
    );
}

/// `d809`, whole: the boot key still lands you on your own project, `/`
/// still lists it once you go there on purpose, and the page it landed you
/// on carries the way back -- watched as one session rather than as three
/// separate claims about it.
#[test]
fn the_index_stays_reachable_after_the_boot_lands_on_a_project() {
    let s = up("index-reachable");
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let id = first_event_id(&s._sandbox.0);
    assert_eq!(boot.status, 302, "{}", boot.body);
    assert_eq!(
        boot.header("Location"),
        Some(format!("/p/{id}/")).as_deref(),
        "{:?}",
        boot.headers
    );
    let token = token_from(&boot);

    let index = call(
        s.port(),
        "/",
        &[("Host", s.host()), ("X-Vivac-Token", token.clone())],
    );
    assert_eq!(index.status, 200, "{}", index.body);
    assert!(index.body.contains(&format!("/p/{id}/")), "{}", index.body);

    let today = call(
        s.port(),
        &format!("/p/{id}/"),
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(today.status, 200, "{}", today.body);
    assert!(
        today.body.contains("href=\"/\""),
        "no way back to the index:\n{}",
        today.body
    );
}

/// `d146`: the link shows the directory's own name and points at its
/// sanitized id. One of the two sandboxes carries a space in its name for
/// exactly that reason: a `href` can never carry one, a link's text can.
#[test]
fn two_or_more_projects_list_with_a_link_each() {
    let up = up_many(&["index-list-a", "index list b"]);
    let boot = call(up.port(), &up.boot_path(), &[("Host", up.host())]);
    let token = token_from(&boot);
    let a = call(
        up.port(),
        "/",
        &[("Host", up.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);

    let hrefs = hrefs_in(&a.body);
    assert_eq!(hrefs.len(), 2, "expected one link per project:\n{}", a.body);
    assert!(
        hrefs.iter().all(|h| !h.contains(' ')),
        "a href carried a raw space, which an id can never have: {hrefs:?}"
    );

    for sandbox in &up._sandboxes {
        let name = sandbox
            .0
            .file_name()
            .unwrap()
            .to_string_lossy()
            .into_owned();
        assert!(
            a.body.contains(&name),
            "the link text does not show the raw name {name}:\n{}",
            a.body
        );
    }
}

/// `f806`: a project row used to share the two-column layout an id like
/// `f437` is meant for, so a name such as `FluentOperations` overflowed
/// onto the focus text beside it. The new CSS targets `li.project`; this
/// proves the markup carries it. The look itself is the owner's to check --
/// there is no pixel test.
#[test]
fn a_project_row_carries_its_own_class() {
    let s = up("project-row-class");
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let a = call(
        s.port(),
        "/",
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);
    assert!(a.body.contains("class=\"project\""), "{}", a.body);
}

/// `WEB.md` §3.1 over a real socket: the page a project's `id` routes to,
/// with the focus on it.
#[test]
fn a_projects_today_page_serves_with_its_focus_on_it() {
    let s = up("today");
    s._sandbox
        .ok(&["push", "Fix the cache adapter", "--why", "the bug needs it"]);
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let id = s
        ._sandbox
        .0
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    let a = call(
        s.port(),
        &format!("/p/{id}/"),
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);
    assert_eq!(a.header("Content-Type"), Some("text/html; charset=utf-8"));
    assert!(a.body.contains("Fix the cache adapter"), "{}", a.body);
    assert!(a.body.contains("you are here"), "{}", a.body);
    assert!(a.body.contains("What moved"), "{}", a.body);
}

/// `f679`: the name `--name` fixes reached every surface on the CLI and
/// stopped there. The web took the folder's name and asked nothing else, so
/// a product checked out as `v2` was titled `v2` on its own front page while
/// `vivac brief` in that same folder called it by its name.
///
/// The folder is still the default and still what almost every project goes
/// by. What it is no longer is the only answer available.
#[test]
fn a_page_shows_the_name_the_product_was_given_over_its_folders() {
    let sandbox = Sandbox::new_empty("web-named");
    sandbox.ok(&["init", "--yes", "--name", "IQuorum"]);
    sandbox.ok(&["push", "Fix the cache adapter", "--why", "the bug needs it"]);
    let server = Server::start(&sandbox);
    let boot = call(server.port, &server.boot_path(), &[("Host", server.host())]);
    let token = token_from(&boot);

    // The readable URL is made from the same name, so this path existing at
    // all is half the answer: it is what the refusal on the CLI hands out.
    let a = call(
        server.port,
        "/p/IQuorum/",
        &[("Host", server.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);
    assert!(a.body.contains("IQuorum"), "{}", a.body);
    let folder = sandbox
        .0
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    assert!(
        !a.body.contains(&folder),
        "the folder's name reached the page beside the product's: {folder}\n{}",
        a.body
    );
}

/// The same name on the other surface that shows one, and the one a reader
/// meets first: `d199` says `vivac web` opens from anywhere and lists every
/// project on the machine. A list that named this one by a version folder
/// would be a list nobody could find their product in.
#[test]
fn the_index_lists_a_project_under_the_name_it_was_given() {
    let sandbox = Sandbox::new_empty("web-named-index");
    sandbox.ok(&["init", "--yes", "--name", "IQuorum"]);
    // Started outside it, since from inside a project `/` lands on that
    // project instead of listing -- the same reason `up_many` does this.
    let server = Server::start_serving(
        &std::env::temp_dir(),
        sandbox.global_home(),
        &[sandbox.0.as_path()],
    );
    let boot = call(server.port, &server.boot_path(), &[("Host", server.host())]);
    let token = token_from(&boot);
    let a = call(
        server.port,
        "/",
        &[("Host", server.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);
    assert!(a.body.contains("IQuorum"), "{}", a.body);
    let folder = sandbox
        .0
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    assert!(
        !a.body.contains(&folder),
        "the index named it by its folder: {folder}\n{}",
        a.body
    );
}

/// `WEB.md` §7.4: the page loads with no internet. Proved on the bytes that
/// actually left the socket, not on the template they were built from.
#[test]
fn the_served_page_reaches_for_nothing_off_this_machine() {
    let s = up("today-offline");
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let id = s
        ._sandbox
        .0
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    let a = call(
        s.port(),
        &format!("/p/{id}/"),
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);
    assert!(!a.body.contains("http://"), "{}", a.body);
    assert!(!a.body.contains("https://"), "{}", a.body);
}

/// An `id` the registry does not hold is a 404, and the id it did not
/// recognise never comes back in the answer.
#[test]
fn a_project_id_the_registry_does_not_hold_is_not_found() {
    let s = up("today-unknown");
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let a = call(
        s.port(),
        "/p/not-a-project/",
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 404, "{}", a.body);
    assert_eq!(a.body, "not found\n");
}

/// An admitted request for a path `route` does not know is `NotFound`, and
/// that has to come back as its own 404 rather than as the index page --
/// the one thing a security-relevant router must never do is fall open.
#[test]
fn an_unknown_route_is_not_found_and_not_the_index() {
    let s = up("unknown-route");
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let a = call(
        s.port(),
        "/does-not-exist",
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 404, "{}", a.body);
    assert_eq!(
        a.body, "not found\n",
        "a 404 leaked something else:\n{}",
        a.body
    );
}

#[test]
fn no_token_at_all_is_refused() {
    let s = up("no-token");
    let a = call(s.port(), "/", &[("Host", s.host())]);
    assert_eq!(a.status, 401, "{}", a.body);
}

#[test]
fn a_foreign_host_is_refused_even_with_the_right_token() {
    let s = up("foreign-host");
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let a = call(
        s.port(),
        "/",
        &[("Host", "malo.com".to_string()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 403, "{}", a.body);
}

#[test]
fn a_foreign_origin_is_refused() {
    let s = up("foreign-origin");
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let a = call(
        s.port(),
        "/",
        &[
            ("Host", s.host()),
            ("Origin", "http://malo.com".to_string()),
            ("X-Vivac-Token", token),
        ],
    );
    assert_eq!(a.status, 403, "{}", a.body);
}

/// Nothing here is CORS-visible from another origin: the missing
/// `Access-Control-Allow-Origin` is exactly what leaves a page with a stolen
/// token unable to read the answer.
#[test]
fn no_response_ever_carries_a_cors_header() {
    let s = up("no-cors");
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let served = call(
        s.port(),
        "/",
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    let refused = call(s.port(), "/", &[("Host", s.host())]);
    let foreign = call(s.port(), "/", &[("Host", "malo.com".to_string())]);
    for a in [&boot, &served, &refused, &foreign] {
        assert!(
            a.header("Access-Control-Allow-Origin").is_none(),
            "a response carried a CORS header:\n{:?}",
            a.headers
        );
    }
}

#[test]
fn every_response_carries_the_security_headers() {
    let s = up("security-headers");
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let served = call(
        s.port(),
        "/",
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    let refused = call(s.port(), "/", &[("Host", s.host())]);
    let foreign = call(s.port(), "/", &[("Host", "malo.com".to_string())]);
    for a in [&boot, &served, &refused, &foreign] {
        assert!(
            a.header("Content-Security-Policy").is_some(),
            "no CSP on a {} response",
            a.status
        );
        assert_eq!(
            a.header("Referrer-Policy"),
            Some("no-referrer"),
            "the boot url carries the key in its query string, and this header \
             is what keeps it out of a `Referer`: {:?}",
            a.headers
        );
    }
}
/// `WEB.md` §3.2 over a real socket: the lineage of a node, drawn.
///
/// The unit tests build the page from a folded tree; this one proves the
/// route reaches it and that the bytes leaving the socket carry the shape.
#[test]
fn the_lineage_of_a_node_is_served_with_a_step_per_ancestor() {
    let s = up("why-page");
    s._sandbox
        .ok(&["push", "Ship the thing", "--why", "it is the goal"]);
    s._sandbox
        .ok(&["push", "The face is web", "--why", "the owner asked"]);
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let id = s
        ._sandbox
        .0
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    let a = call(
        s.port(),
        &format!("/p/{id}/why/2"),
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);
    assert_eq!(a.header("Content-Type"), Some("text/html; charset=utf-8"));
    // Both steps of the path, and the mark on the one that was asked for.
    assert!(a.body.contains("Ship the thing"), "{}", a.body);
    assert!(a.body.contains("The face is web"), "{}", a.body);
    assert!(a.body.contains("you are here"), "{}", a.body);
    // The drawing is also the way you walk the tree.
    assert!(
        hrefs_in(&a.body).iter().any(|h| h.contains("/why/")),
        "{}",
        a.body
    );
    // §7.4, proved on the bytes that actually left the socket.
    assert!(!a.body.contains("http://"), "{}", a.body);
    assert!(!a.body.contains("https://"), "{}", a.body);
}

/// A node the tree does not hold is a 404, the same as a project it does
/// not hold: a page that draws an empty spine for a typo teaches that the
/// node exists.
#[test]
fn a_lineage_for_a_node_that_is_not_there_is_not_found() {
    let s = up("why-unknown");
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let id = s
        ._sandbox
        .0
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    let a = call(
        s.port(),
        &format!("/p/{id}/why/f999"),
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 404, "{}", a.body);
    assert_eq!(a.body, "not found\n");
}

/// `f189`: the test that was missing, and whose absence let the main
/// surface sit broken for a day with fifteen green ones around it. No
/// `X-Vivac-Token` anywhere -- just the cookie, which is all a browser
/// sends back when it follows a link.
#[test]
fn a_browser_that_only_carries_the_cookie_can_walk_from_today_to_a_lineage() {
    let s = up("browsing");
    s._sandbox
        .ok(&["push", "Ship the thing", "--why", "it is the goal"]);
    s._sandbox
        .ok(&["push", "The face is web", "--why", "the owner asked"]);
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let jar = format!("vivac_session={}", token_from(&boot));
    let id = s
        ._sandbox
        .0
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();

    let today = call(
        s.port(),
        &format!("/p/{id}/"),
        &[("Host", s.host()), ("Cookie", jar.clone())],
    );
    assert_eq!(today.status, 200, "{}", today.body);

    // Follow a link off the page rather than a path written here: a link
    // that goes nowhere is exactly the failure this test exists for.
    let lineage = hrefs_in(&today.body)
        .into_iter()
        .find(|h| h.contains("/why/"))
        .unwrap_or_else(|| {
            panic!(
                "no lineage link on the Today page:
{}",
                today.body
            )
        });
    let a = call(s.port(), &lineage, &[("Host", s.host()), ("Cookie", jar)]);
    assert_eq!(a.status, 200, "{} -> {}", lineage, a.body);
    assert!(a.body.contains("you are here"), "{}", a.body);
}

/// `WEB.md` §3.6 over a real socket: the global graph, at the route `d194`
/// gave it. Both spellings serve it, and a project the registry does not
/// hold is still a 404 there too, not the page for someone else's tree.
#[test]
fn the_tree_page_routes_with_or_without_a_slash_and_a_bogus_project_is_still_not_found() {
    let s = up("tree-route");
    s._sandbox
        .ok(&["push", "Ship the thing", "--why", "it is the goal"]);
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let id = s
        ._sandbox
        .0
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();

    for path in [format!("/p/{id}/tree"), format!("/p/{id}/tree/")] {
        let a = call(
            s.port(),
            &path,
            &[("Host", s.host()), ("X-Vivac-Token", token.clone())],
        );
        assert_eq!(a.status, 200, "{path}: {}", a.body);
    }

    let bogus = call(
        s.port(),
        "/p/not-a-project/tree",
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(bogus.status, 404, "{}", bogus.body);
}

/// `d391`: the map draws every node once, leaves included. There are no
/// tiles any more -- a leaf used to exist only inside its parent's comb --
/// and every alias still reaches its own lineage, which is exactly what a
/// click costs a reader whose browser runs no script.
#[test]
fn every_node_is_one_row_that_still_reaches_its_own_lineage() {
    let s = up("map-rows");
    s._sandbox
        .ok(&["push", "Root goal", "--why", "it is the goal"]);
    s._sandbox.ok(&[
        "add",
        "A branch",
        "--why",
        "it needs its own children",
        "--parent",
        "1",
    ]);
    s._sandbox.ok(&[
        "add",
        "A leaf beside it",
        "--why",
        "it stands alone",
        "--parent",
        "1",
    ]);
    s._sandbox.ok(&[
        "add",
        "A leaf below the branch",
        "--why",
        "it hangs off the branch",
        "--parent",
        "2",
    ]);

    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let id = s
        ._sandbox
        .0
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    let a = call(
        s.port(),
        &format!("/p/{id}/tree"),
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);

    for alias in ["g1", "t2", "t3", "t4"] {
        let needle = format!("href=\"/p/{id}/why/{alias}\"");
        assert_eq!(
            a.body.matches(&needle).count(),
            1,
            "{alias} should reach its own lineage exactly once:\n{}",
            a.body
        );
        assert_eq!(
            a.body.matches(&format!("id=\"{alias}\"")).count(),
            1,
            "{alias} should be one row and no more:\n{}",
            a.body
        );
    }
}

/// `d391`, and `d387` before it: one flat list, one row per node, every row
/// at the same offset. A row's index in that list *is* the row its station
/// is drawn on, so a nest here would put the drawing and the list on
/// different lines.
///
/// The old page gave a row only to a node with children and drew a leaf as
/// a tile in its parent's comb. The map gives every node a row, which is
/// what lets a leaf carry a station of its own.
#[test]
fn the_map_is_one_flat_list_with_a_row_for_every_node() {
    let s = up("map-flat");
    s._sandbox
        .ok(&["push", "Root goal", "--why", "it is the goal"]);
    s._sandbox.ok(&[
        "add",
        "A branch",
        "--why",
        "it needs its own children",
        "--parent",
        "1",
    ]);
    s._sandbox.ok(&[
        "add",
        "A leaf beside it",
        "--why",
        "it stands alone",
        "--parent",
        "1",
    ]);
    s._sandbox.ok(&[
        "add",
        "A leaf below the branch",
        "--why",
        "it hangs off the branch",
        "--parent",
        "2",
    ]);

    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let id = s
        ._sandbox
        .0
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    let a = call(
        s.port(),
        &format!("/p/{id}/tree"),
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);

    assert_eq!(
        a.body.matches("<ol class=\"stops\">").count(),
        1,
        "a second list is a nest, and a nest moves a row off its station:\n{}",
        a.body
    );
    assert_eq!(a.body.matches("<li class=\"stop").count(), 4, "{}", a.body);

    // Tree order, and the two gutters drawing the same four stations on the
    // same four rows.
    for (row, alias) in ["g1", "t2", "t4", "t3"].iter().enumerate() {
        assert!(
            a.body
                .contains(&format!("id=\"{alias}\" data-stop=\"{row}\"")),
            "{alias} should be row {row}:\n{}",
            a.body
        );
        assert_eq!(
            a.body.matches(&format!("data-stop=\"{row}\" cx=")).count(),
            2,
            "one station in each of the two gutters:\n{}",
            a.body
        );
    }
}

/// The drawing carries the fan-out in the radius of a station, and a radius
/// saturates: past thirty children they all look alike. The number on the
/// row is what tells those apart, which is why `d194`'s ban on counting it
/// does not carry over -- that ban existed because a comb's *width* said it
/// exactly, and there is no comb any more.
#[test]
fn the_row_counts_the_fan_out_the_radius_can_no_longer_tell_apart() {
    let s = up("map-fan");
    s._sandbox
        .ok(&["push", "Root goal", "--why", "it is the goal"]);
    s._sandbox.ok(&[
        "add",
        "A branch",
        "--why",
        "it needs its own children",
        "--parent",
        "1",
    ]);
    s._sandbox.ok(&[
        "add",
        "A leaf beside it",
        "--why",
        "it stands alone",
        "--parent",
        "1",
    ]);
    s._sandbox.ok(&[
        "add",
        "A leaf below the branch",
        "--why",
        "it hangs off the branch",
        "--parent",
        "2",
    ]);

    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let id = s
        ._sandbox
        .0
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    let a = call(
        s.port(),
        &format!("/p/{id}/tree"),
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);

    // g1 has two children, t2 has one, and the two leaves have none and
    // therefore no number at all.
    assert!(
        a.body.contains("<span class=\"fan\">2</span>"),
        "{}",
        a.body
    );
    assert_eq!(
        a.body.matches("<span class=\"fan\">1</span>").count(),
        1,
        "{}",
        a.body
    );
    assert_eq!(a.body.matches("class=\"fan\"").count(), 2, "{}", a.body);
}

/// DX pillar: state never rides on a colour alone. Each row spells its
/// state as a word in `title`, not only through its class and the fill of
/// its station.
#[test]
fn state_reaches_the_row_as_a_word_in_its_title_attribute_not_only_as_a_class() {
    let s = up("map-state-words");
    s._sandbox
        .ok(&["push", "Root goal", "--why", "it is the goal"]);
    s._sandbox.ok(&[
        "add",
        "Still open",
        "--why",
        "nothing settled it yet",
        "--parent",
        "1",
    ]);
    s._sandbox.ok(&[
        "add",
        "Already closed",
        "--why",
        "it shipped",
        "--parent",
        "1",
    ]);
    s._sandbox.ok(&["done", "3", "shipped it"]);
    s._sandbox.ok(&[
        "add",
        "Parked for later",
        "--why",
        "it is not due yet",
        "--parent",
        "1",
    ]);
    s._sandbox.ok(&["park", "4", "waiting on the release"]);

    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let id = s
        ._sandbox
        .0
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    let a = call(
        s.port(),
        &format!("/p/{id}/tree"),
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);
    assert!(
        a.body.contains("title=\"t2 · open · Still open\""),
        "{}",
        a.body
    );
    assert!(
        a.body.contains("title=\"t3 · closed · Already closed\""),
        "{}",
        a.body
    );
    assert!(
        a.body.contains("title=\"t4 · parked · Parked for later\""),
        "{}",
        a.body
    );
    // And the word is not the only cue either: the closed one is struck
    // through and its station is hollow.
    assert!(a.body.contains("<li class=\"stop shut\""), "{}", a.body);
}

/// The promise `d391` signs, over HTTP rather than through a unit test: the
/// detail of every node is already on the page when it arrives, so reading
/// one costs no second request. That is what "without letting go" means in
/// a browser -- and it is also why the CSP can keep saying `default-src
/// 'none'`, with no way for the page to talk to anything at all.
#[test]
fn the_detail_of_every_node_arrives_with_the_page() {
    let s = up("map-detail");
    s._sandbox
        .ok(&["push", "Root goal", "--why", "it is the goal"]);
    s._sandbox.ok(&[
        "add",
        "A branch",
        "--why",
        "it needs its own children",
        "--parent",
        "1",
    ]);
    s._sandbox.ok(&["note", "2", "the first note"]);
    s._sandbox
        .ok(&["note", "2", "and the one that corrects it"]);

    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let id = s
        ._sandbox
        .0
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    let a = call(
        s.port(),
        &format!("/p/{id}/tree"),
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);

    assert!(
        a.body
            .contains("<script type=\"application/json\" id=\"map-data\">"),
        "{}",
        a.body
    );
    for why in ["it is the goal", "it needs its own children"] {
        assert!(
            a.body.contains(why),
            "{why} is not on the page:\n{}",
            a.body
        );
    }
    // `f389`: both notes travel, not only the last one written.
    assert!(a.body.contains("the first note"), "{}", a.body);
    assert!(
        a.body.contains("and the one that corrects it"),
        "{}",
        a.body
    );
    assert!(a.body.contains("2 notes"), "{}", a.body);
}

/// Folding is a link, so it has to survive the gate as well as the router:
/// the query is the one part of a URL the gate reads for itself, looking for
/// a boot key, and a fold arriving there must be served rather than treated
/// as a key that is missing.
#[test]
fn a_fold_travels_in_the_url_and_is_served_like_any_other_page() {
    let s = up("map-fold");
    s._sandbox
        .ok(&["push", "Root goal", "--why", "it is the goal"]);
    s._sandbox.ok(&[
        "add",
        "A branch",
        "--why",
        "it needs its own children",
        "--parent",
        "1",
    ]);
    s._sandbox.ok(&[
        "add",
        "A leaf below the branch",
        "--why",
        "it hangs off the branch",
        "--parent",
        "2",
    ]);

    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let id = s
        ._sandbox
        .0
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    let headers = [("Host", s.host()), ("X-Vivac-Token", token)];

    let whole = call(s.port(), &format!("/p/{id}/tree"), &headers);
    assert_eq!(whole.status, 200, "{}", whole.body);
    assert_eq!(whole.body.matches("<li class=\"stop").count(), 3);

    let folded = call(s.port(), &format!("/p/{id}/tree?fold=t2"), &headers);
    assert_eq!(folded.status, 200, "{}", folded.body);
    assert_eq!(
        folded.body.matches("<li class=\"stop").count(),
        2,
        "t2's own child should be off the page:\n{}",
        folded.body
    );
    assert!(
        folded.body.contains("<span class=\"held\">+1</span>"),
        "{}",
        folded.body
    );
    // And the control that undoes it is a link in the gutter, one per lane
    // width, so it works with no script at all.
    assert_eq!(folded.body.matches("class=\"fold on\"").count(), 2);
}

/// `WEB.md` §7.4: the whole map loads with no internet, the same as every
/// other page.
///
/// It is the first page with a drawing and a script in it, so this is also
/// the first time the promise means more than "no `<img>`". The assertion
/// used to be that the page carried no `<svg>` and no `<script>` at all,
/// which stopped saying anything the day it carried both. What it has to
/// say instead is that neither of them *reaches*: no `src`, no `@import`,
/// no `<use>`, and no absolute URL anywhere on the page.
#[test]
fn the_map_reaches_for_nothing_off_this_machine() {
    let s = up("tree-offline");
    s._sandbox
        .ok(&["push", "Ship the thing", "--why", "it is the goal"]);
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let id = s
        ._sandbox
        .0
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    let a = call(
        s.port(),
        &format!("/p/{id}/tree"),
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);
    assert!(!a.body.contains("http://"), "{}", a.body);
    assert!(!a.body.contains("https://"), "{}", a.body);
    for reaching in ["src=", "@import", "<use", "<image", "url("] {
        assert!(
            !a.body.contains(reaching),
            "{reaching} would fetch something:\n{}",
            a.body
        );
    }
}

/// `f189`'s test, extended: the tree the front page links to has to be
/// reachable with nothing but the cookie a browser keeps on its own.
#[test]
fn a_browser_that_only_carries_the_cookie_can_walk_from_today_to_the_tree() {
    let s = up("tree-browsing");
    s._sandbox
        .ok(&["push", "Ship the thing", "--why", "it is the goal"]);
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let jar = format!("vivac_session={}", token_from(&boot));
    let id = s
        ._sandbox
        .0
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();

    let today = call(
        s.port(),
        &format!("/p/{id}/"),
        &[("Host", s.host()), ("Cookie", jar.clone())],
    );
    assert_eq!(today.status, 200, "{}", today.body);

    let tree_link = hrefs_in(&today.body)
        .into_iter()
        .find(|h| h.contains("/tree"))
        .unwrap_or_else(|| {
            panic!(
                "no link to the tree on the Today page:
{}",
                today.body
            )
        });
    let a = call(s.port(), &tree_link, &[("Host", s.host()), ("Cookie", jar)]);
    assert_eq!(a.status, 200, "{} -> {}", tree_link, a.body);
}

// ---------------------------------------------------------------------------
// `d199`, `d200` and `d374`: the index of projects, and what a URL's `<id>`
// names. Everything below is about the two ways in and the answer to an
// ambiguous one.
// ---------------------------------------------------------------------------

/// The id the registry keys a project by, read the way the registry reads it:
/// the id of its first event. Not `config.project_id`, which `f266`
/// disqualified because a missing `config` is silently regenerated.
fn first_event_id(root: &std::path::Path) -> String {
    let log = std::fs::read_to_string(root.join(".vivac").join("events")).unwrap();
    let line = log.lines().next().expect("a tree with no events has no id");
    let at = line.find("\"id\":\"").expect("no id on the first event") + 6;
    let rest = &line[at..];
    rest[..rest.find('"').unwrap()].to_string()
}

/// Two projects whose directories carry the *same* name, which `Sandbox` will
/// not produce on its own because it keeps every name unique. They share one
/// `VIVAC_HOME`, so one registry holds both.
fn twins(name: &str) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
    let home = std::env::temp_dir().join(format!("t-home-twins-{name}"));
    std::fs::create_dir_all(&home).unwrap();
    let mut roots = Vec::new();
    for side in ["a", "b"] {
        let d = std::env::temp_dir()
            .join(format!("t-twins-{name}-{side}"))
            .join("same-name");
        std::fs::create_dir_all(&d).unwrap();
        let ok = Command::new(BIN)
            .current_dir(&d)
            .env("VIVAC_HOME", &home)
            .env("TZ", "UTC")
            .args(["init", "--yes"])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .unwrap()
            .success();
        assert!(ok, "init failed in a twin");
        roots.push(d);
    }
    (home, roots[0].clone(), roots[1].clone())
}

/// `f804`/`d810`: a project the machine's registry still names after its
/// folder is gone must not stop every other project from being served.
/// Before this decision, `Registry::open` tried that root the same as any
/// other, and the whole server refused to start: `Input/output error ...
/// os error 3`, exit 5.
#[test]
fn a_dead_registry_entry_does_not_stop_the_server() {
    let live = Sandbox::new_seeded("dead-reg-live");
    let dead = Sandbox::new_seeded_in("dead-reg-dead", live.global_home());
    let dead_name = dead.0.file_name().unwrap().to_string_lossy().into_owned();
    std::fs::remove_dir_all(&dead.0).unwrap();

    // No `--project` and no tree above `temp_dir()`: every root here comes
    // from the registry alone, which is what makes the dead one optional.
    let mut server = Server::start_serving(&std::env::temp_dir(), live.global_home(), &[]);
    assert_eq!(
        server.next_startup_line(),
        format!("1 project unreachable: {dead_name}")
    );

    let boot = call(server.port, &server.boot_path(), &[("Host", server.host())]);
    let token = token_from(&boot);
    let a = call(
        server.port,
        "/",
        &[("Host", server.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);
    assert!(
        a.body
            .contains(&format!("1 project unreachable: {dead_name}")),
        "{}",
        a.body
    );
}

/// `d810`: a root named with `--project` is required, so a failure to open
/// it stays the error it always was -- only a root the registry alone
/// named may be skipped.
#[test]
fn a_project_flag_naming_nothing_on_disk_still_fails() {
    let sandbox = Sandbox::new_empty("bad-explicit-project");
    let missing = sandbox.0.join("nowhere");
    let output = Command::new(BIN)
        .current_dir(std::env::temp_dir())
        .env("VIVAC_HOME", sandbox.global_home())
        .env("TZ", "UTC")
        .args([
            "web",
            "--port",
            "0",
            "--no-open",
            "--project",
            missing.to_str().unwrap(),
        ])
        .output()
        .unwrap();
    assert_ne!(
        output.status.code(),
        Some(0),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(
        !String::from_utf8_lossy(&output.stdout).contains("http://"),
        "printed a boot url despite a bad --project:\n{}",
        String::from_utf8_lossy(&output.stdout)
    );
}

/// `d199`: the server opens from a directory that is not a project at all.
///
/// This used to be impossible for a reason no error explained: `main` looked
/// for a tree at or above the cwd and returned `NoStore` before the `web`
/// branch was ever reached, so the command died in a directory it had no
/// business needing a tree in. That the server answers here at all is half of
/// what this asserts; the other half is that `/` is then the index, because
/// there is no "the project" to land on.
#[test]
fn started_outside_a_project_the_index_is_what_answers() {
    let one = Sandbox::new_seeded("outside-one");
    let two = Sandbox::new_seeded_in("outside-two", one.global_home());
    let server = Server::start_serving(
        &std::env::temp_dir(),
        one.global_home(),
        &[one.0.as_path(), two.0.as_path()],
    );
    let boot = call(server.port, &server.boot_path(), &[("Host", server.host())]);
    let token = token_from(&boot);
    let a = call(
        server.port,
        "/",
        &[("Host", server.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);
    let one_name = one.0.file_name().unwrap().to_string_lossy().into_owned();
    let two_name = two.0.file_name().unwrap().to_string_lossy().into_owned();
    assert!(a.body.contains(&one_name), "{}", a.body);
    assert!(a.body.contains(&two_name), "{}", a.body);
}

/// `d200`: the index is a page, not the bare `<ul>` it used to be.
///
/// The list of links had no stylesheet, no `<title>` and no viewport, which
/// made it the only surface here that was not one. It also said nothing a
/// `cd` did not already say, and the promise it now has to keep is that you
/// can see which project moved and which has been sitting still.
#[test]
fn the_index_is_a_page_and_carries_what_d200_admitted() {
    let one = Sandbox::new_seeded("index-fields-one");
    let two = Sandbox::new_seeded_in("index-fields-two", one.global_home());
    two.ok(&["push", "Ship the thing", "--why", "it is the goal"]);
    let server = Server::start_serving(
        &std::env::temp_dir(),
        one.global_home(),
        &[one.0.as_path(), two.0.as_path()],
    );
    let boot = call(server.port, &server.boot_path(), &[("Host", server.host())]);
    let token = token_from(&boot);
    let a = call(
        server.port,
        "/",
        &[("Host", server.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);
    assert!(a.body.contains("<title>"), "no title: {}", a.body);
    assert!(a.body.contains("<style>"), "no stylesheet: {}", a.body);
    assert!(
        a.body.contains("width=device-width"),
        "no viewport: {}",
        a.body
    );
    // The focus: one of `d200`'s four, and the one that says what a project
    // was doing when it stopped.
    assert!(a.body.contains("Ship the thing"), "no focus: {}", a.body);
    // The silence, which is the field the promise is actually about.
    assert!(a.body.contains("moved today"), "no silence: {}", a.body);
    // And the project with nothing in it says so rather than being blank.
    assert!(a.body.contains("no focus"), "{}", a.body);
}

/// `d817`: the card's last-stop line reads the same tree `changes --since
/// manual` does, and moves with it -- a stop made by hand with nothing
/// after it, then a node born after that stop.
#[test]
fn the_index_card_says_whether_work_followed_the_stop_you_made() {
    let s = up("index-card-stop-since");
    s._sandbox.ok(&[
        "add",
        "Something",
        "--why",
        "so the stop has work behind it",
    ]);
    s._sandbox.ok(&["save", "checkpoint"]);
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let a = call(
        s.port(),
        "/",
        &[("Host", s.host()), ("X-Vivac-Token", token.clone())],
    );
    assert_eq!(a.status, 200, "{}", a.body);
    assert!(a.body.contains("nothing since"), "{}", a.body);

    s._sandbox.ok(&[
        "add",
        "After the stop",
        "--why",
        "so the hook has something to see",
    ]);
    let b = call(
        s.port(),
        "/",
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(b.status, 200, "{}", b.body);
    assert!(b.body.contains("work since"), "{}", b.body);
}

/// `d374`: the permanent form of the URL opens the project.
#[test]
fn a_project_opens_by_its_permanent_id() {
    let s = up("permanent-id");
    s._sandbox
        .ok(&["push", "Root goal", "--why", "it is the goal"]);
    let ulid = first_event_id(&s._sandbox.0);
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let a = call(
        s.port(),
        &format!("/p/{ulid}/"),
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 200, "{}", a.body);
    assert!(a.body.contains("Root goal"), "{}", a.body);
}

/// `d374`: a name more than one project carries is answered with the choice,
/// never with a guess.
///
/// The `-2` this replaces made the second twin reachable at `same-name-2`,
/// and `f373` showed what that cost: the suffix was positional, so the first
/// twin leaving the registry handed its URL to the second and a saved link
/// opened the wrong tree without an error.
#[test]
fn a_name_two_projects_share_is_a_choice_and_not_a_guess() {
    let (home, a_root, b_root) = twins("choice");
    let server = Server::start_serving(
        &std::env::temp_dir(),
        &home,
        &[a_root.as_path(), b_root.as_path()],
    );
    let boot = call(server.port, &server.boot_path(), &[("Host", server.host())]);
    let token = token_from(&boot);
    let a = call(
        server.port,
        "/p/same-name/",
        &[("Host", server.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(a.status, 300, "{}", a.body);
    // The `-2` is gone: nothing here invents a second spelling.
    assert!(!a.body.contains("same-name-2"), "{}", a.body);
}

/// The security pillar allows a project's *name* across this boundary and
/// nothing else. A real path carries the name of whoever owns the machine,
/// so the page that has to tell two identically named projects apart is
/// exactly the one where a path would be easiest to reach for.
#[test]
fn the_choice_tells_them_apart_without_naming_a_path() {
    let (home, a_root, b_root) = twins("no-paths");
    let server = Server::start_serving(
        &std::env::temp_dir(),
        &home,
        &[a_root.as_path(), b_root.as_path()],
    );
    let boot = call(server.port, &server.boot_path(), &[("Host", server.host())]);
    let token = token_from(&boot);
    let a = call(
        server.port,
        "/p/same-name/",
        &[("Host", server.host()), ("X-Vivac-Token", token)],
    );
    for root in [&a_root, &b_root] {
        let parent = root.parent().unwrap().to_string_lossy().into_owned();
        assert!(
            !a.body.contains(&parent),
            "a path reached the page: {}",
            a.body
        );
        // The other spelling of the separator too: a fragment is a leak.
        assert!(
            !a.body.contains(&parent.replace('\\', "/")),
            "a path reached the page: {}",
            a.body
        );
    }
}

// ---------------------------------------------------------------------------
// `t594` §5.6: three surfaces used to read `tree.lane()` -- one lane out of
// however many the tree holds -- and show it as if it were the whole
// product's own focus: the Today page's own stack, the project index's, and
// the map's "where am I" control. A tree with one lane must not notice any
// of this; with several, the one that wrote most recently is what they show,
// named.
// ---------------------------------------------------------------------------

/// A second folder, joined to `on`'s own tree as a lane named `name`, with
/// nothing pushed yet -- the same shape `stack --lanes`'s own tests already
/// build one with.
fn join_lane(on: &Sandbox, folder: &str, name: &str) -> Sandbox {
    let joined = Sandbox::new_empty_in(folder, on.global_home());
    joined.ok(&[
        "init",
        "--yes",
        "--join",
        on.0.to_str().unwrap(),
        "--lane-name",
        name,
    ]);
    joined
}

/// The `data-stop` on the row whose visible title is `title`, read by
/// walking back from the text to the attribute the same `<li>` carries --
/// `the_map_is_one_flat_list_with_a_row_for_every_node` already reads a row
/// this way, just forward from the alias rather than back from the title.
fn stop_of_title(body: &str, title: &str) -> String {
    let marker = format!("<span class=\"title\">{title}</span>");
    let at = body
        .find(&marker)
        .unwrap_or_else(|| panic!("no row titled {title}:\n{body}"));
    let before = &body[..at];
    let data_stop = "data-stop=\"";
    let start = before
        .rfind(data_stop)
        .unwrap_or_else(|| panic!("no data-stop before {title}:\n{body}"))
        + data_stop.len();
    let rest = &before[start..];
    rest[..rest.find('"').unwrap()].to_string()
}

/// The `data-stop` the "where am I" control points at, or `None` when the
/// map drew no such control at all.
fn here_stop(body: &str) -> Option<String> {
    let marker = "id=\"here\" type=\"button\" data-stop=\"";
    let start = body.find(marker)? + marker.len();
    let rest = &body[start..];
    Some(rest[..rest.find('"')?].to_string())
}

/// Golden: a tree with one lane must not notice this task happened, on the
/// Today page or on the map.
#[test]
fn with_one_lane_the_web_says_exactly_what_it_did() {
    let s = up("web-lanes-one");
    s._sandbox
        .ok(&["push", "Fix the cache adapter", "--why", "the bug needs it"]);
    let boot = call(s.port(), &s.boot_path(), &[("Host", s.host())]);
    let token = token_from(&boot);
    let id = s
        ._sandbox
        .0
        .file_name()
        .unwrap()
        .to_string_lossy()
        .into_owned();
    let today = call(
        s.port(),
        &format!("/p/{id}/"),
        &[("Host", s.host()), ("X-Vivac-Token", token.clone())],
    );
    assert_eq!(today.status, 200, "{}", today.body);
    assert!(today.body.contains("you are here"), "{}", today.body);
    assert!(!today.body.contains("in lane"), "{}", today.body);

    let map = call(
        s.port(),
        &format!("/p/{id}/tree"),
        &[("Host", s.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(map.status, 200, "{}", map.body);
    assert!(map.body.contains("Where am I?"), "{}", map.body);
}

/// With several lanes, the Today page's own stack shows the one that wrote
/// most recently -- not whichever lane this project happened to resolve to
/// -- and names whose it is.
#[test]
fn with_several_lanes_the_front_page_names_whose_focus_it_is() {
    let a = Sandbox::new_seeded("web-lanes-front-a");
    a.ok(&["push", "Main line work", "--why", "seed"]);
    let b = join_lane(&a, "web-lanes-front-b", "hotfix");
    b.ok(&["push", "Hotfix triage", "--why", "seed"]);
    let c = join_lane(&a, "web-lanes-front-c", "sonar");
    c.ok(&["push", "Backend webapi cleanup", "--why", "seed"]);

    let server = Server::start(&a);
    let boot = call(server.port, &server.boot_path(), &[("Host", server.host())]);
    let token = token_from(&boot);
    let id = a.0.file_name().unwrap().to_string_lossy().into_owned();
    let today = call(
        server.port,
        &format!("/p/{id}/"),
        &[("Host", server.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(today.status, 200, "{}", today.body);
    assert!(
        today.body.contains("Backend webapi cleanup"),
        "{}",
        today.body
    );
    assert!(
        today.body.contains("in lane sonar, 1 of 3 lanes"),
        "{}",
        today.body
    );
    assert!(!today.body.contains("you are here"), "{}", today.body);
}

/// The map's "where am I" control points at the lane of the folder the web
/// was opened from, not at whichever lane wrote most recently -- that is
/// only what it falls back to once the opening folder has nothing of its
/// own to point at.
#[test]
fn the_map_points_at_the_lane_of_the_folder_the_web_was_opened_from() {
    let a = Sandbox::new_seeded("web-lanes-here-a");
    a.ok(&["push", "Main line work", "--why", "seed"]);
    let b = join_lane(&a, "web-lanes-here-b", "sonar");
    b.ok(&["push", "Backend webapi cleanup", "--why", "seed"]);
    let c = join_lane(&a, "web-lanes-here-c", "hotfix");
    // Written after `b`'s, so `hotfix` -- not `sonar` -- is the lane that
    // wrote most recently; the control still has to point at `sonar`,
    // because that is the folder the server was started in.
    c.ok(&["push", "Hotfix triage", "--why", "seed"]);

    let server = Server::start_serving(&b.0, a.global_home(), &[]);
    let boot = call(server.port, &server.boot_path(), &[("Host", server.host())]);
    let token = token_from(&boot);
    let id = a.0.file_name().unwrap().to_string_lossy().into_owned();
    let map = call(
        server.port,
        &format!("/p/{id}/tree"),
        &[("Host", server.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(map.status, 200, "{}", map.body);
    let here = here_stop(&map.body).unwrap_or_else(|| panic!("no here control:\n{}", map.body));
    let b_stop = stop_of_title(&map.body, "Backend webapi cleanup");
    assert_eq!(here, b_stop, "{}", map.body);
}

/// When the folder the web was opened from does not belong to this tree at
/// all, the control has no position of its own to answer for and stops
/// asking: it points at the lane that wrote most recently and says that is
/// not where you are.
#[test]
fn the_map_falls_back_to_the_last_writer_and_says_so() {
    // `main`'s own stack has to stay empty, or `Whose::Founding` -- what
    // every project the server was not started in resolves to -- would land
    // on a real stack of its own and never reach the fallback this test is
    // about. `--join` needs the tree to already have an identity, so this
    // gives it one and immediately closes it back off the stack.
    let a = Sandbox::new_seeded("web-lanes-fallback-a");
    a.ok(&["push", "Seed the tree's own identity", "--why", "seed"]);
    a.ok(&["done", "g1", "not main's own thread"]);
    let b = join_lane(&a, "web-lanes-fallback-b", "sonar");
    b.ok(&["push", "Backend webapi cleanup", "--why", "seed"]);
    let c = join_lane(&a, "web-lanes-fallback-c", "hotfix");
    // Written after `b`'s, so `hotfix` is the lane that wrote most
    // recently, and the one the fallback has to point at.
    c.ok(&["push", "Hotfix triage", "--why", "seed"]);

    let server = Server::start_serving(&std::env::temp_dir(), a.global_home(), &[a.0.as_path()]);
    let boot = call(server.port, &server.boot_path(), &[("Host", server.host())]);
    let token = token_from(&boot);
    let id = a.0.file_name().unwrap().to_string_lossy().into_owned();
    let map = call(
        server.port,
        &format!("/p/{id}/tree"),
        &[("Host", server.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(map.status, 200, "{}", map.body);
    assert!(!map.body.contains("Where am I?"), "{}", map.body);
    assert!(
        map.body
            .contains("Where the last write is (not where you are)"),
        "{}",
        map.body
    );
    let here = here_stop(&map.body).unwrap_or_else(|| panic!("no fallback control:\n{}", map.body));
    let c_stop = stop_of_title(&map.body, "Hotfix triage");
    assert_eq!(here, c_stop, "{}", map.body);
}

/// `d200`'s own index follows the same rule for its focus field, and not
/// only the Today page it shares the underlying function with: a shared
/// function says where the data comes from, not that this surface prints
/// it.
#[test]
fn the_index_names_whose_focus_it_is_too() {
    let a = Sandbox::new_seeded("web-lanes-index-a");
    a.ok(&["push", "Main line work", "--why", "seed"]);
    let b = join_lane(&a, "web-lanes-index-b", "hotfix");
    b.ok(&["push", "Hotfix triage", "--why", "seed"]);
    let c = join_lane(&a, "web-lanes-index-c", "sonar");
    c.ok(&["push", "Backend webapi cleanup", "--why", "seed"]);
    let other = Sandbox::new_seeded_in("web-lanes-index-other", a.global_home());

    let server = Server::start_serving(
        &std::env::temp_dir(),
        a.global_home(),
        &[a.0.as_path(), other.0.as_path()],
    );
    let boot = call(server.port, &server.boot_path(), &[("Host", server.host())]);
    let token = token_from(&boot);
    let index = call(
        server.port,
        "/",
        &[("Host", server.host()), ("X-Vivac-Token", token)],
    );
    assert_eq!(index.status, 200, "{}", index.body);
    assert!(
        index.body.contains("Backend webapi cleanup"),
        "{}",
        index.body
    );
    assert!(
        index.body.contains("in lane sonar, 1 of 3 lanes"),
        "{}",
        index.body
    );
}