gent-daemon 0.1.1

Local daemon, storage and synchronization for Gent chat clusters.
Documentation
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
use super::*;
use crate::pairing::{self, Peer};
use std::os::unix::fs::PermissionsExt;

#[path = "administration_tests.rs"]
mod administration_tests;
#[path = "configuration_storage_tests.rs"]
mod configuration_storage_tests;
#[path = "direct_tests.rs"]
mod direct_tests;
#[path = "directory_compact_tests.rs"]
mod directory_compact_tests;
#[path = "directory_push_tests.rs"]
mod directory_push_tests;
#[path = "directory_tests.rs"]
mod directory_tests;
#[path = "group_administration_tests.rs"]
mod group_administration_tests;
#[path = "helper_tests.rs"]
mod helper_tests;
#[path = "hosted_tests.rs"]
mod hosted_tests;
#[path = "node_invite_tests.rs"]
mod node_invite_tests;
#[path = "owner_handoff_tests.rs"]
mod owner_handoff_tests;
#[path = "presence_tests.rs"]
mod presence_tests;
#[path = "queue_tests.rs"]
mod queue_tests;
#[path = "registration_tests.rs"]
mod registration_tests;
#[path = "retention_tests.rs"]
mod retention_tests;
#[path = "retries.rs"]
mod retries;
#[path = "wire_tests.rs"]
mod wire_tests;

#[path = "dashboard_tests.rs"]
mod dashboard_tests;
#[path = "ordinary_babysitter_tests.rs"]
mod ordinary_babysitter_tests;
struct OwnerPeer<'a>(&'a mut Store, String);
impl Peer for OwnerPeer<'_> {
    async fn call(&mut self, action: PairingOp) -> Result<Value> {
        self.0.execute(Request::Owner {
            credential: self.1.clone(),
            action: OwnerOp::Pair {
                cluster_id: self.0.config.cluster.id.clone(),
                action,
            },
        })
    }
}
struct Pair {
    homes: [tempfile::TempDir; 2],
    stores: [Store; 2],
    keys: [String; 2],
    agents: [String; 2],
}
impl Pair {
    fn relay_attach(&mut self) -> String {
        self.agent(
            0,
            AgentOp::RelayAttach {
                target: self.agents[1].clone(),
                request_id: Uuid::now_v7().to_string(),
            },
        )
        .unwrap()["attachment"]["id"]
            .as_str()
            .unwrap()
            .into()
    }
    async fn new() -> Self {
        Self::with_preexisting_chat(false).await
    }
    async fn with_preexisting_chat(before_join: bool) -> Self {
        let homes = std::array::from_fn(|_| {
            let home = tempfile::tempdir().unwrap();
            std::fs::set_permissions(home.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
            home
        });
        let mut cfg = config::initialize(homes[0].path(), "network-tests").unwrap();
        cfg.relay = Some(config::RelayConfig {
            endpoint: "https://relay.example".into(),
            credential_file: "relay.key".into(),
        });
        config::write_private(
            &homes[0].path().join("relay.key"),
            config::secret().as_bytes(),
        )
        .unwrap();
        config::save(homes[0].path(), &cfg).unwrap();
        crate::entitlements::grant_test(homes[0].path(), &cfg);
        let mut owner = Store::open(homes[0].path()).unwrap();
        let keys: [String; 2] = std::array::from_fn(|_| config::secret());
        if before_join {
            owner
                .execute(Request::Agent {
                    credential: keys[0].clone(),
                    action: AgentOp::Register {
                        name: "coordinator".into(),
                        provider: "test".into(),
                    },
                })
                .unwrap();
        }
        let credential = config::read_private(&homes[0].path().join("owner.key")).unwrap();
        pairing::join(
            homes[1].path(),
            pairing::Options {
                replace_node: None,
                cluster: &cfg.cluster.id,
                name: "joined",
                relay_endpoint: None,
            },
            &mut OwnerPeer(&mut owner, credential),
        )
        .await
        .unwrap();
        let joined = Store::open(homes[1].path()).unwrap();
        crate::entitlements::grant_test(homes[1].path(), &joined.config);
        let mut stores = [owner, joined];
        let agents = std::array::from_fn(|i| {
            stores[i]
                .execute(Request::Agent {
                    credential: keys[i].clone(),
                    action: AgentOp::Register {
                        name: format!("agent-{i}"),
                        provider: "test".into(),
                    },
                })
                .unwrap()["agent"]["id"]
                .as_str()
                .unwrap()
                .to_owned()
        });
        let mut pair = Self {
            homes,
            stores,
            keys,
            agents,
        };
        pair.pump();
        pair.policy(true);
        pair.pump();
        pair
    }
    fn agent(&mut self, i: usize, action: AgentOp) -> Result<Value> {
        self.stores[i].execute(Request::Agent {
            credential: self.keys[i].clone(),
            action,
        })
    }
    fn policy(&mut self, allow: bool) {
        let mut policy = Policy::default();
        if allow {
            for (a, b, p) in [
                (0, 1, Permission::Enumerate),
                (1, 0, Permission::Enumerate),
                (0, 1, Permission::Send),
                (1, 0, Permission::Receive),
            ] {
                policy.rules.push(Rule {
                    actor: Selector::Agent(self.agents[a].clone()),
                    peer: Selector::Agent(self.agents[b].clone()),
                    permission: p,
                    effect: Effect::Allow,
                });
            }
        }
        self.stores[0]
            .execute(Request::Owner {
                credential: config::read_private(&self.homes[0].path().join("owner.key")).unwrap(),
                action: OwnerOp::SetPolicy { policy },
            })
            .unwrap();
    }
    fn send(&mut self, files: Vec<FilePart>) -> Result<Value> {
        self.agent(
            0,
            AgentOp::Send {
                file_ids: vec![],
                recipient: self.agents[1].clone(),
                request_id: Uuid::now_v7().to_string(),
                text: "private work".into(),
                files,
            },
        )
    }
    fn group(&self) -> Vec<u8> {
        self.stores[0]
            .db
            .query_row("SELECT outgoing FROM network_links", [], |r| r.get(0))
            .unwrap()
    }
    fn pump(&mut self) {
        for _ in 0..100 {
            let mut progressed = false;
            for i in 0..2 {
                let streams = self.stores[i].sync_streams().unwrap();
                for stream in streams.into_iter().filter(|s| s.outgoing) {
                    let group = &stream.group;
                    let packet = if stream.configuration {
                        self.stores[i].sync_prepare(group).unwrap();
                        let next = self.stores[1 - i].sync_next(group).unwrap();
                        self.stores[i].sync_outgoing(group, next).unwrap()
                    } else {
                        self.stores[i].data_prepare(group).unwrap();
                        let next = self.stores[1 - i].data_next(group).unwrap();
                        self.stores[i].data_outgoing(group, next).unwrap()
                    };
                    if let Some(packet) = packet {
                        if stream.configuration {
                            self.stores[1 - i].sync_receive(&packet).unwrap();
                        } else {
                            self.stores[1 - i].data_receive(&packet).unwrap();
                        }
                        progressed = true;
                    }
                }
            }
            if !progressed {
                return;
            }
        }
        panic!("transport failed to drain");
    }
    fn reopen(&mut self, i: usize) {
        self.stores[i] = Store::open(self.homes[i].path()).unwrap();
    }
    fn retire_history(&mut self, i: usize) -> Value {
        // Advance request admission/retention only. MLS still uses the real
        // wall clock and its existing signed authority during these tests.
        self.stores[i]
            .db
            .execute("UPDATE request_clock SET floor=?1", [now() + 9 * 86400])
            .unwrap();
        self.stores[i]
            .execute(Request::Owner {
                credential: config::read_private(&self.homes[i].path().join("owner.key")).unwrap(),
                action: OwnerOp::HistoryClean { dry_run: false },
            })
            .unwrap()
    }
}

#[tokio::test]
async fn tcp_only_peer_watch_retries_exact_ciphertext_until_a_signed_receipt() {
    let mut pair = Pair::new().await;
    let group = pair.group();
    let baseline = pair.stores[1].transport_receipt(&group, false).unwrap();
    pair.stores[0]
        .transport_confirm(&group, false, Some(&baseline))
        .unwrap();
    let sent = pair.send(vec![]).unwrap();
    let stores = pair.stores.map(|s| Arc::new(std::sync::Mutex::new(s)));
    let stream = crate::sync::Stream {
        group,
        outgoing: true,
        configuration: false,
    };
    tokio::time::timeout(
        std::time::Duration::from_secs(30),
        crate::sync::exercise_peer_watch(&stores, stream),
    )
    .await
    .unwrap();
    let inbox = stores[1]
        .lock()
        .unwrap()
        .execute(Request::Agent {
            credential: pair.keys[1].clone(),
            action: AgentOp::Inbox,
        })
        .unwrap();
    assert_eq!(inbox.as_array().unwrap().len(), 1);
    assert_eq!(inbox[0]["id"], sent["message_id"]);
}

#[tokio::test]
async fn uploaded_packets_wait_offline_and_replay_until_the_reader_signs() {
    let mut pair = Pair::new().await;
    let group = pair.group();
    let baseline = pair.stores[1].transport_receipt(&group, false).unwrap();
    let first = baseline.sequence() + 1;
    pair.stores[0]
        .transport_confirm(&group, false, Some(&baseline))
        .unwrap();
    let streams = pair.stores[0].sync_streams().unwrap();
    let dirty = |store: &Store| {
        store
            .sync_pending_groups(&streams)
            .unwrap()
            .ready
            .contains(&group)
    };
    assert!(!dirty(&pair.stores[0]));
    let sent = pair.send(vec![]).unwrap();
    assert!(dirty(&pair.stores[0]));
    pair.stores[0].data_prepare(&group).unwrap();
    let packet = pair.stores[0]
        .data_outgoing(&group, first)
        .unwrap()
        .unwrap();
    let next = first + 1;
    // The relay stored the packet, but the sender did not get the PUT response.
    assert_eq!(
        pair.stores[0]
            .relay_upload_start(&group, next, first)
            .unwrap(),
        first
    );
    assert!(dirty(&pair.stores[0]));
    pair.stores[0].record_relay_upload(&group, next).unwrap();
    pair.reopen(0);
    assert!(!dirty(&pair.stores[0]));
    assert!(
        pair.stores[0]
            .relay_upload_start(&group, next + 1, first)
            .is_err()
    );
    assert!(!dirty(&pair.stores[0]));

    // Relay rollback makes the suffix runnable even across a sender restart.
    assert_eq!(
        pair.stores[0]
            .relay_upload_start(&group, first, first)
            .unwrap(),
        first
    );
    pair.reopen(0);
    assert!(dirty(&pair.stores[0]));
    let replay = pair.stores[0]
        .data_outgoing(&group, first)
        .unwrap()
        .unwrap();
    assert_eq!(replay.encode().unwrap(), packet.encode().unwrap());
    pair.stores[0].record_relay_upload(&group, next).unwrap();
    pair.stores[1].data_receive(&replay).unwrap();
    // Lose the receiver's checkpoint before the sender sees it.
    let lost = pair.stores[1].transport_receipt(&group, false).unwrap();
    assert_eq!(
        pair.stores[0]
            .transport_confirm(&group, false, None)
            .unwrap(),
        Some(baseline)
    );
    assert_eq!(
        pair.stores[0]
            .data_outgoing(&group, first)
            .unwrap()
            .unwrap()
            .encode()
            .unwrap(),
        replay.encode().unwrap()
    );
    pair.reopen(1);
    let recovered = pair.stores[1].transport_receipt(&group, false).unwrap();
    assert_eq!(recovered, lost);
    let (confirmed, advanced) = pair.stores[0]
        .transport_confirmation(&group, false, Some(&recovered))
        .unwrap();
    assert!(advanced);
    assert_eq!(confirmed.as_ref(), Some(&recovered));
    for cached in [Some(&recovered), None] {
        assert!(
            !pair.stores[0]
                .transport_confirmation(&group, false, cached)
                .unwrap()
                .1
        );
    }
    assert!(pair.stores[0].data_outgoing(&group, first).is_err());
    let inbox = pair.agent(1, AgentOp::Inbox).unwrap();
    assert_eq!(inbox.as_array().unwrap().len(), 1);
    assert_eq!(inbox[0]["id"], sent["message_id"]);
}

#[tokio::test]
async fn retired_partial_message_cancels_after_restart_even_if_fragment_cursor_rolled_back() {
    for failed_cursor in [false, true] {
        let mut pair = Pair::new().await;
        pair.send(vec![FilePart {
            name: "partial.png".into(),
            media_type: "image/png".into(),
            data_base64: STANDARD.encode(vec![7; 1024 * 1024]),
        }])
        .unwrap();
        let group = pair.group();
        let next = pair.stores[1].data_next(&group).unwrap();
        if failed_cursor {
            pair.stores[0].db.execute_batch("CREATE TRIGGER fail_offset BEFORE UPDATE OF offset ON network_events BEGIN SELECT RAISE(ABORT,'injected offset failure'); END;").unwrap();
            assert!(pair.stores[0].data_prepare(&group).is_err());
            pair.stores[0]
                .db
                .execute_batch("DROP TRIGGER fail_offset;")
                .unwrap();
        } else {
            pair.stores[0].data_prepare(&group).unwrap();
        }
        let packet = pair.stores[0].data_outgoing(&group, next).unwrap().unwrap();
        pair.stores[1].data_receive(&packet).unwrap();
        let receipt = pair.stores[1].transport_receipt(&group, false).unwrap();
        pair.stores[0]
            .transport_confirm(&group, false, Some(&receipt))
            .unwrap();
        let retained: bool = pair.stores[0]
            .db
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM stream_outbox WHERE group_id=?1 AND sequence=?2)",
                params![&group, next],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(retained, failed_cursor);
        assert_eq!(
            pair.stores[1]
                .db
                .query_row("SELECT COUNT(*) FROM network_partial", [], |r| r
                    .get::<_, u64>(0))
                .unwrap(),
            1
        );
        let cleaned = pair.retire_history(0);
        assert_eq!(cleaned["messages_removed"], 1);
        assert_eq!(cleaned["outbound_events_cancelled"], 1);
        let offset: usize = pair.stores[0].db.query_row("SELECT offset FROM network_events WHERE cancelled=1 AND length(body)=0 AND subject IS NULL",[],|r|r.get(0)).unwrap();
        assert_eq!(offset, if failed_cursor { 0 } else { FRAGMENT_BYTES });
        pair.reopen(0);
        pair.reopen(1);
        pair.stores[0].db.execute_batch("CREATE TRIGGER fail_cancel BEFORE DELETE ON network_events BEGIN SELECT RAISE(ABORT,'cancel cursor failure'); END;").unwrap();
        assert!(pair.stores[0].data_prepare(&group).is_err());
        let cancel = pair.stores[0]
            .data_outgoing(&group, next + 1)
            .unwrap()
            .unwrap();
        pair.stores[1].data_receive(&cancel).unwrap();
        let receipt = pair.stores[1].transport_receipt(&group, false).unwrap();
        pair.stores[0]
            .transport_confirm(&group, false, Some(&receipt))
            .unwrap();
        let pending_requests = |store: &Store| {
            store
                .db
                .query_row(
                    "SELECT COUNT(*) FROM transport_requests WHERE group_id=?1",
                    [&group],
                    |r| r.get::<_, u64>(0),
                )
                .unwrap()
        };
        assert_eq!(
            pending_requests(&pair.stores[0]),
            1 + u64::from(failed_cursor)
        );
        pair.stores[0]
            .db
            .execute_batch("DROP TRIGGER fail_cancel")
            .unwrap();
        pair.stores[0].data_prepare(&group).unwrap();
        assert_eq!(
            pending_requests(&pair.stores[0]),
            0,
            "confirmed requests survived cursor recovery (fragment rolled back: {failed_cursor})"
        );
        assert_eq!(
            pair.stores[0]
                .transport_confirm(&group, false, Some(&receipt))
                .unwrap(),
            Some(receipt)
        );
        pair.pump();
        assert_eq!(
            pair.stores[1]
                .db
                .query_row("SELECT COUNT(*) FROM network_partial", [], |r| r
                    .get::<_, u64>(0))
                .unwrap(),
            0
        );
        assert_eq!(
            pair.stores[0]
                .db
                .query_row("SELECT COUNT(*) FROM network_events", [], |r| r
                    .get::<_, u64>(0))
                .unwrap(),
            0
        );
        assert_eq!(pair.agent(1, AgentOp::Inbox).unwrap(), json!([]));
    }
}

#[tokio::test]
async fn late_authenticated_receipt_after_pruning_does_not_stall_stream() {
    let mut pair = Pair::new().await;
    let id = pair.send(vec![]).unwrap()["message_id"]
        .as_str()
        .unwrap()
        .to_owned();
    pair.pump();
    pair.agent(
        1,
        AgentOp::Ack {
            message_id: id.clone(),
        },
    )
    .unwrap();
    assert_eq!(pair.retire_history(0)["messages_removed"], 1);
    pair.reopen(0);
    pair.pump();
    assert_eq!(
        pair.stores[0]
            .db
            .query_row("SELECT COUNT(*) FROM messages", [], |r| r.get::<_, u64>(0))
            .unwrap(),
        0
    );
    assert_eq!(
        pair.stores[1]
            .db
            .query_row("SELECT COUNT(*) FROM network_events", [], |r| r
                .get::<_, u64>(0))
            .unwrap(),
        0
    );
}

#[tokio::test]
async fn pruned_remote_request_cannot_return_with_original_or_rewritten_timestamps() {
    let mut pair = Pair::new().await;
    pair.send(vec![]).unwrap();
    let body: Vec<u8> = pair.stores[0]
        .db
        .query_row(
            "SELECT body FROM network_events WHERE subject IS NOT NULL",
            [],
            |r| r.get(0),
        )
        .unwrap();
    pair.pump();
    assert_eq!(pair.retire_history(1)["messages_removed"], 1);
    let state = pair.stores[1].identity.state(&pair.stores[1].db).unwrap();
    let renewal = state
        .renew(
            &pair.stores[0]
                .identity
                .signing_owner(&pair.stores[0].db)
                .unwrap(),
            (now() + 9 * 86400) as u64,
        )
        .unwrap();
    pair.stores[1]
        .identity
        .apply(&pair.stores[1].db, renewal)
        .unwrap();
    pair.reopen(1);
    let peer = pair.stores[0].identity.node.id().to_owned();
    for rewrite in [false, true] {
        let mut record: Record = serde_json::from_slice(&body).unwrap();
        if rewrite {
            if let Event::Message { message, .. } = &mut record.event {
                message.created_at = now() + 9 * 86400;
                message.expires_at = message.created_at + EXCHANGE_TTL_SECONDS;
            } else {
                panic!("expected message");
            }
        }
        let store = &pair.stores[1];
        let tx = store.db.unchecked_transaction().unwrap();
        let mut session = store.network_session(&tx, store.identity.state(&tx).unwrap());
        session.import_event(&peer, record.event).unwrap();
        tx.commit().unwrap();
        assert_eq!(
            store
                .db
                .query_row("SELECT COUNT(*) FROM messages", [], |r| r.get::<_, u64>(0))
                .unwrap(),
            0
        );
    }
    assert_eq!(
        pair.stores[1]
            .db
            .query_row("SELECT COUNT(*) FROM network_events", [], |r| r
                .get::<_, u64>(0))
            .unwrap(),
        0
    );
}

#[tokio::test]
async fn remote_relay_replies_cannot_strip_or_substitute_authenticated_turn_context() {
    let mut pair = Pair::new().await;
    let attachment = pair.relay_attach();
    let turn = pair
        .agent(
            0,
            AgentOp::RelaySend {
                file_ids: vec![],
                attachment_id: attachment,
                request_id: Uuid::now_v7().to_string(),
                text: "original turn".into(),
                files: vec![],
            },
        )
        .unwrap()["turn_id"]
        .as_str()
        .unwrap()
        .to_owned();
    pair.pump();
    let target = &pair.stores[1];
    let target_session =
        target.network_session(&target.db, target.identity.state(&target.db).unwrap());
    let registration = target_session.registration(&pair.agents[1]).unwrap();
    let root = target_session.message(&turn).unwrap();
    for attack in 0..4 {
        let store = &pair.stores[0];
        let tx = store.db.unchecked_transaction().unwrap();
        let mut session = store.network_session(&tx, store.identity.state(&tx).unwrap());
        let request = Uuid::now_v7().to_string();
        let mut message = root.clone();
        message.id = messages::message_id(&pair.agents[1], &request).unwrap();
        message.sender.clone_from(&root.recipient);
        message.recipient.clone_from(&root.sender);
        message.reply_to = Some(root.id.clone());
        message.relay.as_mut().unwrap().kind = RelayMessageKind::Complete;
        match attack {
            0 => message.relay = None,
            1 => message.relay.as_mut().unwrap().attachment_id = Uuid::new_v4().to_string(),
            2 => message.relay.as_mut().unwrap().turn_id = Uuid::new_v4().to_string(),
            _ => message.reply_to = Some(Uuid::new_v4().to_string()),
        }
        assert!(
            session
                .import_event(
                    pair.stores[1].identity.node.id(),
                    Event::Message {
                        attachments: vec![],
                        sender: Box::new(registration.clone()),
                        request_id: request,
                        message,
                    }
                )
                .is_err()
        );
        tx.rollback().unwrap();
    }
    let response = AgentOp::RelayRespond {
        file_ids: vec![],
        turn_id: turn.clone(),
        request_id: Uuid::now_v7().to_string(),
        text: "verified reply".into(),
        files: vec![],
        outcome: RelayResponseKind::Complete,
    };
    pair.agent(1, response).unwrap();
    pair.pump();
    let status = pair
        .agent(
            0,
            AgentOp::RelayTurnStatus {
                turn_id: turn,
                after_message_id: None,
            },
        )
        .unwrap();
    assert_eq!(status["state"], "completed");
    assert_eq!(status["responses"].as_array().unwrap().len(), 1);
}

#[tokio::test]
async fn crossed_cancellation_and_completion_do_not_reopen_or_lose_a_remote_turn() {
    let mut pair = Pair::new().await;
    let attachment = pair.relay_attach();
    let send = AgentOp::RelaySend {
        file_ids: vec![],
        attachment_id: attachment.clone(),
        request_id: Uuid::now_v7().to_string(),
        text: "work".into(),
        files: vec![],
    };
    let turn = pair.agent(0, send.clone()).unwrap()["turn_id"]
        .as_str()
        .unwrap()
        .to_owned();
    pair.pump();
    pair.agent(
        0,
        AgentOp::RelayDetach {
            attachment_id: attachment,
        },
    )
    .unwrap();
    let cancel = AgentOp::RelayCancel {
        turn_id: turn.clone(),
        request_id: Uuid::now_v7().to_string(),
    };
    pair.agent(0, cancel.clone()).unwrap();
    let response = AgentOp::RelayRespond {
        file_ids: vec![],
        turn_id: turn.clone(),
        request_id: Uuid::now_v7().to_string(),
        text: "already finished".into(),
        files: vec![],
        outcome: RelayResponseKind::Complete,
    };
    pair.stores[1].db.execute_batch("CREATE TRIGGER fail_relay_outbox BEFORE INSERT ON network_events BEGIN SELECT RAISE(ABORT,'injected'); END;").unwrap();
    assert!(pair.agent(1, response.clone()).is_err());
    assert_eq!(
        pair.agent(1, AgentOp::RelayNext).unwrap()["request"]["id"],
        turn
    );
    pair.stores[1]
        .db
        .execute_batch("DROP TRIGGER fail_relay_outbox;")
        .unwrap();
    pair.agent(1, response.clone()).unwrap();
    pair.reopen(0);
    pair.reopen(1);
    pair.pump();
    let status = pair
        .agent(
            0,
            AgentOp::RelayTurnStatus {
                turn_id: turn.clone(),
                after_message_id: None,
            },
        )
        .unwrap();
    assert_eq!(status["state"], "completed");
    assert_eq!(status["cancel_requested"], true);
    assert_eq!(status["responses"][0]["relay"]["kind"], "complete");
    assert_eq!(pair.agent(1, AgentOp::RelayNext).unwrap(), Value::Null);
    assert_eq!(pair.agent(0, send).unwrap()["duplicate"], true);
    assert_eq!(pair.agent(0, cancel).unwrap()["duplicate"], true);
    assert_eq!(pair.agent(1, response).unwrap()["duplicate"], true);
    pair.pump();
    assert_eq!(pair.agent(1, AgentOp::Inbox).unwrap(), json!([]));
}

#[tokio::test]
async fn permission_denial_blocks_relay_turns_before_encryption_and_before_target_work() {
    let mut pair = Pair::new().await;
    let attachment = pair.relay_attach();
    let first = pair
        .agent(
            0,
            AgentOp::RelaySend {
                file_ids: vec![],
                attachment_id: attachment.clone(),
                request_id: Uuid::now_v7().to_string(),
                text: "accepted earlier".into(),
                files: vec![],
            },
        )
        .unwrap()["turn_id"]
        .as_str()
        .unwrap()
        .to_owned();
    pair.pump();
    assert_eq!(
        pair.agent(1, AgentOp::RelayNext).unwrap()["request"]["id"],
        first
    );
    let queued = pair
        .agent(
            0,
            AgentOp::RelaySend {
                file_ids: vec![],
                attachment_id: attachment,
                request_id: Uuid::now_v7().to_string(),
                text: "must not encrypt".into(),
                files: vec![],
            },
        )
        .unwrap()["turn_id"]
        .as_str()
        .unwrap()
        .to_owned();
    let mut policy = pair.stores[0].config.policy.clone();
    policy.rules.push(Rule {
        actor: Selector::Agent(pair.agents[0].clone()),
        peer: Selector::Agent(pair.agents[1].clone()),
        permission: Permission::Send,
        effect: Effect::Deny,
    });
    pair.stores[0]
        .execute(Request::Owner {
            credential: config::read_private(&pair.homes[0].path().join("owner.key")).unwrap(),
            action: OwnerOp::Configure {
                request_id: Uuid::new_v4().to_string(),
                edit: ConfigurationEdit::Policy { policy },
            },
        })
        .unwrap();
    pair.pump();
    assert_eq!(pair.agent(1, AgentOp::RelayNext).unwrap(), Value::Null);
    assert_eq!(pair.agent(1, AgentOp::Inbox).unwrap(), json!([]));
    assert_eq!(
        pair.agent(
            0,
            AgentOp::RelayTurnStatus {
                turn_id: queued.clone(),
                after_message_id: None
            }
        )
        .unwrap()["state"],
        "revoked"
    );
    assert!(
        !pair.stores[1]
            .db
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM messages WHERE id=?1)",
                [queued],
                |r| r.get::<_, bool>(0)
            )
            .unwrap()
    );
}

#[tokio::test]
async fn failed_enqueue_rolls_back_message_and_retry_preserves_ciphertext_after_cursor_failure() {
    let mut pair = Pair::new().await;
    pair.stores[0].db.execute_batch("CREATE TRIGGER fail_enqueue BEFORE INSERT ON network_events BEGIN SELECT RAISE(ABORT,'disk failure'); END;").unwrap();
    assert!(pair.send(vec![]).is_err());
    let count: usize = pair.stores[0]
        .db
        .query_row("SELECT COUNT(*) FROM messages", [], |r| r.get(0))
        .unwrap();
    assert_eq!(count, 0);
    pair.stores[0]
        .db
        .execute_batch("DROP TRIGGER fail_enqueue;")
        .unwrap();
    pair.send(vec![]).unwrap();
    pair.stores[0].db.execute_batch("CREATE TRIGGER fail_cursor BEFORE DELETE ON network_events BEGIN SELECT RAISE(ABORT,'disk failure'); END;").unwrap();
    let group = pair.group();
    let next = pair.stores[1].data_next(&group).unwrap();
    assert!(pair.stores[0].data_prepare(&group).is_err());
    let packet = pair.stores[0].data_outgoing(&group, next).unwrap().unwrap();
    pair.reopen(0);
    pair.stores[0]
        .db
        .execute_batch("DROP TRIGGER fail_cursor;")
        .unwrap();
    pair.stores[0].data_prepare(&group).unwrap();
    assert_eq!(
        packet.encode().unwrap(),
        pair.stores[0]
            .data_outgoing(&group, next)
            .unwrap()
            .unwrap()
            .encode()
            .unwrap()
    );
    pair.pump();
    assert_eq!(
        pair.agent(1, AgentOp::Inbox)
            .unwrap()
            .as_array()
            .unwrap()
            .len(),
        1
    );
    assert!(
        pair.stores[0]
            .data_outgoing(&group, next + 1)
            .unwrap()
            .is_none()
    );
}

#[tokio::test]
async fn joined_runtime_clears_conservative_legacy_join_pins_without_changing_authority() {
    let mut pair = Pair::new().await;
    let before = pair.stores[1]
        .identity
        .state(&pair.stores[1].db)
        .unwrap()
        .checkpoint()
        .clone();
    pair.stores[1]
        .db
        .execute_batch("DROP TABLE authority_join_pins; PRAGMA user_version=5;")
        .unwrap();
    pair.reopen(1);
    assert_eq!(
        pair.stores[1]
            .db
            .query_row("SELECT COUNT(*) FROM authority_join_pins", [], |r| r
                .get::<_, u64>(0))
            .unwrap(),
        0
    );
    assert_eq!(
        pair.stores[1]
            .identity
            .state(&pair.stores[1].db)
            .unwrap()
            .checkpoint(),
        &before
    );
}

#[tokio::test]
async fn queued_message_uses_retained_authority_digest_after_full_history_compaction() {
    let mut pair = Pair::new().await;
    let sent = pair.send(vec![]).unwrap();
    let revision = pair.stores[0]
        .identity
        .state(&pair.stores[0].db)
        .unwrap()
        .checkpoint()
        .revision;
    let edit = Uuid::new_v4().to_string();
    pair.owner(
        1,
        OwnerOp::Configure {
            request_id: edit.clone(),
            edit: ConfigurationEdit::RenameNode {
                name: "delayed-result".into(),
            },
        },
    )
    .unwrap();
    let request_group: Vec<u8> = pair.stores[1]
        .db
        .query_row("SELECT outgoing FROM network_links", [], |r| r.get(0))
        .unwrap();
    let next = pair.stores[0].data_next(&request_group).unwrap();
    pair.stores[1].data_prepare(&request_group).unwrap();
    let request = pair.stores[1]
        .data_outgoing(&request_group, next)
        .unwrap()
        .unwrap();
    pair.stores[0].data_receive(&request).unwrap();
    for _ in 0..80 {
        let store = &pair.stores[0];
        let tx = store.db.unchecked_transaction().unwrap();
        let state = store.identity.state(&tx).unwrap();
        store
            .identity
            .apply(
                &tx,
                state
                    .renew(&store.identity.signing_owner(&tx).unwrap(), now() as u64)
                    .unwrap(),
            )
            .unwrap();
        tx.commit().unwrap();
    }
    // Deliver only configuration, leaving the old queued message untouched.
    let streams = pair.stores[0].sync_streams().unwrap();
    for entry in streams
        .into_iter()
        .filter(|s| s.outgoing && s.configuration)
    {
        loop {
            pair.stores[0].sync_prepare(&entry.group).unwrap();
            let next = pair.stores[1].sync_next(&entry.group).unwrap();
            let Some(packet) = pair.stores[0].sync_outgoing(&entry.group, next).unwrap() else {
                break;
            };
            pair.stores[1].sync_receive(&packet).unwrap();
        }
    }
    for store in &pair.stores {
        while {
            let tx = store.db.unchecked_transaction().unwrap();
            let (n, _) = encrypted::history::clean(&tx, false).unwrap();
            tx.commit().unwrap();
            n > 0
        } {}
    }
    assert!(
        !pair.stores[1]
            .db
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM authority_history WHERE revision=?1)",
                [revision],
                |r| r.get::<_, bool>(0)
            )
            .unwrap()
    );
    pair.reopen(1);
    pair.pump();
    assert_eq!(
        pair.owner(
            1,
            OwnerOp::ConfigurationRequests {
                request_id: Some(edit)
            }
        )
        .unwrap()["state"],
        "applied"
    );
    assert_eq!(
        pair.agent(1, AgentOp::Inbox).unwrap()[0]["id"],
        sent["message_id"]
    );
}

#[tokio::test]
async fn checkpoints_preserve_pending_send_cursors_and_do_not_acknowledge_agents() {
    let mut pair = Pair::new().await;
    let sent = pair.send(vec![]).unwrap();
    let group = pair.group();
    let next = pair.stores[1].data_next(&group).unwrap();
    pair.stores[0].db.execute_batch("CREATE TRIGGER fail_cursor BEFORE DELETE ON network_events BEGIN SELECT RAISE(ABORT,'injected cursor'); END;").unwrap();
    assert!(pair.stores[0].data_prepare(&group).is_err());
    let packet = pair.stores[0].data_outgoing(&group, next).unwrap().unwrap();
    pair.stores[1].data_receive(&packet).unwrap();
    let receipt = pair.stores[1].transport_receipt(&group, false).unwrap();
    pair.stores[0]
        .transport_confirm(&group, false, Some(&receipt))
        .unwrap();
    let retained: Vec<u8> = pair.stores[0]
        .db
        .query_row(
            "SELECT packet FROM stream_outbox WHERE group_id=?1 AND sequence=?2",
            params![&group, next],
            |r| r.get(0),
        )
        .unwrap();
    assert_eq!(retained, packet.encode().unwrap());
    // Storage confirmation is independent of Gent's agent-level inbox/ack.
    assert_eq!(
        pair.agent(1, AgentOp::Inbox)
            .unwrap()
            .as_array()
            .unwrap()
            .len(),
        1
    );
    pair.reopen(0);
    pair.stores[0]
        .db
        .execute_batch("DROP TRIGGER fail_cursor")
        .unwrap();
    pair.stores[0].data_prepare(&group).unwrap();
    pair.stores[0]
        .transport_confirm(&group, false, Some(&receipt))
        .unwrap();
    let retained: Option<Vec<u8>> = pair.stores[0]
        .db
        .query_row(
            "SELECT packet FROM stream_outbox WHERE group_id=?1 AND sequence=?2",
            params![&group, next],
            |r| r.get(0),
        )
        .optional()
        .unwrap();
    assert!(retained.is_none());
    pair.pump();
    assert_eq!(
        pair.agent(1, AgentOp::Inbox).unwrap()[0]["id"],
        sent["message_id"]
    );
}

#[tokio::test]
async fn failed_recipient_import_keeps_decrypted_record_until_transaction_can_commit() {
    let mut pair = Pair::new().await;
    pair.send(vec![]).unwrap();
    let group = pair.group();
    let next = pair.stores[1].data_next(&group).unwrap();
    pair.stores[0].data_prepare(&group).unwrap();
    let packet = pair.stores[0].data_outgoing(&group, next).unwrap().unwrap();
    pair.stores[1].db.execute_batch("CREATE TRIGGER fail_import BEFORE INSERT ON messages BEGIN SELECT RAISE(ABORT,'disk failure'); END;").unwrap();
    assert!(pair.stores[1].data_receive(&packet).is_err());
    assert_eq!(pair.agent(1, AgentOp::Inbox).unwrap(), json!([]));
    pair.reopen(1);
    pair.stores[1]
        .db
        .execute_batch("DROP TRIGGER fail_import;")
        .unwrap();
    assert_eq!(pair.stores[1].data_next(&group).unwrap(), next + 1);
    pair.stores[1].data_receive(&packet).unwrap();
    assert_eq!(
        pair.agent(1, AgentOp::Inbox)
            .unwrap()
            .as_array()
            .unwrap()
            .len(),
        1
    );
}

#[tokio::test]
async fn partially_encrypted_file_is_cancelled_and_next_allowed_message_can_progress() {
    let mut pair = Pair::new().await;
    let cancelled = pair
        .send(vec![FilePart {
            name: "screenshot.png".into(),
            media_type: "image/png".into(),
            data_base64: STANDARD.encode(vec![7; 1024 * 1024]),
        }])
        .unwrap();
    let group = pair.group();
    let next = pair.stores[1].data_next(&group).unwrap();
    pair.stores[0].data_prepare(&group).unwrap();
    let packet = pair.stores[0].data_outgoing(&group, next).unwrap().unwrap();
    pair.stores[1].data_receive(&packet).unwrap();
    assert_eq!(pair.agent(1, AgentOp::Inbox).unwrap(), json!([]));
    pair.policy(false);
    pair.pump();
    let pending: usize = pair.stores[1]
        .db
        .query_row("SELECT COUNT(*) FROM network_partial", [], |r| r.get(0))
        .unwrap();
    assert_eq!(pending, 0);
    pair.reopen(0);
    pair.policy(true);
    pair.pump();
    assert_eq!(
        pair.agent(
            0,
            AgentOp::MessageStatus {
                message_id: cancelled["message_id"].as_str().unwrap().into(),
            }
        )
        .unwrap()["state"],
        "revoked"
    );
    let sent = pair.send(vec![]).unwrap();
    pair.pump();
    let inbox = pair.agent(1, AgentOp::Inbox).unwrap();
    assert_eq!(inbox.as_array().unwrap().len(), 1);
    assert_eq!(inbox[0]["id"], sent["message_id"]);
}

#[tokio::test]
async fn enrolled_peer_cannot_claim_unknown_foreign_agent_or_forge_reply_or_receipt() {
    let mut pair = Pair::new().await;
    let store = &pair.stores[0];
    let tx = store.db.unchecked_transaction().unwrap();
    let state = store.identity.state(&tx).unwrap();
    let session = store.network_session(&tx, state);
    let peer = pair.stores[1].identity.node.id();
    let mut registration = pair.stores[1]
        .network_session(
            &pair.stores[1].db,
            pair.stores[1].identity.state(&pair.stores[1].db).unwrap(),
        )
        .registration(&pair.agents[1])
        .unwrap();
    registration.id =
        gent_crypto::agent_id(store.identity.node.id(), registration.nonce.unwrap()).unwrap();
    assert!(session.import_registration(peer, &registration).is_err());
    tx.rollback().unwrap();

    let sent = pair.send(vec![]).unwrap();
    pair.pump();
    let store = &pair.stores[1];
    let tx = store.db.unchecked_transaction().unwrap();
    let mut session = store.network_session(&tx, store.identity.state(&tx).unwrap());
    let mut message = session
        .message(sent["message_id"].as_str().unwrap())
        .unwrap();
    assert!(
        session
            .import_event(
                pair.stores[0].identity.node.id(),
                Event::Receipt {
                    message_id: message.id.clone(),
                    delivered: true
                }
            )
            .is_err()
    );
    let sender = pair.stores[0]
        .network_session(
            &pair.stores[0].db,
            pair.stores[0].identity.state(&pair.stores[0].db).unwrap(),
        )
        .registration(&pair.agents[0])
        .unwrap();
    let request = Uuid::now_v7().to_string();
    message.id = messages::message_id(&sender.id, &request).unwrap();
    message.reply_to = Some(Uuid::new_v4().to_string());
    assert!(
        session
            .import_event(
                pair.stores[0].identity.node.id(),
                Event::Message {
                    attachments: vec![],
                    sender: Box::new(sender),
                    request_id: request,
                    message
                }
            )
            .is_err()
    );
    tx.rollback().unwrap();
    assert_eq!(
        pair.agent(1, AgentOp::Inbox)
            .unwrap()
            .as_array()
            .unwrap()
            .len(),
        1
    );
}

#[tokio::test]
async fn message_waits_for_missing_configuration_before_delivery() {
    let mut pair = Pair::new().await;
    pair.policy(false);
    pair.pump();
    pair.policy(true);
    let sent = pair.send(vec![]).unwrap();
    let group = pair.group();
    let next = pair.stores[1].data_next(&group).unwrap();
    pair.stores[0].data_prepare(&group).unwrap();
    let packet = pair.stores[0].data_outgoing(&group, next).unwrap().unwrap();
    pair.stores[1].data_receive(&packet).unwrap();
    assert_eq!(pair.agent(1, AgentOp::Inbox).unwrap(), json!([]));
    pair.reopen(1);
    pair.pump();
    assert_eq!(
        pair.agent(1, AgentOp::Inbox).unwrap()[0]["id"],
        sent["message_id"]
    );
}

#[tokio::test]
async fn remote_exchange_budget_stays_bounded_when_both_nodes_queue_replies() {
    let mut pair = Pair::new().await;
    let initial = pair.send(vec![]).unwrap();
    pair.pump();
    let reply = |message: &Value| AgentOp::Reply {
        file_ids: vec![],
        message_id: message["message_id"].as_str().unwrap().into(),
        request_id: Uuid::now_v7().to_string(),
        text: "response".into(),
        files: vec![],
    };
    let first_reply = pair.agent(1, reply(&initial)).unwrap();
    pair.pump();
    for _ in 0..15 {
        pair.agent(0, reply(&first_reply)).unwrap();
        pair.agent(1, reply(&initial)).unwrap();
    }
    assert!(pair.agent(0, reply(&first_reply)).is_err());
    assert!(pair.agent(1, reply(&initial)).is_err());
    pair.pump();
    for store in &pair.stores {
        let count: u32 = store
            .db
            .query_row(
                "SELECT count FROM exchanges WHERE id=?1",
                [initial["exchange_id"].as_str().unwrap()],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(count, MAX_EXCHANGE_MESSAGES);
    }
}

impl Pair {
    fn owner(&mut self, i: usize, action: OwnerOp) -> Result<Value> {
        self.stores[i].execute(Request::Owner {
            credential: config::read_private(&self.homes[i].path().join("owner.key"))?,
            action,
        })
    }
}

#[tokio::test]
async fn member_rename_from_joined_admin_checks_writer_grant_and_pins_target() -> Result<()> {
    let mut pair = Pair::new().await;
    let target = pair.stores[0].identity.node.id().to_owned();
    let caller = pair.stores[1].identity.node.id().to_owned();
    let id = Uuid::new_v4().to_string();
    let rename = |request_id: &str, node_id: &str, name: &str| OwnerOp::Configure {
        request_id: request_id.into(),
        edit: ConfigurationEdit::RenameMember {
            node_id: node_id.into(),
            name: name.into(),
        },
    };
    let action = rename(&id, &target, "Studio");
    let queued = pair.owner(1, action.clone())?;
    assert_eq!(queued["state"], "queued");
    assert_eq!(queued["node_id"], target);
    // Keep the request across restart without placing an unsupported record on the stream.
    assert!(
        !pair.stores[1]
            .db
            .prepare("SELECT 1 FROM configuration_routes WHERE id=?1")?
            .exists([&id])?
    );
    pair.reopen(1);
    directory_push_tests::negotiate(&mut pair);
    pair.stores[1].reconcile_configuration()?;
    pair.pump();
    let applied = pair.owner(1, action)?;
    assert_eq!(applied["state"], "applied");
    assert_eq!(applied["name"], "Studio");
    assert_eq!(config::load(pair.homes[0].path())?.node.name, "Studio");
    assert_eq!(config::load(pair.homes[1].path())?.node.name, "joined");
    for i in 0..2 {
        let nodes = pair.owner(i, OwnerOp::Nodes)?;
        assert!(
            nodes
                .as_array()
                .unwrap()
                .iter()
                .any(|n| n["id"] == target && n["name"] == "Studio")
        );
    }
    assert!(pair.owner(1, rename(&id, &caller, "Studio")).is_err());

    let pending = rename(&Uuid::new_v4().to_string(), &target, "Forbidden");
    assert_eq!(pair.owner(1, pending.clone())?["state"], "queued");
    pair.owner(
        0,
        OwnerOp::DelegateConfiguration {
            node_id: caller,
            allow: false,
        },
    )?;
    pair.pump();
    assert_eq!(pair.owner(1, pending)?["state"], "rejected");
    assert!(
        pair.owner(1, rename(&Uuid::new_v4().to_string(), &target, "Forbidden"))
            .is_err()
    );
    assert_eq!(config::load(pair.homes[0].path())?.node.name, "Studio");
    Ok(())
}

#[tokio::test]
async fn configuration_proposal_revision_and_result_recover_atomically_after_storage_failures() {
    let mut pair = Pair::new().await;
    let id = Uuid::new_v4().to_string();
    let action = OwnerOp::Configure {
        request_id: id.clone(),
        edit: ConfigurationEdit::RenameNode {
            name: "renamed-remotely".into(),
        },
    };
    pair.stores[1].db.execute_batch("CREATE TRIGGER fail_proposal BEFORE INSERT ON network_events BEGIN SELECT RAISE(ABORT,'disk failure'); END;").unwrap();
    assert!(pair.owner(1, action.clone()).is_err());
    assert!(
        pair.owner(
            1,
            OwnerOp::ConfigurationRequests {
                request_id: Some(id.clone())
            }
        )
        .is_err()
    );
    pair.stores[1]
        .db
        .execute_batch("DROP TRIGGER fail_proposal;")
        .unwrap();
    assert_eq!(pair.owner(1, action.clone()).unwrap()["state"], "queued");
    let before = pair.stores[0]
        .identity
        .state(&pair.stores[0].db)
        .unwrap()
        .checkpoint()
        .clone();
    pair.stores[0].db.execute_batch("CREATE TRIGGER fail_result BEFORE INSERT ON configuration_edits BEGIN SELECT RAISE(ABORT,'disk failure'); END;").unwrap();
    let group: Vec<u8> = pair.stores[1]
        .db
        .query_row("SELECT outgoing FROM network_links", [], |r| r.get(0))
        .unwrap();
    let next = pair.stores[0].data_next(&group).unwrap();
    pair.stores[1].data_prepare(&group).unwrap();
    let packet = pair.stores[1].data_outgoing(&group, next).unwrap().unwrap();
    assert!(pair.stores[0].data_receive(&packet).is_err());
    assert_eq!(
        pair.stores[0]
            .identity
            .state(&pair.stores[0].db)
            .unwrap()
            .checkpoint(),
        &before
    );
    pair.reopen(0);
    pair.stores[0]
        .db
        .execute_batch("DROP TRIGGER fail_result;")
        .unwrap();
    pair.stores[0].data_next(&group).unwrap();
    pair.pump();
    let result = pair
        .owner(
            1,
            OwnerOp::ConfigurationRequests {
                request_id: Some(id.clone()),
            },
        )
        .unwrap();
    assert_eq!(result["revision"], before.revision + 1);
    assert_eq!(
        pair.owner(1, action).unwrap()["revision"],
        result["revision"]
    );
    assert_eq!(
        config::load(pair.homes[1].path()).unwrap().node.name,
        "renamed-remotely"
    );
    assert_eq!(
        pair.stores[0]
            .identity
            .state(&pair.stores[0].db)
            .unwrap()
            .checkpoint()
            .revision,
        before.revision + 1
    );
}

#[tokio::test]
async fn configuration_results_require_the_original_writer_request_and_verified_revision() {
    let mut pair = Pair::new().await;
    let id = Uuid::new_v4();
    let edit = ConfigurationEdit::RenameNode {
        name: "pending".into(),
    };
    pair.owner(
        1,
        OwnerOp::Configure {
            request_id: id.to_string(),
            edit,
        },
    )
    .unwrap();
    let store = &pair.stores[1];
    let tx = store.db.unchecked_transaction().unwrap();
    let state = store.identity.state(&tx).unwrap();
    let fingerprint: String = tx
        .query_row(
            "SELECT fingerprint FROM configuration_edits WHERE origin=?1 AND id=?2",
            params![store.identity.node.id(), id.to_string()],
            |r| r.get(0),
        )
        .unwrap();
    let session = store.network_session(&tx, state.clone());
    let mut checkpoint = state.checkpoint().clone();
    checkpoint.state_hash[0] ^= 1;
    assert!(
        session
            .import_configuration_result(
                pair.stores[0].identity.node.id(),
                id,
                &fingerprint,
                crate::messages::EditResult::Applied { checkpoint }
            )
            .is_err()
    );
    assert!(
        session
            .import_configuration_result(
                store.identity.node.id(),
                id,
                &fingerprint,
                crate::messages::EditResult::Rejected {
                    reason: "forged".into()
                }
            )
            .is_err()
    );
    assert!(
        session
            .import_configuration_result(
                pair.stores[0].identity.node.id(),
                id,
                "wrong request digest",
                crate::messages::EditResult::Rejected {
                    reason: "forged".into()
                }
            )
            .is_err()
    );
    tx.rollback().unwrap();
    assert_eq!(
        pair.owner(
            1,
            OwnerOp::ConfigurationRequests {
                request_id: Some(id.to_string())
            }
        )
        .unwrap()["state"],
        "queued"
    );
    pair.pump();
    assert_eq!(
        pair.owner(
            1,
            OwnerOp::ConfigurationRequests {
                request_id: Some(id.to_string())
            }
        )
        .unwrap()["state"],
        "applied"
    );
}

fn send_attachment(pair: &mut Pair, bytes: &[u8]) -> Value {
    let paths = pair.agent(0, AgentOp::FilePaths).unwrap();
    std::fs::write(
        std::path::Path::new(paths["import_directory"].as_str().unwrap()).join("native.bin"),
        bytes,
    )
    .unwrap();
    let imported = pair
        .agent(
            0,
            AgentOp::FileImport {
                request_id: Uuid::now_v7().to_string(),
                name: "native.bin".into(),
                media_type: "application/octet-stream".into(),
            },
        )
        .unwrap();
    pair.agent(
        0,
        AgentOp::Send {
            recipient: pair.agents[1].clone(),
            request_id: Uuid::now_v7().to_string(),
            text: "file review".into(),
            files: vec![],
            file_ids: vec![imported["file"]["id"].as_str().unwrap().into()],
        },
    )
    .unwrap()
}

#[tokio::test]
async fn attachment_grants_reject_substitution_and_downloads_resume_with_current_authority() {
    let mut pair = Pair::new().await;
    directory_push_tests::negotiate(&mut pair);
    let bytes = vec![0x91; gent_crypto::files::CHUNK_BYTES * 2 + 7];
    let sent = send_attachment(&mut pair, &bytes);
    let message_id = sent["message_id"].as_str().unwrap();
    let (body, compress): (Vec<u8>, bool) = pair.stores[0]
        .db
        .query_row(
            "SELECT body,compress FROM network_events WHERE subject=?1",
            [message_id],
            |r| Ok((r.get(0)?, r.get(1)?)),
        )
        .unwrap();
    let record: Record = serde_json::from_slice(&body).unwrap();
    assert_eq!(record.version, messages::wire::CURRENT);
    assert!(!compress, "file grants must use the uncompressed envelope");
    let id = match &record.event {
        Event::Message { message, .. } => message.attachments[0].id.clone(),
        _ => panic!(),
    };
    // Message publication waits for all object chunks; a restart preserves the job.
    pair.pump();
    assert!(
        pair.agent(1, AgentOp::Inbox)
            .unwrap()
            .as_array()
            .unwrap()
            .is_empty()
    );
    pair.reopen(0);
    let job = pair.stores[0].file_transfer(&id).unwrap().unwrap();
    assert_eq!(job.missing, vec![0, 1, 2]);
    let group = pair.group();
    let baseline = pair.stores[1].transport_receipt(&group, false).unwrap();
    pair.stores[0]
        .transport_confirm(&group, false, Some(&baseline))
        .unwrap();
    let streams = pair.stores[0].sync_streams().unwrap();
    let ready = |s: &Store| {
        s.sync_pending_groups(&streams)
            .unwrap()
            .ready
            .contains(&group)
    };
    assert!(!ready(&pair.stores[0]));
    let chunks: Vec<_> = (0..3)
        .map(|i| pair.stores[0].file_upload(&id, i).unwrap())
        .collect();
    pair.stores[0].file_uploaded(&id, &[0, 1]).unwrap();
    assert!(!ready(&pair.stores[0]));
    // A cancelled record can still publish its cancellation before the file finishes.
    let tx = pair.stores[0].db.unchecked_transaction().unwrap();
    tx.execute(
        "UPDATE network_events SET cancelled=1 WHERE subject=?1",
        [message_id],
    )
    .unwrap();
    assert!(ready(&pair.stores[0]));
    tx.rollback().unwrap();
    pair.stores[0].file_uploaded(&id, &[0, 1, 2]).unwrap();
    assert!(ready(&pair.stores[0]));
    // A forged grant for the same visible descriptor must be rejected, including
    // duplicate messages after the original object has expired/reaped.
    for attack in 0..4 {
        let mut wire: serde_json::Value = serde_json::from_slice(&body).unwrap();
        match attack {
            0 => {
                wire["event"]["attachments"] = json!([]);
            }
            1 => {
                wire["event"]["attachments"][0]["manifest"]["expires_at"] = json!(1);
            }
            2 => {
                wire["event"]["message"]["attachments"][0]["name"] = json!("substituted.bin");
            }
            _ => {
                wire["event"]["attachments"][0]["manifest"]["chunks"][0]["bytes"] = json!(17);
            }
        }
        let forged: Record = serde_json::from_value(wire).unwrap();
        let store = &pair.stores[1];
        let tx = store.db.unchecked_transaction().unwrap();
        let mut session = store.network_session(&tx, store.identity.state(&tx).unwrap());
        assert!(
            session
                .import_event(pair.stores[0].identity.node.id(), forged.event)
                .is_err()
        );
        tx.rollback().unwrap();
    }
    pair.pump();
    let status = pair
        .agent(
            1,
            AgentOp::FileStatus {
                file_id: id.clone(),
            },
        )
        .unwrap();
    assert_eq!(status["state"], "pending");
    pair.stores[1].file_received(&id, 0, &chunks[0]).unwrap();
    pair.reopen(1);
    assert_eq!(
        pair.stores[1].file_transfer(&id).unwrap().unwrap().missing,
        vec![1, 2]
    );
    let mut bad = chunks[1].clone();
    bad[0] ^= 1;
    assert!(pair.stores[1].file_received(&id, 1, &bad).is_err());
    pair.stores[1].file_received(&id, 1, &chunks[1]).unwrap();
    pair.stores[1].file_received(&id, 2, &chunks[2]).unwrap();
    let exported = pair
        .agent(
            1,
            AgentOp::FileExport {
                file_id: id.clone(),
            },
        )
        .unwrap();
    assert_eq!(
        std::fs::read(exported["path"].as_str().unwrap()).unwrap(),
        bytes
    );
    let mut wire: serde_json::Value = serde_json::from_slice(&body).unwrap();
    let grant = &mut wire["event"]["attachments"][0]["grant"];
    let mut secret: serde_json::Value =
        serde_json::from_slice(&STANDARD.decode(grant.as_str().unwrap()).unwrap()).unwrap();
    secret["key"][0] = json!(secret["key"][0].as_u64().unwrap() ^ 1);
    *grant = json!(STANDARD.encode(serde_json::to_vec(&secret).unwrap()));
    for reaped in [false, true] {
        let store = &pair.stores[1];
        let tx = store.db.unchecked_transaction().unwrap();
        if reaped {
            tx.execute("DELETE FROM file_objects WHERE id=?1", [&id])
                .unwrap();
        }
        let mut session = store.network_session(&tx, store.identity.state(&tx).unwrap());
        let changed: Record = serde_json::from_value(wire.clone()).unwrap();
        assert!(
            session
                .import_event(pair.stores[0].identity.node.id(), changed.event)
                .unwrap_err()
                .to_string()
                .contains("conflicting remote file grants")
        );
        tx.rollback().unwrap();
    }
    pair.policy(false);
    pair.pump();
    assert!(pair.stores[0].file_upload(&id, 0).is_err());
    assert!(pair.stores[1].file_transfer(&id).is_err());
    assert!(pair.stores[1].file_received(&id, 0, &chunks[0]).is_err());
    assert!(pair.agent(1, AgentOp::FileExport { file_id: id }).is_err());
}