summaryrefslogtreecommitdiff
path: root/core/tape.zig
blob: 1552d65c46612b607a9f95e8c702ddf3e7002e43 (plain) (blame)
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
//! The recorder and its tape (docs/next-daemon.md, phase 1). Recording,
//! everything the core consumes is appended in the order it consumed it,
//! which is the turn's order (a 9P request served while a step is out in a
//! syscall lands inside that syscall's record):
//!
//!   - each call the host makes into the core (`Input`), with its arguments;
//!   - each call the core makes out into the host -- a Host function, or a
//!     syscall of its own (`Site`) -- and what it returned;
//!   - each field the host wrote in the core between calls (`watched`);
//!   - after every call the host made at the top, the session's digest.
//!
//! Replaying (`PARDES_REPLAY=<tape> pardes`, the same build), a core takes
//! its inputs off the tape instead: a host call answers what it answered, a
//! site returns what it returned, nothing is performed and no syscall is
//! made, and each digest is checked against the recorded one -- by two
//! replicas at different addresses and a third that never draws.
//!
//! The local path pays a check a call: `on` is null, and a core's tape is
//! `none` (it records nothing), unless PARDES_RECORD names where to write,
//! `<prefix><pid>.tape`. A core holds its tape (`Pardes.tape`) as it holds
//! its allocator; the free functions read `on`, set beside it, until the
//! last of their callers is handed the tape (P20).
const std = @import("std");
const pardes = @import("root.zig");
const walk = @import("walk.zig");
const host_io = @import("dev").host_io;
const Pardes = pardes.Pardes;
const Host = pardes.Host;
const VTable = Host.VTable;
const libc = std.c;

pub var on: ?*Tape = null;

/// The tape of a session nobody records (`Tape.through`): a core's when it
/// is given none, so `Pardes.tape` is never null. Nothing writes it.
pub var none: Tape = .{ .gpa = std.heap.page_allocator, .replay = false, .through = true, .scratch = .init(std.heap.page_allocator), .arena = .init(std.heap.page_allocator) };

/// Every call into the core a host makes (a 9P connection task's too).
/// An entry written once (`taped`) has the variant `Args(<the entry>)`,
/// its arguments after the core in order; the six written by hand say
/// what they carry, and each has its arm in `apply`.
pub const Input = union(enum) {
    init: pardes.Options,
    init_from_dump: struct { opts: pardes.Options, bytes: []const u8 },
    restore: Args(pardes.dump.restore),
    /// Whether it was the session's own core, or one a Restore replaced.
    deinit: bool,
    update: Args(Pardes.update),
    serve_fs: Args(Pardes.serveFs),
    pump,
    step: Args(Pardes.step),
    perform: Args(Pardes.perform),
    next_effect: Args(Pardes.nextEffect),
    advance: Args(Pardes.advance),
    render,
    take_restore: Args(Pardes.takeRestore),
    set_cwd: Args(Pardes.setCwd),
    acknowledge_shell: Args(Pardes.acknowledgeShell),
    /// A dead session's shell taken in (Adopt), and a terminal's reader
    /// that failed: what a host writes into the core, made inputs.
    adopt_shell: Args(Pardes.adoptShell),
    reader_failed: Args(Pardes.readerFailed),
    shell_failed: Args(Pardes.shellFailed),
    restart_failed: Args(Pardes.restartFailed),
    save_failed: Args(Pardes.saveFailed),
    dump_failed: Args(Pardes.dumpFailed),
    set_last_dump: Args(Pardes.setLastDump),
    set_message: Args(Pardes.setMessage),
    set_status: Args(Pardes.setStatus),
    report_error: Args(Pardes.reportError),
    reload_watched_file: Args(Pardes.reloadWatchedFile),
    note_late_failure: Args(Pardes.noteLateFailure),
    invalidate: Args(Pardes.invalidate),
    presented: Args(Pardes.presented),
    run_closed_lines: Args(pardes.ctlfs.runClosedLines),
    file_deleted: Args(pardes.panes.File.deleted),
    open_view: Args(Pardes.openView),
    close_view: Args(Pardes.closeView),
    leave_view: Args(Pardes.leaveView),
    away_view: Args(Pardes.awayView),
    rejoin_view: Args(Pardes.rejoinView),
    to_view: Pardes.View.Id,
    /// What a window says of its font and its opacity (gui.zig).
    take_font_request: Args(Pardes.takeFontRequest),
    observe_font: Args(Pardes.observeFont),
    acknowledge_font: Args(Pardes.acknowledgeFont),
    reject_font: Args(Pardes.rejectFont),
    window_opacity_done: Args(Pardes.windowOpacityDone),
};

/// The core's own syscalls (each `turn.yield()`s around itself), numbered
/// after the Host functions on the tape.
pub const Site = enum(u16) {
    // Out of the turn (`site`).
    os_stat,
    os_listing,
    os_rw,
    make_dirs,
    resolve,
    read_mount,
    read_file,
    dir_listing,
    kind,
    probe,
    preview,
    /// A search run on the loop (Stream.runHere: a 9P write's Grep or Find).
    search,
    /// The daemon's registry, as /sessions reads it (daemon.ask "list").
    sessions,
    /// Whether a shell is installed (host_io.Shell.refusal): the session's
    /// disk, asked as any file is.
    shell,
    /// The machine's fonts (Font <name>, Fonts): its disk too.
    fonts,
    /// What jj says of a file (jj.zig): a file at a revision.
    jj,
    // Read in place (`value`).
    clock,
    wake,
    env,
    interpreter,
    denied,
    mtime,
    /// What a terminal's ingest told the positions pardes keeps over it.
    positions,
    /// Whether a terminal is at its prompt, as a step reads it after its
    /// output (a greeting, a command waiting for the prompt), and what its
    /// command printed (a pty/run's answer): a screen-state replica's
    /// emulator is the last delta's until the next.
    prompt,
    /// What the authority alone holds and a step reads (`authority`).
    authority,
    /// What a call into a kind did (Kind.Outcome), and a kind's pane's
    /// tag prefix: the authority's, whose core alone runs the kind.
    addon,
    /// Whether the session reloads a terminal at a join (written since its
    /// last reload), then the hash of its snapshot as it did
    /// (panes.reloadTerminals), which every replica's own reload compares.
    reload,
    /// A kitty image's medium as a terminal's emulator read it (a file, a
    /// temporary file, shared memory: Term.media), its bytes or its failure.
    medium,
    /// An addon's library loaded or let go (Addon.perform): what it brought
    /// is the `addon` event inside it, which a replica applies from here.
    landing,
};

/// What the sites return. wire.semantics hashes their shape with the
/// rest of the tape's (`shape`), so two builds whose tapes differ in it
/// refuse each other's replicas in words, and a site returning a type not
/// listed is a compile error (`call`). An error union is listed as
/// `anyerror!` its payload: an error goes by its name (walk.encode).
pub const results = .{
    void,                          bool,
    u32,                           i64,
    [8]u8,                         ?u64,
    []const u8,                    ?[]const u8,
    ?std.Io.File.Kind,             ?pardes.filesystem.Resolved,
    pardes.filesystem.OsReadWrite, anyerror!pardes.filesystem.OsStat,
    anyerror![]const u8,           anyerror![]u8,
    anyerror!void,                 pardes.Term.Told,
    ?pardes.ctlfs.pty.Printed,     @typeInfo(@TypeOf(pardes.panes.Pane.greeting)).@"fn".return_type.?,
    []pardes.Stream.Batch,
        // What only the authority holds (`authority`): a closed pane's record,
        // Recent's entry for a closed jump, the closed panes' names.
            ?@import("Store.zig").Record,
    ?@import("recent.zig").Entry,  []const @import("Store.zig").Named,
    @import("Kind.zig").Outcome,   pardes.Term.Prompt,
    @import("jj.zig").Shown,
};

/// What a host reports to the core as failed (`shell_failed`, `save_failed`,
/// `dump_failed`, `report_error`), as a replica reads it back: an error is
/// taped by its name, and `anyerror` keeps no list of names to look one up
/// in. ponytail: kept by hand, the sets of what a host reports from; one
/// outside them is a Debug build's panic as it is taped (walk.encode) and a
/// release build's divergence (the replica joins again).
pub const Failure = ErrorOf(host_io.forkShell) || ErrorOf(pardes.filesystem.write) ||
    ErrorOf(pardes.filesystem.readRestore) || ErrorOf(pardes.dump.restore) ||
    @typeInfo(@TypeOf(pardes.config.User.dumpThemes(undefined, undefined, undefined, pardes.themes))).error_union.error_set ||
    ErrorOf(host_io.Lsp.snapshot) ||
    ErrorOf(host_io.Inbox.startReader) || std.Io.File.ReadStreamingError ||
    error{ NoDumpDirectory, ListenFailed, WorkersUnavailable, WorkersBusy };

fn ErrorOf(comptime f: anytype) type {
    return @typeInfo(@typeInfo(@TypeOf(f)).@"fn".return_type.?).error_union.error_set;
}

/// Every type the tape carries, as walk.shape says it: wire.semantics's.
/// The sites too: a record names one by its number.
pub const shape = blk: {
    var types: []const type = &.{ Input, Site, []const u64, struct { u8, u64 } };
    for (results) |R| types = types ++ .{R};
    for (host_fns) |f| types = types ++ .{Host.Ret(@field(Host.Fn, f))};
    for (watched) |name| types = types ++ .{Watched(name)};
    break :blk walk.shape(types);
};

/// Fields a host writes straight into the core between its calls.
const watched = .{ "frontend", "needs_frame", "quit", "active", "unattended" };

/// Watched field `name` of `p`: the live view's, or the session's.
fn watchedOf(p: *Pardes, comptime name: []const u8) *Watched(name) {
    return if (comptime @hasField(Pardes.View, name)) &@field(p.view(), name) else &@field(p, name);
}

fn Watched(comptime name: []const u8) type {
    return if (@hasField(Pardes.View, name)) @FieldType(Pardes.View, name) else @FieldType(Pardes, name);
}

/// `blob`: a record of `by_hash_min` bytes or more, in the replica stream,
/// as its kind and its bytes' BLAKE3 (`Big`): its bytes go beside the unit.
const Kind = enum(u8) { input, done, host, ret, set, digest, blob };
/// A record at least this long crosses to a replica by hash: a unit stays
/// under the wire's bound (16 MiB) whatever a file read holds.
pub const by_hash_min = 1 << 20;
/// A record's bytes by hash: the session's (`Tape.big`), to send; a
/// replica's (`Tape.files`), to replay. `path`: a file read's answer, which
/// a replica on the session's machine reads itself, its hash the file's
/// own bytes' (after the answer's 9: yes, a length), as a dump's text is.
pub const Big = struct {
    hash: [32]u8,
    bytes: []u8,
    path: bool = false,

    pub fn hashOf(bytes: []const u8, path: bool) [32]u8 {
        var h: [32]u8 = undefined;
        std.crypto.hash.Blake3.hash(if (path) bytes[9..] else bytes, &h, .{});
        return h;
    }
};
/// A digest record's kind byte (replica.zig reads a unit's last).
pub const digest_kind: u8 = @backingInt(Kind.digest);
pub const set_kind: u8 = @backingInt(Kind.set);
const host_fns = @typeInfo(VTable).@"struct".field_names;
/// The `set` that says which Host functions the recording host had.
const set_mask = 0xff;

pub const Tape = struct {
    gpa: std.mem.Allocator,
    /// Zig's `io`, handed to a site's body: in core/, a body is the only
    /// code that holds one.
    io: std.Io = std.Io.Threaded.global_single_threaded.io(),
    /// A session nobody records (`none`): every call goes through as it
    /// is, and nothing is taped.
    through: bool = false,
    replay: bool,
    /// The core whose digest is taken (a Restore replaces it).
    core: ?*Pardes = null,
    /// The host has the turn: a call into the core now is an input, and a
    /// call out of it is the host's to answer.
    host_side: bool = true,
    depth: u32 = 0,
    // Recording.
    fd: c_int = -1,
    buf: std.ArrayList(u8) = .empty,
    scratch: std.Io.Writer.Allocating,
    /// The host whose functions were last said (`noteHost`).
    real: Host = .{},
    seen: [watched.len]u64 = @splat(0),
    // Replaying.
    in: walk.Reader = .{ .bytes = &.{} },
    arena: std.heap.ArenaAllocator,
    last_ret: walk.Reader = .{ .bytes = &.{} },
    /// Which functions the session's host has, a bit each in the table's
    /// order (`Host.mask`): what a replica's core answers by (`has`).
    mask: u64 = 0,
    /// A replica's (a client's, a replay's), from its first replay or its
    /// join (`replayUnit`, `adoptCore`): its core has no host, and asks
    /// the tape what the session's has, between its steps too (a frame).
    replica: bool = false,
    skips_render: bool = false,
    digests: u64 = 0,
    /// What `diverge` said first, in `diverged_buf`: nothing to free.
    diverged: ?[]const u8 = null,
    diverged_buf: [1024]u8 = undefined,
    /// The input being applied, for a divergence's report.
    applying: []const u8 = "",
    /// PARDES_RECORD_EVERY: a digest after every input, a nested one's too
    /// (to find the step a divergence starts at), not only the host's last.
    every: bool = false,
    /// A replica applying its own input before the authority has ordered it
    /// (core/replica.zig): recorded as the authority would record it, so the
    /// two can be compared, but nothing is performed. A host call or a
    /// syscall stops it (`poisoned`): what the call returns is the
    /// authority's to say, and the input waits for it. A read of the clock
    /// or the environment (`value`) is made here, a guess the comparison
    /// checks.
    speculating: bool = false,
    poisoned: bool = false,
    /// The turn's yields when the speculation began (`stray`).
    yields: u64 = 0,
    /// What stopped it: a host function's or a site's name, or a poison's
    /// reason (PARDES_REPLICA_STATS counts them).
    poisoned_by: []const u8 = "",
    /// The authority's last yes or no to each question a replayed unit
    /// asked it (`authority`), a speculation's guess.
    answers: std.AutoHashMapUnmanaged(u64, bool) = .empty,
    /// The allocator of the core a replay makes (a replica's rollback epoch,
    /// core/rollback.zig), when it is not the tape's own.
    core_gpa: ?std.mem.Allocator = null,
    /// Where a replay keeps what a core keeps of an input (its options),
    /// for a tape that is let go; else the tape's allocator, for good.
    kept_arena: ?std.heap.ArenaAllocator = null,
    /// No digests recorded (a speculation's: a replica compares what it
    /// was given and what it asked, from a state the authority shares).
    no_digest: bool = false,
    /// PARDES_REPLAY_DUMP (phase 2's gate): at the session's end, its dump
    /// loaded must be it, digest for digest, and dump again byte for byte.
    dump_check: bool = false,
    dumps: usize = 0,
    dump_bytes: usize = 0,
    /// The session's (replica.Peers): called between two of its inputs once
    /// what it recorded since its last unit passes `unit_max`, to send that
    /// as a unit: a pump of a flood's reads is cut into units under it.
    cut: ?struct { ctx: *anyopaque, f: *const fn (*anyopaque) void } = null,
    /// A digest as one word (screen-state replicas: every unit of a pty's
    /// output carries one, at the pty's read rate), not one a field; what
    /// differs is then not named.
    whole_digest: bool = false,
    /// A digest only when asked (`recordDigest`): the replica stream's,
    /// one a unit, not one after each of its inputs.
    unit_digests: bool = false,
    /// A digest record replayed is compared with the core's own; a replica
    /// client's compares one now and then (core/replica.zig `check_every`).
    checks: bool = true,
    /// A replica client's guess of the session's clocks for a speculation
    /// (core/replica.zig): its clock reads (a message's stamp, a file's
    /// mtime) answer this instead of the clocks here.
    guess: ?Guess = null,
    /// The same guess, as the client sent it with its input, while the
    /// authority steps that input: the step's clock reads are the input's
    /// time, so the guess a speculation recorded is what the authority
    /// records (a message's millisecond, an edit's second never miss).
    stamp: ?Guess = null,
    /// The replica stream's records by hash (`unit_digests`), until the
    /// unit is sent (core/replica.zig `Peers.unit`).
    big: std.ArrayListUnmanaged(Big) = .empty,
    /// A replica's: the last few records by hash it was sent or read.
    files: std.ArrayListUnmanaged(Big) = .empty,
    /// A replica on the session's machine: a file read by hash is read
    /// here, by its path, and checked.
    local_files: bool = false,
    /// The path a `read_file` site reads, while it is recorded or replayed.
    reading: ?[:0]const u8 = null,

    fn record(t: *Tape, kind: Kind, comptime T: type, v: *const T) void {
        t.scratch.clearRetainingCapacity();
        walk.encode(T, v, &t.scratch.writer) catch @panic("tape: out of memory");
        var payload = t.scratch.written();
        var kind_ = kind;
        var by_hash: [34]u8 = undefined;
        if (t.unit_digests and payload.len >= by_hash_min) {
            // A file read's yes, by the file's bytes' hash.
            const path = t.reading != null and kind == .ret and payload[0] == 1;
            by_hash[0] = @backingInt(kind);
            by_hash[1..33].* = Big.hashOf(payload, path);
            by_hash[33] = @intFromBool(path);
            const bytes = t.gpa.dupe(u8, payload) catch @panic("tape: out of memory");
            t.big.append(t.gpa, .{ .hash = by_hash[1..33].*, .bytes = bytes, .path = path }) catch @panic("tape: out of memory");
            payload = &by_hash;
            kind_ = .blob;
        }
        const len: u32 = @intCast(payload.len);
        t.buf.append(t.gpa, @backingInt(kind_)) catch @panic("tape: out of memory");
        t.buf.appendSlice(t.gpa, std.mem.asBytes(&len)) catch @panic("tape: out of memory");
        t.buf.appendSlice(t.gpa, payload) catch @panic("tape: out of memory");
        if (t.buf.items.len > 1 << 20) t.flush();
    }

    fn flush(t: *Tape) void {
        // A tape in memory (a replica's, an authority's stream) is taken
        // by whoever holds it.
        if (t.fd < 0) return;
        _ = host_io.writeFd(t.fd, t.buf.items);
        t.buf.clearRetainingCapacity();
    }

    /// What the host wrote between calls, said before the core goes on.
    fn noteWrites(t: *Tape) void {
        const p = t.core orelse return;
        inline for (watched, 0..) |name, i| {
            const now = walk.digest(Watched(name), watchedOf(p, name));
            if (now != t.seen[i]) {
                t.seen[i] = now;
                const set: struct { u8, Watched(name) } = .{ i, watchedOf(p, name).* };
                t.record(.set, @TypeOf(set), &set);
            }
        }
    }

    fn seeFields(t: *Tape) void {
        const p = t.core orelse return;
        inline for (watched, 0..) |name, i| t.seen[i] = walk.digest(Watched(name), watchedOf(p, name));
    }

    /// Which functions the session's host has, said at an entry whose
    /// core holds another host than the last said (each pump is given its
    /// host again: then nothing).
    fn noteHost(t: *Tape, p: *const Pardes) void {
        if (p.host.vtable == t.real.vtable and p.host.ctx == t.real.ctx) return;
        t.real = p.host;
        t.mask = p.host.mask();
        const set: struct { u8, u64 } = .{ set_mask, t.mask };
        t.record(.set, @TypeOf(set), &set);
    }

    fn enterInput(t: *Tape, p: ?*Pardes, input: *const Input) Entered {
        if (!t.host_side) return .{};
        t.host_side = false;
        t.depth += 1;
        if (t.replay) return .{ .tape = t };
        if (p) |core| {
            if (t.core == null) t.core = core;
            t.noteWrites();
            t.noteHost(core);
        }
        t.record(.input, Input, input);
        return .{ .tape = t };
    }

    fn leaveInput(t: *Tape, p: ?*Pardes) void {
        t.depth -= 1;
        t.host_side = true;
        if (t.replay) return;
        if (p) |core| if (t.core == null) {
            t.core = core;
            t.noteHost(core);
        };
        t.record(.done, void, &{});
        if ((t.depth == 0 or t.every) and !t.no_digest and !t.unit_digests) recordDigest(t);
        if (t.depth == 0) t.flush();
        t.seeFields();
        if (t.depth == 0 and t.buf.items.len >= unit_max) if (t.cut) |c| c.f(c.ctx);
    }

    // ---- replaying ----

    const Record = struct { kind: Kind, payload: walk.Reader };

    /// The next record, or null at the tape's end; a record the tape cannot
    /// read (cut short, of no kind, by a hash not here) diverges it.
    fn next(t: *Tape) ?Record {
        const head = t.in.take(5) catch return null;
        const len = std.mem.bytesToValue(u32, head[1..5]);
        const payload = t.in.take(len) catch {
            t.diverge("the tape ends inside a record", .{});
            return null;
        };
        const kind = std.enums.fromInt(Kind, head[0]) orelse {
            t.diverge("a record of no kind ({d})", .{head[0]});
            return null;
        };
        if (kind != .blob) return .{ .kind = kind, .payload = .{ .bytes = payload } };
        if (payload.len != 34) {
            t.diverge("a record by hash is short", .{});
            return null;
        }
        const of = std.enums.fromInt(Kind, payload[0]) orelse {
            t.diverge("a record by hash of no kind ({d})", .{payload[0]});
            return null;
        };
        const bytes = t.byHash(payload[1..33], payload[33] != 0) orelse {
            t.diverge("a record by hash {x} is not here", .{payload[1..9]});
            return null;
        };
        return .{ .kind = of, .payload = .{ .bytes = bytes } };
    }

    /// The next record's kind, or null at the tape's end and for a byte of
    /// no kind (which `next` diverges on).
    fn peek(t: *const Tape) ?Kind {
        if (t.in.bytes.len - t.in.at < 5) return null;
        const kind = std.enums.fromInt(Kind, t.in.bytes[t.in.at]) orelse return null;
        if (kind == .blob and t.in.bytes.len - t.in.at > 5) return std.enums.fromInt(Kind, t.in.bytes[t.in.at + 5]);
        return kind;
    }

    /// A host record's call (its first two bytes), 0 for one too short to
    /// name it: what a divergence says.
    fn hostId(payload: []const u8) u16 {
        return if (payload.len < 2) 0 else std.mem.bytesToValue(u16, payload[0..2]);
    }

    /// The bytes of a record by hash: sent, or read here (a file read's
    /// answer, on the session's machine), each checked against its hash.
    fn byHash(t: *Tape, hash: *const [32]u8, is_path: bool) ?[]const u8 {
        for (t.files.items) |f| if (std.mem.eql(u8, &f.hash, hash)) return f.bytes;
        const path = t.reading orelse return null;
        if (!t.local_files or !is_path) return null;
        const file = pardes.filesystem.readHost(t.io, t.gpa, path, pardes.memory.limits.max_file_bytes) catch return null;
        defer t.gpa.free(file);
        // The answer as `record` wrote it: an error union's yes, a length, the bytes.
        const bytes = t.gpa.alloc(u8, 9 + file.len) catch return null;
        bytes[0] = 1;
        std.mem.writeInt(u64, bytes[1..9], file.len, .little);
        @memcpy(bytes[9..], file);
        if (!std.mem.eql(u8, &Big.hashOf(bytes, true), hash)) {
            t.gpa.free(bytes);
            return null;
        }
        keepFile(t, .{ .hash = hash.*, .bytes = bytes, .path = true });
        return bytes;
    }

    /// A replay came to another state than the authority's (`why`, the
    /// first said): its replica joins again.
    pub fn diverge(t: *Tape, comptime why: []const u8, args: anytype) void {
        if (t.diverged != null) return;
        t.diverged = std.fmt.bufPrint(&t.diverged_buf, why ++ " (tape byte {d}, in {s})", args ++ .{ t.in.at, t.applying }) catch why;
    }

    /// A host call a replica that skips render does not make (it draws no frame,
    /// so presents none): what the host told the core inside it (what it
    /// presented, `presented`) is applied all the
    /// same, the host's own calls below it stepped over.
    fn skipHost(t: *Tape) void {
        while (t.diverged == null) {
            var rec = t.next() orelse return;
            switch (rec.kind) {
                .ret => return,
                .input => t.apply(&rec.payload),
                .set => t.applySet(&rec.payload),
                .host => t.skipHost(),
                .digest => t.check(rec.payload.bytes),
                .done, .blob => return t.diverge("a host call's records are out of order", .{}),
            }
        }
    }

    /// Over a call the replica does not make (a present, in one that skips render),
    /// what was applied inside it too.
    fn skip(t: *Tape) void {
        var depth: usize = 1;
        while (depth > 0) {
            const rec = t.next() orelse return;
            switch (rec.kind) {
                .host, .input => depth += 1,
                .ret, .done => depth -= 1,
                else => {},
            }
        }
    }

    /// The records of an input up to its end: what was applied inside it,
    /// as it was; a replica that skips render steps over the host calls it did
    /// not make.
    fn finishInput(t: *Tape) void {
        while (t.diverged == null) {
            const kind = t.peek() orelse return t.diverge("the tape ends inside an input", .{});
            var rec = t.next() orelse return t.diverge("the tape ends inside an input", .{});
            switch (kind) {
                .done => return,
                .set => t.applySet(&rec.payload),
                .host => if (t.skips_render) t.skipHost() else return t.diverge("the core did not make the host call {d} the tape has", .{hostId(rec.payload.bytes)}),
                .input => t.apply(&rec.payload),
                .digest => t.check(rec.payload.bytes),
                .ret, .blob => return t.diverge("the core's input ended before the recorded one", .{}),
            }
        }
    }

    /// The records inside a host call up to its return, whose result is
    /// left in `last_ret`.
    fn finishHost(t: *Tape) bool {
        while (t.diverged == null) {
            var rec = t.next() orelse {
                t.diverge("the tape ends inside a host call", .{});
                return false;
            };
            switch (rec.kind) {
                .ret => {
                    t.last_ret = rec.payload;
                    return true;
                },
                .input => t.apply(&rec.payload),
                .set => t.applySet(&rec.payload),
                .digest => t.check(rec.payload.bytes),
                .host, .done, .blob => {
                    t.diverge("a host call's records are out of order", .{});
                    return false;
                },
            }
        }
        return false;
    }

    fn expectHost(t: *Tape, id: u16, comptime what: []const u8) bool {
        if (t.diverged != null) return false;
        const rec = t.next() orelse {
            t.diverge("the core called " ++ what ++ " past the tape's end", .{});
            return false;
        };
        if (rec.kind != .host or rec.payload.bytes.len < 2 or hostId(rec.payload.bytes) != id) {
            const other: u16 = if (rec.kind == .host) hostId(rec.payload.bytes) else 0;
            t.diverge("the core called " ++ what ++ " where the tape has a {t} ({d})", .{ rec.kind, other });
            return false;
        }
        const outer = !t.host_side;
        t.host_side = true;
        defer t.host_side = !outer;
        return t.finishHost();
    }

    /// A digest record's payload (a unit's last) against the core's own: a
    /// difference is `diverged`, its fields named when the record has them.
    pub fn check(t: *Tape, payload: []const u8) void {
        if (!t.checks) return;
        var r: walk.Reader = .{ .bytes = payload };
        const want = walk.decode([]const u64, &r, t.arena.allocator()) catch return;
        const p = t.core orelse return;
        var parts: Parts = undefined;
        const whole = [1]u64{digestOf(p)};
        const got: []const u64 = if (want.len == 1) &whole else digestParts(p, &parts);
        if (!std.mem.eql(u64, got, want)) t.diverge("digest {d} differs in {s}", .{ t.digests, if (want.len == 1) "the session (a digest of one word: run the authority with whole_digest off to name the field)" else partsDiffer(got, want, t.arena.allocator()) });
        t.digests += 1;
    }

    /// The session's dump loaded into a core of its own, which must be the
    /// same session (its digest) and dump to the same bytes. The tape is
    /// put aside meanwhile: a dump is no input.
    fn dumpRoundTrip(t: *Tape, p: *Pardes) void {
        on = null;
        defer on = t;
        // The core's own tape aside too: the dump's reads are no input.
        p.tape = &none;
        defer p.tape = t;
        const bytes = pardes.dump.dumpBytes(p) catch |err| return t.diverge("dump failed: {t}", .{err});
        defer t.gpa.free(bytes);
        var notes: std.ArrayList(u8) = .empty;
        defer notes.deinit(t.gpa);
        // Its own core, on no tape (the session's options name this one).
        var opts = p.opts;
        opts.tape = &none;
        const q = pardes.dump.load(t.gpa, opts, bytes, &notes) catch |err| return t.diverge("dump load failed: {t}", .{err});
        defer q.deinit();
        if (notes.items.len > 0) return t.diverge("dump of this build had notes: {s}", .{notes.items});
        var want: Parts = undefined;
        var got: Parts = undefined;
        const a = digestParts(p, &want);
        const b = digestParts(q, &got);
        if (!std.mem.eql(u64, a, b)) return t.diverge("dump round trip: the loaded digest differs in {s}", .{partsDiffer(b, a, t.arena.allocator())});
        const again = pardes.dump.dumpBytes(q) catch |err| return t.diverge("dump of the loaded failed: {t}", .{err});
        defer t.gpa.free(again);
        if (!std.mem.eql(u8, bytes, again)) {
            const at = std.mem.indexOfDiff(u8, bytes, again) orelse 0;
            return t.diverge("dump is no fixpoint: {d} bytes then {d}, first differing at {d}", .{ bytes.len, again.len, at });
        }
        t.dumps += 1;
        t.dump_bytes += bytes.len;
    }

    fn applySet(t: *Tape, r: *walk.Reader) void {
        const which = (r.take(1) catch return)[0];
        if (which == set_mask) {
            t.mask = std.mem.bytesToValue(u64, r.take(8) catch return);
            return;
        }
        const p = t.core orelse return;
        inline for (watched, 0..) |name, i| if (i == which) {
            watchedOf(p, name).* = walk.decode(Watched(name), r, t.arena.allocator()) catch return;
        };
    }

    /// One input, applied to the replica as the host applied it.
    fn apply(t: *Tape, r: *walk.Reader) void {
        // A session's options are kept by its core (`opts`): theirs for good.
        const Tag = std.meta.Tag(Input);
        const tag = walk.enumFrom(Tag, (r.take(@sizeOf(Tag)) catch return t.diverge("a short input", .{}))[0..@sizeOf(Tag)]) orelse return t.diverge("an input of no kind", .{});
        r.at -= @sizeOf(Tag);
        const kept = tag == .init or tag == .init_from_dump or tag == .restore;
        const keep = if (t.kept_arena) |*k| k.allocator() else t.gpa;
        const input = walk.decode(Input, r, if (kept) keep else t.arena.allocator()) catch return t.diverge("a short input", .{});
        const outer = t.applying;
        t.applying = switch (input) {
            .update => |a| @tagName(a.args[0]),
            else => @tagName(input),
        };
        defer t.applying = outer;
        t.host_side = true;
        defer t.host_side = true;
        // Not at the end: the dump checked there reads through no tape.
        const yields = pardes.turn.yields;
        defer if (input != .deinit) t.stray(yields);
        switch (input) {
            .init, .init_from_dump => {
                var opts = switch (input) {
                    .init => |o| o,
                    .init_from_dump => |d| d.opts,
                    else => unreachable,
                };
                const gpa = t.core_gpa orelse t.gpa;
                opts.image_allocator = gpa;
                opts.tree_sitter_allocator = gpa;
                opts.frame_allocator = gpa;
                opts.tape = t;
                t.core = switch (input) {
                    .init => Pardes.init(gpa, opts),
                    .init_from_dump => |d| pardes.dump.initFromDump(gpa, opts, d.bytes),
                    else => unreachable,
                } catch |err| return t.diverge("init failed: {t}", .{err});
                return t.finishInput();
            },
            else => {},
        }
        const p = t.core orelse return t.diverge("an input before the core", .{});
        switch (input) {
            .init, .init_from_dump => unreachable,
            .restore => |a| {
                const nc = pardes.dump.restore(p, a.args[0], a.args[1]) catch |err| return t.diverge("restore failed: {t}", .{err});
                t.core = nc;
                nc.tape = t;
            },
            // The session is over (or the core a Restore replaced is
            // freed): nothing done now is compared.
            .deinit => |own| {
                if (own) {
                    if (t.dump_check) if (t.core) |core| t.dumpRoundTrip(core);
                    t.core = null;
                }
                return t.skip();
            },
            .pump => p.pump(.{}) catch {},
            .render => if (t.skips_render) return t.skip() else {
                _ = p.frame_arena.reset(.retain_capacity);
                _ = p.render(p.frame_arena.allocator()) catch {};
            },
            .to_view => |k| p.toView(k),
            // Every entry written once: the one its variant names.
            inline else => |a| _ = @call(.auto, @TypeOf(a).entry, .{p} ++ a.args),
        }
        t.finishInput();
    }

    // ---- the entry points, on the handle a step is given (`Pardes.tape`,
    // or a `tape: *Tape` parameter); the free functions below are the
    // same on `on` until the last of their callers is moved ----

    /// A syscall of the core's own, `f(args)`, made out of the turn (a 9P
    /// request through a mount of this very session is answered meanwhile):
    /// recorded with what it returned, or answered from the tape and never
    /// made. A result with slices is decoded into `a` on replay, the allocator
    /// `f` would have used.
    pub fn site(t: *Tape, comptime s: Site, a: ?std.mem.Allocator, comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? {
        return t.call(s, a, f, args, true);
    }

    /// A read of the host's that is no syscall out of the turn (the clock, the
    /// environment) or yields for itself: as `site`.
    pub fn value(t: *Tape, comptime s: Site, comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? {
        return t.call(s, null, f, args, false);
    }

    /// A read of what the authority alone holds (`.authority` state a step
    /// makes digested state from: the session's closed panes, and Recent, which
    /// every session of its user writes; the 9P server's readers and socket),
    /// taped as `value` is; a speculation that reaches it waits for the
    /// authority's answer, as at a host call. A replica's own is never read.
    /// What it returns is the tape's arena's on a replay: `f` returns what
    /// lives to the step's end (scratch, or the authority's own), and the
    /// caller copies what it keeps.
    ///
    /// A yes or no (whether a script reads a pane's events, whether the
    /// session serves a socket) is guessed by a speculation, mosh's way: the
    /// authority's last answer to that question, as a replayed unit gave it,
    /// recorded as the answer, so its unit confirms the guess or rolls it back.
    /// A Look or a click's command in a pane then shows at once, not a round
    /// trip late. ponytail: bools alone; a list (the closed panes, Recent)
    /// changes with what the user does, and is asked of the authority.
    pub fn authority(t: *Tape, comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? {
        if (comptime @typeInfo(@TypeOf(f)).@"fn".return_type.? == bool) {
            if (t.speculating) if (t.answers.get(question(f, args))) |was| {
                const id: u16 = @as(u16, host_fns.len) + @backingInt(Site.authority);
                t.record(.host, u16, &id);
                t.record(.ret, bool, &was);
                return was;
            };
            if (t.replay) {
                const got = t.value(.authority, f, args);
                t.answers.put(t.gpa, question(f, args), got) catch {};
                return got;
            }
        }
        t.poison("the authority's own state");
        return t.value(.authority, f, args);
    }

    /// A body whose first parameter is an `std.Io` its caller does not pass
    /// is handed the tape's (`args` are the rest): the only way core/ comes
    /// to hold one.
    fn call(t: *Tape, comptime s: Site, a: ?std.mem.Allocator, comptime f: anytype, args: anytype, comptime yields: bool) @typeInfo(@TypeOf(f)).@"fn".return_type.? {
        const R = @typeInfo(@TypeOf(f)).@"fn".return_type.?;
        const params = @typeInfo(@TypeOf(f)).@"fn".param_types;
        const full = if (comptime params.len == args.len + 1 and params[0] == std.Io) .{t.io} ++ args else args;
        comptime {
            const Listed = if (@typeInfo(R) == .error_union) anyerror!@typeInfo(R).error_union.payload else R;
            for (results) |T| {
                if (T == Listed) break;
            } else @compileError("tape: the site ." ++ @tagName(s) ++ " returns " ++ @typeName(R) ++ ", which tape.results does not list");
        }
        // No tape where there is no host to record or replay one.
        if (t.through) return if (yields) out(f, full) else @call(.auto, f, full);
        const id: u16 = @as(u16, host_fns.len) + @backingInt(s);
        if (comptime s == .read_file) t.reading = args[1];
        defer if (comptime s == .read_file) {
            t.reading = null;
        };
        if (t.replay) {
            // Diverged (said in `diverged`): what a speculation gets, harmless,
            // for the rest of the input. A replica joins again; a replay says so.
            if (!t.expectHost(id, @tagName(s))) return poisonOf(R);
            // What a terminal told (its rows moved, its prompt, a command's
            // output) is the session's answer, kept, and a replica whose
            // emulators are fed the same bytes asks its own and compares: a
            // check a unit, for nothing (P30: a digest, not state).
            if (comptime s == .positions or s == .prompt) {
                const mine = @call(.auto, f, full);
                t.scratch.clearRetainingCapacity();
                walk.encode(R, &mine, &t.scratch.writer) catch @panic("tape: out of memory");
                if (!std.mem.eql(u8, t.scratch.written(), t.last_ret.bytes[t.last_ret.at..])) t.diverge("what this replica's terminal told ({t}) is not what the session's did", .{s});
            }
            var ret = t.last_ret;
            return walk.decode(R, &ret, a orelse t.arena.allocator()) catch {
                t.diverge("the tape's answer to {t} is short", .{s});
                return poisonOf(R);
            };
        }
        // The host's own (a shell's spawn asking the shell), or one inside a
        // site's syscall: the outer call is the record.
        if (t.host_side) return if (yields) out(f, full) else @call(.auto, f, full);
        // A syscall a speculating replica must not make: its input waits for
        // the authority's answer.
        if (yields and t.speculating) {
            t.poisoned = true;
            t.poisoned_by = @tagName(s);
            return poisonOf(R);
        }
        if (comptime s == .clock or s == .mtime) if (if (t.speculating) t.guess else t.stamp) |g| {
            const r = guessed(R, g);
            t.record(.host, u16, &id);
            t.record(.ret, R, &r);
            return r;
        };
        t.record(.host, u16, &id);
        t.seeFields();
        t.host_side = true;
        const r = if (yields) out(f, full) else @call(.auto, f, full);
        t.host_side = false;
        t.noteWrites();
        t.record(.ret, R, &r);
        return r;
    }

    /// One call out to the session's host, `f(args)`: made and recorded
    /// with what it answered; answered from the tape on a replay; refused
    /// to a speculation, or recorded as made (`keeps_stopping`). Null: the
    /// session's host has no such function.
    pub inline fn host(t: *Tape, p: *const Pardes, comptime f: Host.Fn, args: Host.Args(f)) ?Host.Ret(f) {
        // Nobody records: the call it always was.
        if (t.through) return p.host.call(f, args);
        if (!t.has(p, f)) return null;
        return hostCall(t, p, f, args);
    }

    /// Whether the session's host has `f`, asked apart from a call: a
    /// replica's core has no host, and answers as its session's did.
    pub fn has(t: *const Tape, p: *const Pardes, comptime f: Host.Fn) bool {
        if (!t.replica) return p.host.has(f);
        // A replica that never draws asks, and is told no one watches (`hostCall`).
        if (comptime f == .watched) if (t.skips_render) return true;
        return t.mask & (@as(u64, 1) << @backingInt(f)) != 0;
    }

    /// Asked by `turn.yield`: a syscall a replica must never make.
    pub fn replaying(t: *const Tape) bool {
        return t.replay or t.speculating;
    }

    /// A syscall of the core's that is no site, made by a replica since the
    /// turn's count of yields was `since`: what it returned is the
    /// authority's to say. A speculation waits for it, and a replay has
    /// diverged (it joins again), never the process (a window client's
    /// `Term fish`, H17).
    fn stray(t: *Tape, since: u64) void {
        if (pardes.turn.yields == since) return;
        if (t.speculating) t.poisoned = true else t.diverge("a syscall that is no tape site, made replaying", .{});
    }

    /// Inside a step: one being recorded, a replica's replay of one, or its
    /// speculation. A read made between steps (a frame drawn) is none.
    pub fn stepping(t: *const Tape) bool {
        return t.depth > 0 or t.replay or t.speculating;
    }

    /// What a speculation reached is the authority's (`why`): the input is
    /// undone and waits for the authority's order.
    pub fn poison(t: *Tape, why: []const u8) void {
        if (t.speculating) {
            t.poisoned = true;
            t.poisoned_by = why;
        }
    }

    /// A replica's speculation leaves what is the authority's be (a terminal's
    /// emulator, a kind's state): true, and the input waits for its order.
    pub fn authorityOnly(t: *Tape, comptime why: []const u8) bool {
        if (!t.speculating) return false;
        t.poison(why);
        return true;
    }

    /// The core a Restore made is the session's from here.
    pub fn adopt(t: *Tape, p: *Pardes) void {
        p.tape = t;
        if (t.replay or t.through) return;
        t.core = p;
        t.noteHost(p);
    }

    /// Whether `p` is the core being recorded (a Restore's old one is not).
    pub fn current(t: *const Tape, p: *const Pardes) bool {
        return t.core == null or t.core == p;
    }

    /// The session's core is freed: no digest of it after.
    pub fn forget(t: *Tape, p: *Pardes) void {
        if (t.core == p) t.core = null;
    }
};

const pardes_fields = walk.fieldNames(Pardes);
const stream_fields = walk.fieldNames(pardes.Stream);
const pane_fields = walk.fieldNames(pardes.Pane);
const file_fields = walk.fieldNames(pardes.panes.File.State);
const places_fields = walk.fieldNames(pardes.panes.Places);
const view_fields = walk.fieldNames(Pardes.View);
pub const Parts = [pardes_fields.len + stream_fields.len + pardes.views.max * view_fields.len + pardes.MAX_PANES * (2 + pane_fields.len + file_fields.len + places_fields.len)]u64;

/// The session's digest as one per field of the core's, its stream's, and
/// each pane's and its file's, so a divergence says where it is.
pub fn digestParts(p: *const Pardes, parts: *Parts) []const u64 {
    var n = walk.fieldDigests(Pardes, p, parts[0..pardes_fields.len]).len;
    n += walk.fieldDigests(pardes.Stream, &p.stream, parts[n..][0..stream_fields.len]).len;
    for (&p.views) |*slot| if (slot.*) |*v| {
        n += walk.fieldDigests(Pardes.View, v, parts[n..][0..view_fields.len]).len;
    } else {
        @memset(parts[n..][0..view_fields.len], 0);
        n += view_fields.len;
    };
    for (p.panes, 0..) |slot, id| {
        const pane = slot orelse continue;
        parts[n] = id;
        parts[n + 1] = @intFromBool(pane.file != null);
        n += 2;
        n += walk.fieldDigests(pardes.Pane, pane, parts[n..][0..pane_fields.len]).len;
        if (pane.file) |*f| n += walk.fieldDigests(pardes.panes.File.State, f, parts[n..][0..file_fields.len]).len;
        n += walk.fieldDigests(pardes.panes.Places, &pane.places, parts[n..][0..places_fields.len]).len;
    }
    return parts[0..n];
}

/// The fields whose digests differ, named.
pub fn partsDiffer(got: []const u64, want: []const u64, a: std.mem.Allocator) []const u8 {
    var said: std.ArrayList(u8) = .empty;
    if (got.len != want.len) said.print(a, "the panes there are ({d} parts, {d} recorded); ", .{ got.len, want.len }) catch {};
    const n = @min(got.len, want.len);
    var i: usize = 0;
    var count: usize = 0;
    while (i < pardes_fields.len + stream_fields.len and i < n) : (i += 1) {
        if (got[i] == want[i]) continue;
        const name = if (i < pardes_fields.len) pardes_fields[i] else stream_fields[i - pardes_fields.len];
        said.print(a, "{s}{s} ", .{ if (i < pardes_fields.len) "" else "stream.", name }) catch {};
        count += 1;
    }
    for (0..pardes.views.max) |k| for (view_fields) |name| {
        if (i >= n) break;
        if (got[i] != want[i]) {
            said.print(a, "views[{d}].{s} ", .{ k, name }) catch {};
            count += 1;
        }
        i += 1;
    };
    while (i + 2 <= n and count < 16) {
        const id = got[i];
        const has_file = got[i + 1] != 0;
        i += 2;
        for (pane_fields) |name| {
            if (i >= n) break;
            if (got[i] != want[i]) {
                said.print(a, "pane {d}.{s} ", .{ id, name }) catch {};
                count += 1;
            }
            i += 1;
        }
        if (has_file) for (file_fields) |name| {
            if (i >= n) break;
            if (got[i] != want[i]) {
                said.print(a, "pane {d}.file.{s} ", .{ id, name }) catch {};
                count += 1;
            }
            i += 1;
        };
        for (places_fields) |name| {
            if (i >= n) break;
            if (got[i] != want[i]) {
                said.print(a, "pane {d}.places.{s} ", .{ id, name }) catch {};
                count += 1;
            }
            i += 1;
        }
    }
    return said.items;
}

/// A call into the core: the host's, and recorded, or the core's own. The
/// tape it entered (null: the core's own, or nobody records), so `leave`
/// needs neither the global nor a core `init` did not make or `deinit` freed.
pub const Entered = struct { tape: ?*Tape = null };

pub inline fn enter(p: ?*Pardes, input: Input) Entered {
    // While the global is (P20: the terminal's questions read it), a core
    // stepped is the one it says: every entry a safe build makes checks it.
    if (std.debug.runtime_safety) if (p) |core| if (on) |was| if (core.tape != was)
        @panic("tape: a core's field is not the tape being stepped (tape.on)");
    const t = tapeOf(p, &input);
    // A client's tape between its steps records nothing (its frame drawn,
    // its core freed: the test "a client's frame drawn between its steps
    // records nothing into its idle tape"); an authority's records every
    // entry, in a Stepping scope or not, as a real session's.
    if (!records(t)) return .{};
    return t.enterInput(p, &input);
}

/// The tape an entry steps: its core's; for a session not made yet, the one
/// its options name (`Pardes.create`'s).
fn tapeOf(p: ?*Pardes, input: *const Input) *Tape {
    if (p) |core| return core.tape;
    const opts = switch (input.*) {
        .init => |o| o,
        .init_from_dump => |d| d.opts,
        else => return &none,
    };
    return opts.tape orelse &none;
}

/// Whether an entry on `t` is recorded: not on the tape nobody records, nor
/// on a replica's between its steps (a client's frame drawn, its core freed).
fn records(t: *const Tape) bool {
    return !(t.through or (t.replica and !t.replaying()));
}

pub inline fn leave(p: ?*Pardes, e: Entered) void {
    if (e.tape) |t| t.leaveInput(p);
}

/// An entry written once (P22): its public name made from the private
/// body directly under it, `pub const setCwd = pardes.tape.taped(setCwdInner);`.
/// The same parameters; the call recorded as the variant of `Input` whose
/// line names the entry (`set_cwd: Args(Pardes.setCwd)`), which the entry
/// finds by itself; the body inlined, so the entry compiles to what one
/// opening with its own `enter` and deferred `leave` did.
pub fn taped(comptime inner: anytype) @TypeOf(inner) {
    const T = Taped(inner);
    return switch (@typeInfo(@TypeOf(inner)).@"fn".param_types.len) {
        1 => T.f1,
        2 => T.f2,
        3 => T.f3,
        4 => T.f4,
        else => @compileError("tape: an entry of more arguments"),
    };
}

/// One function for each number of parameters, of which only the one
/// `taped` picks is analysed; a profile names it `tape.Taped((function
/// '<inner>')).f<n>`. The variant is found in the body, not in the
/// declaration: there it would need `Input`, whose line needs the entry
/// (a dependency loop).
fn Taped(comptime inner: anytype) type {
    const F = @typeInfo(@TypeOf(inner)).@"fn";
    const P = F.param_types;
    const R = F.return_type.?;
    return struct {
        fn f1(p: P[0].?) R {
            const entered = enter(p, @unionInit(Input, tagOf(f1, @This()), .{ .args = .{} }));
            defer leave(p, entered);
            return @call(.always_inline, inner, .{p});
        }
        fn f2(p: P[0].?, a: P[1].?) R {
            const entered = enter(p, @unionInit(Input, tagOf(f2, @This()), .{ .args = .{a} }));
            defer leave(p, entered);
            return @call(.always_inline, inner, .{ p, a });
        }
        fn f3(p: P[0].?, a: P[1].?, b: P[2].?) R {
            const entered = enter(p, @unionInit(Input, tagOf(f3, @This()), .{ .args = .{ a, b } }));
            defer leave(p, entered);
            return @call(.always_inline, inner, .{ p, a, b });
        }
        fn f4(p: P[0].?, a: P[1].?, b: P[2].?, c: P[3].?) R {
            const entered = enter(p, @unionInit(Input, tagOf(f4, @This()), .{ .args = .{ a, b, c } }));
            defer leave(p, entered);
            return @call(.always_inline, inner, .{ p, a, b, c });
        }
    };
}

/// What an entry's variant carries: its arguments after the core, and
/// the entry itself, which makes the type the entry's own (two entries of
/// the same parameters are two types): the entry finds its variant by it
/// (`tagOf`) and the replay calls the entry from it (`apply`).
pub fn Args(comptime f: anytype) type {
    const params = @typeInfo(@TypeOf(f)).@"fn".param_types;
    var types: [params.len - 1]type = undefined;
    for (params[1..], &types) |P, *T| T.* = P.?;
    const Tuple = @Tuple(&types);
    return struct {
        args: Tuple,
        pub const entry = f;
    };
}

/// The variant whose line names `entry`, which `Made` (`Taped(inner)`) made.
fn tagOf(comptime entry: anytype, comptime Made: type) [:0]const u8 {
    const u = @typeInfo(Input).@"union";
    var found: ?[:0]const u8 = null;
    for (u.field_names, u.field_types) |name, T| {
        if (@typeInfo(T) != .@"struct" or !@hasDecl(T, "entry")) continue;
        if (@TypeOf(T.entry) != @TypeOf(entry) or T.entry != entry) continue;
        if (found) |other| @compileError("tape: two variants of Input name the entry " ++ @typeName(Made) ++ ": " ++ other ++ " and " ++ name);
        found = name;
    }
    return found orelse @compileError("tape: no variant of Input names the entry " ++ @typeName(Made) ++ " (a line `<tag>: Args(<the entry>)` in tape.Input)");
}

/// The Host entries that return nothing and still stop a speculation, each
/// with why; a speculation records any other as made and goes on (`hostCall`).
/// The entries that answer stop by nature: the answer is the session's.
const keeps_stopping = [_]Host.Fn{
    // A shell's input: a device by the user's line (a far shell may feel
    // like ssh; core/echo.zig predicts its echo), and off the tape outside
    // a speculation.
    .pty_write,
    // Its host says into the core on every call that the shell started
    // and where (host_io.forkShell: acknowledgeShell, setCwd), and gives
    // the turn away: a rollback every time, nothing gained.
    .spawn,
    // Its host writes the core outside any record (exec.reapplyInitFile,
    // Plumb.saved, fs.writeSelf) besides `saved` or the failure, every call.
    .write_file,
    // Their hosts say done or failed into the core on every call
    // (setLastDump, dumpFailed; setMessage, reportError): a rollback every
    // time, nothing gained.
    .write_dump,
    .dump_themes,
    // The session's own: it execs itself after the step, carries a window
    // away, or lets its frontend go (writing `frontend` and `unattended`).
    .upgrade,
    .hand_over,
    .detach,
    // The loop's, never a step's.
    .wait_input,
    .present,
    .post_present,
    .poll_frame,
};

fn keepsStopping(comptime f: Host.Fn, args: Host.Args(f)) bool {
    // Turned on, its host loads the theme file into the core outside any
    // record (colors.loadThemeFile: custom_theme, theme_file_loaded);
    // turned off it only lets the file go.
    if (comptime f == .watch_theme) return args[1];
    return comptime std.mem.indexOfScalar(Host.Fn, &keeps_stopping, f) != null;
}

/// The entries a view's frontend makes on its own machine (P16).
fn forTheView(comptime f: Host.Fn) bool {
    return f == .set_clipboard or f == .read_clipboard or f == .open_link;
}

/// The one body of a call out to the host through the tape (`Tape.host`).
fn hostCall(t: *Tape, p: *const Pardes, comptime f: Host.Fn, args: Host.Args(f)) Host.Ret(f) {
    const R = Host.Ret(f);
    const name = @tagName(f);
    // A terminal's answers and what is typed at it from its output are the
    // authority's to write, never a replica's: off the tape on both sides
    // (a replica's replay of the step writes nothing, and checks nothing:
    // a write returns nothing a step reads).
    if (comptime std.mem.eql(u8, name, "pty_write")) if (!t.speculating) {
        if (!t.replay) _ = p.host.call(f, args);
        return;
    };
    if (t.replay) {
        // A replica that never draws is never watched: it asks no one.
        if (comptime std.mem.eql(u8, name, "watched")) if (t.skips_render) return false;
        if (!t.expectHost(@backingInt(f), name)) return std.mem.zeroes(R);
        var ret = t.last_ret;
        if (R == ?[]const u8) {
            // fg_name's answer is written into the caller's buffer.
            const text = (walk.decode(R, &ret, t.arena.allocator()) catch return null) orelse return null;
            const buf = args[args.len - 1];
            const n = @min(text.len, buf.len);
            @memcpy(buf[0..n], text[0..n]);
            return buf[0..n];
        }
        return walk.decode(R, &ret, t.arena.allocator()) catch std.mem.zeroes(R);
    }
    const id: u16 = @backingInt(f);
    if (t.speculating) {
        // Nobody watches a replica's step: its frames are its own, drawn
        // outside it (and the authority's host says so too, or the
        // comparison fails).
        if (comptime std.mem.eql(u8, name, "watched")) {
            const r = false;
            t.record(.host, u16, &id);
            t.record(.ret, R, &r);
            return r;
        }
        // Nothing to wait for: recorded as made, and the speculation goes
        // on. The session's unit records the same, or more where its host
        // wrote the core during the call (an input it made, a watched field
        // set), and the client rolls back.
        if (R == void and !keepsStopping(f, args)) {
            t.record(.host, u16, &id);
            t.record(.ret, void, &{});
            return;
        }
        t.poisoned = true;
        t.poisoned_by = name;
        return poisonOf(R);
    }
    // A client's yank, paste or link is its own frontend's, made on its own
    // machine from its view's record (Pardes.View.yanks): never the
    // session's, whose host makes them for a view no client draws.
    if (comptime forTheView(f)) if (p.undrawn & (@as(u8, 1) << @intCast(p.live)) != 0) {
        t.record(.host, u16, &id);
        t.record(.ret, void, &{});
        return;
    };
    t.record(.host, u16, &id);
    t.seeFields();
    const outer = !t.host_side;
    t.host_side = true;
    const r = p.host.call(f, args).?;
    t.host_side = !outer;
    t.noteWrites();
    t.record(.ret, R, &r);
    return r;
}

pub fn site(comptime s: Site, a: ?std.mem.Allocator, comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? {
    return (on orelse &none).site(s, a, f, args);
}

pub fn value(comptime s: Site, comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? {
    return (on orelse &none).value(s, f, args);
}

pub fn authority(comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? {
    return (on orelse &none).authority(f, args);
}

/// `value` whose answer's slices are `a`'s on a replay, as `site`'s are:
/// what its caller keeps (a kitty image's medium, Term.media).
pub fn valueIn(comptime s: Site, a: std.mem.Allocator, comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? {
    return (on orelse &none).call(s, a, f, args, false);
}

/// What `authority` was asked: `f` and its arguments as they are.
fn question(comptime f: anytype, args: anytype) u64 {
    var h = std.hash.Wyhash.init(@intFromPtr(&f));
    inline for (args) |a| h.update(std.mem.asBytes(&a));
    return h.final();
}

pub const Guess = struct { real_ns: i64, mono_ns: i64, gmtoff: i32 };

/// A record's bytes by hash kept for a replica's replays (`files`, the
/// tape's allocator's): the last eight, a rollback's units' and the next's.
pub fn keepFile(t: *Tape, b: Big) void {
    if (t.files.items.len == 8) t.gpa.free(t.files.orderedRemove(0).bytes);
    t.files.append(t.gpa, b) catch t.gpa.free(b.bytes);
}

/// A clock read of the session's, as a replica client guesses it: a file's
/// mtime (realtime seconds), a message's clock (monotonic ms), a message's
/// time of day (in the session's zone).
fn guessed(comptime R: type, g: Guess) R {
    if (R == u32) return std.math.cast(u32, @divFloor(g.real_ns, std.time.ns_per_s)) orelse 0;
    if (R == i64) return @divFloor(g.mono_ns, std.time.ns_per_ms);
    if (R == [8]u8) return pardes.Messages.Message.clockText(@divFloor(g.real_ns, std.time.ns_per_s), g.gmtoff);
    @compileError("tape: no guess of a clock read as " ++ @typeName(R));
}

/// The session's digest recorded now: at a step's end; at a unit's
/// (`unit_digests`, the replica stream's); or a batch of steps recorded
/// without one each (`no_digest`) checked once, at its end.
pub fn recordDigest(t: *Tape) void {
    const core = t.core orelse return;
    var parts: Parts = undefined;
    const whole = [1]u64{digestOf(core)};
    const d: []const u64 = if (t.whole_digest) &whole else digestParts(core, &parts);
    t.record(.digest, []const u64, &d);
}


/// A core made outside the tape (a replica client's, from a dump) is the
/// one it replays into.
pub fn adoptCore(t: *Tape, p: *Pardes) void {
    t.core = p;
    p.tape = t;
    t.replica = true;
}

/// A replica joins the session recorded on `t` (core/replica.zig): what the
/// host wrote in the core and which host it is are said again at the next
/// input, for a core made from a dump, which has neither.
pub fn resync(t: *Tape) void {
    t.seen = @splat(0);
    t.real = .{};
}

/// One host call, `f(args)`, made out of the turn (pardes.turn).
pub fn out(comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? {
    pardes.turn.yield();
    defer pardes.turn.back();
    return @call(.auto, f, args);
}

pub fn replaying() bool {
    return (on orelse &none).replaying();
}

/// A replica speculating (core/replica.zig): state only the authority
/// changes (a terminal's emulator) is left alone, and the input waits.
pub fn speculating() bool {
    return (on orelse &none).speculating;
}

pub fn stepping() bool {
    return (on orelse &none).stepping();
}

pub fn poison(why: []const u8) void {
    (on orelse &none).poison(why);
}

/// A replica's replay came to another state than the authority's (`why`):
/// it joins again. (No method: `Tape.diverged` is the field it writes.)
pub fn diverged(why: []const u8) void {
    if (on) |t| if (t.replay) t.diverge("{s}", .{why});
}

pub fn authorityOnly(comptime why: []const u8) bool {
    return (on orelse &none).authorityOnly(why);
}

/// A harmless stand-in for what a host call or a syscall would have
/// returned to a speculation that is thrown away once it returns: an
/// error where one can be said, else zeroes.
fn poisonOf(comptime R: type) R {
    return switch (@typeInfo(R)) {
        .error_union => |e| if (@typeInfo(e.error_set).error_set.error_names) |errors|
            (if (errors.len > 0) @field(e.error_set, errors[0]) else std.mem.zeroes(R))
        else
            error.Unexpected,
        .optional => null,
        .void => {},
        .@"union" => |u| inline for (u.field_names, u.field_types) |name, F| {
            if (comptime zeroable(F)) break @unionInit(R, name, std.mem.zeroes(F));
        } else @compileError("tape: no harmless value of " ++ @typeName(R)),
        else => std.mem.zeroes(R),
    };
}

fn zeroable(comptime T: type) bool {
    return switch (@typeInfo(T)) {
        .int, .float, .bool, .optional, .void => true,
        .pointer => |p| p.size == .slice,
        .array => |a| zeroable(a.child),
        .@"struct" => |s| blk: {
            for (s.field_types) |F| if (!zeroable(F)) break :blk false;
            break :blk true;
        },
        else => false,
    };
}

// ---- a replica's tapes in memory (core/replica.zig) ----

/// A tape recorded in memory: an authority's stream, taken unit by unit.
pub fn memory(gpa: std.mem.Allocator) Tape {
    return .{ .gpa = gpa, .replay = false, .scratch = .init(gpa), .arena = .init(gpa), .kept_arena = .init(gpa) };
}

/// What a tape in memory holds, given back (its core is gone already).
pub fn release(t: *Tape) void {
    for (t.big.items) |b| t.gpa.free(b.bytes);
    t.big.deinit(t.gpa);
    for (t.files.items) |b| t.gpa.free(b.bytes);
    t.files.deinit(t.gpa);
    t.answers.deinit(t.gpa);
    t.buf.deinit(t.gpa);
    t.scratch.deinit();
    t.arena.deinit();
    if (t.kept_arena) |*k| k.deinit();
}

/// The records of `bytes`, top-level inputs and all, applied to the
/// tape's core as the authority applied them, each digest checked; why
/// they diverged, or null.
pub fn replayUnit(t: *Tape, bytes: []const u8) ?[]const u8 {
    t.replica = true;
    t.replay = true;
    t.speculating = false;
    defer t.replay = false;
    t.in = .{ .bytes = bytes };
    while (t.diverged == null) {
        const kind = t.peek() orelse {
            // Bytes left that are no record's head: cut, or of no kind.
            if (t.in.at < t.in.bytes.len and t.next() == null and t.diverged == null) t.diverge("the tape ends inside a record's head", .{});
            break;
        };
        var rec = t.next() orelse break;
        switch (kind) {
            .input => {
                t.apply(&rec.payload);
                _ = t.arena.reset(.retain_capacity);
            },
            .set => t.applySet(&rec.payload),
            .digest => t.check(rec.payload.bytes),
            .host, .ret, .done, .blob => t.diverge("a {t} record at the top", .{kind}),
        }
    }
    return t.diverged;
}

/// Starts recording `t`'s core as a speculation: the host's watched
/// fields as they are now, nothing recorded yet.
pub fn beginSpeculation(t: *Tape) void {
    t.replay = false;
    t.speculating = true;
    t.poisoned = false;
    t.poisoned_by = "";
    t.no_digest = true;
    t.yields = pardes.turn.yields;
    t.buf.clearRetainingCapacity();
    t.seeFields();
}

/// Whether it stayed clean (no host call, no syscall, no authority state).
pub fn endSpeculation(t: *Tape) bool {
    t.stray(t.yields);
    t.speculating = false;
    t.no_digest = false;
    return !t.poisoned;
}

/// About what a unit of the session's holds at most (`Tape.cut`): a pump
/// takes up to 496 reads of 64 KiB, which as one unit could pass the 16 MiB
/// a message may be (replica.zig `lag_max`'s neighbour, wire's bound).
pub const unit_max = 1 << 20;

/// Whether two tapes record the same inputs, host calls and answers,
/// their digests aside.
pub fn sameRecords(a: []const u8, b: []const u8) bool {
    var x: walk.Reader = .{ .bytes = a };
    var y: walk.Reader = .{ .bytes = b };
    while (true) {
        const ra = nextRecord(&x);
        const rb = nextRecord(&y);
        if (ra == null or rb == null) return ra == null and rb == null;
        if (ra.?.kind != rb.?.kind or !std.mem.eql(u8, ra.?.payload, rb.?.payload)) return false;
    }
}

fn nextRecord(r: *walk.Reader) ?struct { kind: Kind, payload: []const u8 } {
    while (true) {
        const head = r.take(5) catch return null;
        const payload = r.take(std.mem.bytesToValue(u32, head[1..5])) catch return null;
        const kind = std.enums.fromInt(Kind, head[0]) orelse return null;
        if (kind != .digest) return .{ .kind = kind, .payload = payload };
    }
}

/// A tape's records, one a line (kind; an input's or a host call's name),
/// for a divergence's report.
pub fn describe(bytes: []const u8, w: *std.Io.Writer) void {
    var r: walk.Reader = .{ .bytes = bytes };
    var depth: usize = 0;
    while (true) {
        const head = r.take(5) catch return;
        const payload = r.take(std.mem.bytesToValue(u32, head[1..5])) catch return;
        const raw = std.enums.fromInt(Kind, head[0]) orelse return w.print("a record of no kind ({d})\n", .{head[0]}) catch {};
        // A record by hash, as the kind it stands for (its bytes are not here).
        const kind: Kind = if (raw == .blob and payload.len > 0) std.enums.fromInt(Kind, payload[0]) orelse .blob else raw;
        if (raw == .blob) {
            w.splatByteAll(' ', depth * 2) catch {};
            w.print("{t} by hash\n", .{kind}) catch {};
            if (kind == .done or kind == .ret) depth -|= 1;
            if (kind == .input or kind == .host) depth += 1;
            continue;
        }
        if (kind == .done or kind == .ret) depth -|= 1;
        w.splatByteAll(' ', depth * 2) catch {};
        switch (kind) {
            .input => {
                // Its tags read as the replay reads them: one of no kind is said, not cast.
                const Tag = std.meta.Tag(Input);
                const EventTag = std.meta.Tag(pardes.Event);
                const tag: ?Tag = if (payload.len < @sizeOf(Tag)) null else walk.enumFrom(Tag, payload[0..@sizeOf(Tag)]);
                w.print("input {s}", .{if (tag) |g| @tagName(g) else "of no kind"}) catch {};
                if (tag == .update and payload.len >= @sizeOf(Tag) + @sizeOf(EventTag)) {
                    const ev = walk.enumFrom(EventTag, payload[@sizeOf(Tag)..][0..@sizeOf(EventTag)]);
                    w.print(" {s}", .{if (ev) |e| @tagName(e) else "of no kind"}) catch {};
                }
                // A key's or a pointer's own words: which one a divergence
                // starts at.
                var room: [4096]u8 = undefined;
                var fixed: std.heap.FixedBufferAllocator = .init(&room);
                var in: walk.Reader = .{ .bytes = payload };
                if (tag == .update) if (walk.decode(Input, &in, fixed.allocator())) |input| switch (input.update.args[0]) {
                    .key => |k| w.print(" {any}", .{k}) catch {},
                    .mouse => |m| w.print(" {t} {t} {d},{d} body {any} tag {any}", .{ m.button, m.kind, m.col, m.row, m.body_hit != null, m.tag_hit != null }) catch {},
                    else => {},
                } else |_| {};
            },
            .host => {
                const id = Tape.hostId(payload);
                const of = if (id < host_fns.len) null else std.enums.fromInt(Site, id - host_fns.len);
                w.print("host {s}", .{if (id < host_fns.len) host_fns[id] else if (of) |s| @tagName(s) else "of no kind"}) catch {};
            },
            // Its bytes when traced: which field of equal length differs.
            .ret => if (payload.len <= 8 or libc.getenv("PARDES_REPLICA_TRACE") != null) w.print("ret {x}", .{payload}) catch {} else w.print("ret ({d} bytes)", .{payload.len}) catch {},
            else => w.print("{t} ({d} bytes)", .{ kind, payload.len }) catch {},
        }
        w.writeByte('\n') catch {};
        if (kind == .input or kind == .host) depth += 1;
    }
}

/// The digest a replica and its authority must agree on.
pub fn digestOf(p: *const Pardes) u64 {
    return walk.digest(Pardes, p);
}

/// PARDES_RECORD set: the tape a session is written to from its first
/// call, which whoever starts it hands in `Options.tape` (runtime/session.zig,
/// the Mac's start). `on` too, while the terminal's questions read it (P20).
pub fn fromEnv() ?*Tape {
    const prefix = std.mem.span(libc.getenv("PARDES_RECORD") orelse return null);
    if (prefix.len == 0) return null;
    const gpa = std.heap.c_allocator;
    var path_buf: [4096]u8 = undefined;
    const path = std.fmt.bufPrintSentinel(&path_buf, "{s}{d}.tape", .{ prefix, libc.getpid() }, 0) catch return null;
    const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644));
    if (fd < 0) return null;
    const t = gpa.create(Tape) catch return null;
    t.* = .{ .gpa = gpa, .replay = false, .fd = fd, .scratch = .init(gpa), .arena = .init(gpa), .every = libc.getenv("PARDES_RECORD_EVERY") != null };
    on = t;
    return t;
}

/// `PARDES_REPLAY=<tape>`: the tape replayed into three replicas, each
/// digest checked; 0 when none diverged.
pub fn replayMain(path: []const u8) u8 {
    const gpa = std.heap.c_allocator;
    // What a shell starts before its core (tui.zig's localSession).
    pardes.Term.start(gpa);
    pardes.syntax.start(gpa);
    const bytes = std.Io.Dir.cwd().readFileAlloc(std.Io.Threaded.global_single_threaded.io(), path, gpa, .unlimited) catch |err| {
        std.debug.print("replay: cannot read {s}: {t}\n", .{ path, err });
        return 2;
    };
    return if (replayBytes(gpa, bytes, path, libc.getenv("PARDES_REPLAY_DUMP") != null)) 0 else 1;
}

/// `bytes`, a tape named `path`, replayed into three replicas, each digest
/// checked, and with `dump` the session's dump at its end loaded to its
/// digest and dumped to its bytes again: true when none diverged. An
/// in-process session's tape too (test/session.zig's replayTape).
pub fn replayBytes(gpa: std.mem.Allocator, bytes: []const u8, path: []const u8, dump: bool) bool {
    const runs = [_]struct { name: []const u8, skips_render: bool }{
        .{ .name = "first", .skips_render = false },
        // The first replica's memory is still held: this one's lies elsewhere.
        .{ .name = "second", .skips_render = false },
        .{ .name = "skips-render", .skips_render = true },
    };
    var failed = false;
    for (runs) |run| {
        var t: Tape = .{ .gpa = gpa, .replay = true, .skips_render = run.skips_render, .scratch = .init(gpa), .arena = .init(gpa) };
        t.dump_check = std.mem.eql(u8, run.name, "first") and dump;
        on = &t;
        defer on = null;
        _ = replayUnit(&t, bytes);
        // A session killed mid-step leaves its last input cut short: the
        // end of the tape, not a divergence.
        if (t.diverged) |why| if (std.mem.startsWith(u8, why, "the tape ends")) {
            t.diverged = null;
        };
        // One killed (as the harnesses end theirs) has its end state here.
        if (t.dump_check and t.diverged == null) if (t.core) |core| t.dumpRoundTrip(core);
        if (t.diverged) |why| {
            failed = true;
            std.debug.print("replay {s}: {s} replica diverged after {d} digests: {s}\n", .{ path, run.name, t.digests, why });
        } else std.debug.print("replay {s}: {s} replica: {d} digests agree\n", .{ path, run.name, t.digests });
        if (t.dump_check and t.diverged == null) std.debug.print("replay {s}: {d} dumps loaded to their digests and dumped to their bytes again ({d} bytes)\n", .{ path, t.dumps, t.dump_bytes });
    }
    return !failed;
}

test "a syscall that is no site, made replaying, diverges the replay and poisons a speculation" {
    const gpa = std.testing.allocator;
    var t: Tape = .{ .gpa = gpa, .replay = true, .scratch = .init(gpa), .arena = .init(gpa) };
    defer t.scratch.deinit();
    defer t.arena.deinit();
    const since = pardes.turn.yields;
    t.stray(since);
    try std.testing.expect(t.diverged == null);
    pardes.turn.yield();
    pardes.turn.back();
    t.stray(since);
    try std.testing.expect(t.diverged != null);
    t.replay = false;
    t.speculating = true;
    t.yields = pardes.turn.yields;
    pardes.turn.yield();
    pardes.turn.back();
    try std.testing.expect(!endSpeculation(&t));
}

test "a replay that finds no answer where its core reads one diverges, and the read goes on harmless" {
    const gpa = std.testing.allocator;
    var t: Tape = .{ .gpa = gpa, .replay = true, .scratch = .init(gpa), .arena = .init(gpa) };
    defer t.scratch.deinit();
    defer t.arena.deinit();
    // The input's end where the core reads a value of the host's (a
    // window client's step that took a turn the session's had not, H9 of
    // 2026-10-30: it aborted the client).
    const bytes = [5]u8{ @backingInt(Kind.done), 0, 0, 0, 0 };
    t.in = .{ .bytes = &bytes };
    t.host_side = false;
    on = &t;
    defer on = null;
    const read = struct {
        fn f() bool {
            return true;
        }
    }.f;
    try std.testing.expect(!value(.denied, read, .{}));
    try std.testing.expect(t.diverged != null);
    try std.testing.expect(!value(.denied, read, .{}));
}

/// The functions of core/ that set `on` and leave a core's field be, each
/// with why the field is that tape already.
const sets_on_alone = [_]struct { []const u8, []const u8, []const u8 }{
    .{ "tape.zig", "fromEnv", "no core yet: its starter hands the tape in Options.tape" },
    .{ "tape.zig", "replayBytes", "its replay's core is made with this tape in its options (apply)" },
    .{ "replica.zig", "begin", "Stepping: the core stepped holds this tape already (adoptCore), which `enter` checks in a safe build" },
    .{ "replica.zig", "end", "Stepping: `on` put back as `begin` found it" },
};

/// The function a line of code declares, or null.
fn declares(code: []const u8) ?[]const u8 {
    var words = std.mem.tokenizeScalar(u8, code, ' ');
    while (words.next()) |w| {
        if (std.mem.eql(u8, w, "pub") or std.mem.eql(u8, w, "inline") or std.mem.eql(u8, w, "export")) continue;
        if (!std.mem.eql(u8, w, "fn")) return null;
        const rest = words.rest();
        return rest[0 .. std.mem.indexOfScalar(u8, rest, '(') orelse return null];
    }
    return null;
}

test "every place that sets the global tape aside sets the core's field aside: a function of core/ that writes `on` writes a core's `tape` too, or is listed with why" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var dir = try std.Io.Dir.cwd().openDir(io, "core", .{ .iterate = true });
    defer dir.close(io);
    var walker = try dir.walk(gpa);
    defer walker.deinit();
    var wrong: usize = 0;
    var seen: [sets_on_alone.len]bool = @splat(false);
    var writers: usize = 0;
    while (try walker.next(io)) |e| {
        if (e.kind != .file or !std.mem.endsWith(u8, e.basename, ".zig")) continue;
        const src = try e.dir.readFileAlloc(io, e.basename, gpa, .limited(16 << 20));
        defer gpa.free(src);
        const own = std.mem.eql(u8, e.path, "tape.zig");
        var name: []const u8 = "";
        var sets_on = false;
        var sets_field = false;
        var in_test = false;
        var lines = std.mem.splitScalar(u8, src, '\n');
        while (true) {
            const line = lines.next();
            const text = line orelse "";
            if (std.mem.startsWith(u8, text, "test ")) in_test = true;
            if (in_test) {
                if (std.mem.eql(u8, text, "}")) in_test = false;
                if (line != null) continue;
            }
            const code = std.mem.trim(u8, text[0 .. std.mem.indexOf(u8, text, "//") orelse text.len], " \t");
            const next = declares(code);
            if (next != null or line == null) {
                // The function before, judged.
                if (sets_on) {
                    writers += 1;
                    const listed = for (sets_on_alone, 0..) |a, i| {
                        if (std.mem.eql(u8, a[0], e.path) and std.mem.eql(u8, a[1], name)) {
                            seen[i] = true;
                            break true;
                        }
                    } else false;
                    if (!sets_field and !listed) {
                        wrong += 1;
                        std.debug.print("core/{s}: {s} sets tape.on and no core's `tape`: put the core's field aside with it (as dumpRoundTrip does), or list it in tape.zig's sets_on_alone with why\n", .{ e.path, name });
                    }
                }
                if (line == null) break;
                name = next.?;
                sets_on = false;
                sets_field = false;
            }
            // A core's field: `p.tape = `, never an options' (`opts.tape`).
            if (std.mem.indexOf(u8, code, ".tape = ")) |at| if (!std.mem.endsWith(u8, code[0..at], "opts")) {
                sets_field = true;
            };
            if (std.mem.indexOf(u8, code, "tape.on = ") != null) sets_on = true;
            if (own) if (std.mem.indexOf(u8, code, "on = ")) |at| if (at == 0 or code[at - 1] == ' ') {
                sets_on = true;
            };
        }
    }
    for (sets_on_alone, seen) |a, s| if (!s) {
        wrong += 1;
        std.debug.print("core/{s}: {s} is on sets_on_alone and sets no tape.on: delete its line\n", .{ a[0], a[1] });
    };
    try std.testing.expect(writers >= sets_on_alone.len + 3);
    try std.testing.expectEqual(@as(usize, 0), wrong);
}

/// The pump's own calls: a host with a clock and a frontend that shows
/// every frame; `more` has one function besides.
const Pumped = struct {
    ns: u64,
    fn now(ctx: ?*anyopaque) u64 {
        const h: *Pumped = @ptrCast(@alignCast(ctx.?));
        h.ns += std.time.ns_per_ms;
        return h.ns;
    }
    fn seen(_: ?*anyopaque) bool {
        return true;
    }
    fn present(_: ?*anyopaque, _: *const pardes.Surface) bool {
        return true;
    }
    fn poll(_: ?*anyopaque) void {}
    const one: VTable = .{ .now = now, .watched = seen, .present = present };
    const more: VTable = .{ .now = now, .watched = seen, .present = present, .poll_frame = poll };

    /// Recorded `bytes`: how many times which functions the host has was
    /// said, the last said, and the calls of each function.
    fn said(bytes: []const u8) struct { sets: usize = 0, mask: u64 = 0, calls: [host_fns.len]usize = @splat(0) } {
        var got: @typeInfo(@TypeOf(said)).@"fn".return_type.? = .{};
        var r: walk.Reader = .{ .bytes = bytes };
        while (nextRecord(&r)) |rec| {
            if (rec.kind == .set and rec.payload[0] == set_mask) {
                got.sets += 1;
                got.mask = std.mem.bytesToValue(u64, rec.payload[1..9]);
            }
            if (rec.kind == .host) {
                const id = std.mem.bytesToValue(u16, rec.payload[0..2]);
                if (id < host_fns.len) got.calls[id] += 1;
            }
        }
        return got;
    }
};

test "a core pumped twice with one host and once with another: which functions its host has is said at the first pump and the third, its clock, watch and present at each; a replica replays the three units to the same digest" {
    const gpa = std.testing.allocator;
    const R = pardes.replica;
    var first: Pumped = .{ .ns = 0 };
    var second: Pumped = .{ .ns = 1 << 40 };
    const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{ .ctx = &first, .vtable = &Pumped.one });
    defer a.deinit();
    const boot = Pumped.said(a.t.buf.items);
    try std.testing.expectEqual(Host.mask(.{ .vtable = &Pumped.one }), boot.mask);
    const r = try R.Replica.init(gpa, 1, try a.unit(0, 0));
    defer r.deinit();
    const hosts = [_]Host{ .{ .ctx = &first, .vtable = &Pumped.one }, .{ .ctx = &second, .vtable = &Pumped.more } };
    for (hosts, [_]usize{ 0, 1 }, 1..) |h, sets, seq| {
        a.host = h;
        a.apply(.{ .resize = .{ .cols = @intCast(80 + seq), .rows = 24 } });
        const got = Pumped.said(a.t.buf.items);
        try std.testing.expectEqual(sets, got.sets);
        if (sets > 0) try std.testing.expectEqual(h.mask(), got.mask);
        inline for (.{ .now, .watched, .present }) |f| try std.testing.expect(got.calls[@backingInt(@as(Host.Fn, f))] > 0);
        try std.testing.expectEqual(@intFromBool(h.has(.poll_frame)), got.calls[@backingInt(Host.Fn.poll_frame)]);
        a.seq += 1;
        r.confirm(try a.unit(0, a.seq));
    }
    r.settle();
    if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why});
    try std.testing.expect(r.diverged == null);
    try std.testing.expectEqual(R.digestOf(a), r.digest());
}

test "a client's frame drawn between its steps records nothing into its idle tape" {
    const gpa = std.testing.allocator;
    const p = try @import("ninep/harness.zig").withFile(gpa, "x\n");
    defer p.deinit();
    const bytes = try pardes.dump.dumpBytes(p);
    defer p.gpa.free(bytes);
    const r = try pardes.replica.Replica.initDump(gpa, 1, 0, bytes, .{ .cols = 80, .rows = 24 });
    defer r.deinit();
    // Between its steps: no tape on, its core's field its own tape, idle.
    try std.testing.expect(on == null and r.core().tape == &r.t and !r.t.stepping());
    const was = r.t.buf.items.len;
    _ = r.draw(.{ .ctx = null, .f = null });
    _ = r.draw(.{ .ctx = null, .f = null });
    try std.testing.expectEqual(was, r.t.buf.items.len);
    try std.testing.expect(!r.t.stepping() and r.t.host_side);
}