khive-runtime 0.16.0

Composable Service API: entity/note CRUD, graph traversal, hybrid search, curation.
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
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
#![cfg(unix)]
use super::*;

#[cfg(test)]
pub(super) static DEFAULT_RENDEZVOUS_PREBIND_HOOK: std::sync::Mutex<
    Option<Box<dyn FnOnce() + Send>>,
> = std::sync::Mutex::new(None);

/// Run the daemon: bind the socket, warm in the background, serve request
/// frames until SIGTERM/SIGINT.
///
/// Fatally acquires its own startup lock, which only protects
/// cleanup→pid-claim→bind — `dispatcher` has already run migrations and
/// applied pack schema plans while constructing itself, unguarded. Production
/// boot must go through [`run_daemon_with_boot_guard`] instead, which extends
/// the same lock back over construction. This entry point is for callers
/// (and tests) that build the dispatcher and start serving as one atomic
/// step with no separate boot-guard window to protect.
#[cfg(unix)]
pub async fn run_daemon<D: DaemonDispatch>(dispatcher: D) -> anyhow::Result<()> {
    let boot_guard = Some(acquire_daemon_boot_guard()?);
    run_daemon_with_boot_guard_inner(
        dispatcher,
        boot_guard,
        false,
        DaemonOptions::default(),
        |_| DaemonStartupReport::default(),
    )
    .await
}

/// Run a real daemon server for an in-process multi-launch test.
///
/// Separate production daemon candidates have distinct PIDs, so the boot fence
/// recognizes a live incumbent and makes later candidates exit. Parallel
/// test launchers share one OS process and therefore one PID; this explicit
/// fault-injection entry point preserves the production fence semantics by
/// allowing a live same-PID incumbent to win. Ordinary daemon startup
/// continues to treat a same-PID rendezvous as stale, protecting PID-reuse
/// cleanup behavior.
///
/// A losing candidate still follows the ordinary daemon-exit path and cancels
/// the process-wide component shutdown token. Callers must therefore use a
/// component-free dispatcher; this seam validates socket/PID ownership, not
/// multi-candidate component lifecycle.
#[cfg(all(unix, any(test, feature = "fault-injection")))]
#[doc(hidden)]
pub async fn run_daemon_in_process_test<D: DaemonDispatch>(dispatcher: D) -> anyhow::Result<()> {
    let boot_guard = Some(acquire_daemon_boot_guard()?);
    run_daemon_with_boot_guard_inner(
        dispatcher,
        boot_guard,
        true,
        DaemonOptions::default(),
        |_| DaemonStartupReport::default(),
    )
    .await
}

#[cfg(unix)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum RendezvousPathRole<'a> {
    Socket,
    PidFile,
    Store(&'a std::path::Path),
}

#[cfg(unix)]
impl RendezvousPathRole<'_> {
    pub(super) fn refusal(
        self,
        rendezvous: std::fmt::Arguments<'_>,
        store: std::fmt::Arguments<'_>,
    ) -> anyhow::Error {
        match self {
            Self::Store(db_path) => anyhow::anyhow!(
                "refusing to open events database {}: {store}. Check the offending directory's \
                 ownership and permissions (remove group/other write access), or move the store \
                 to a location trusted end to end. Only the first offending component is \
                 reported; further untrusted ancestors or components may remain.",
                db_path.display()
            ),
            Self::Socket | Self::PidFile => anyhow::anyhow!("{rendezvous}"),
        }
    }

    pub(super) fn env_name(self) -> &'static str {
        match self {
            Self::Socket => SOCKET_PATH_ENV,
            Self::PidFile => PID_PATH_ENV,
            Self::Store(_) => "events database",
        }
    }

    pub(super) fn directory_name(self) -> &'static str {
        match self {
            Self::Socket => "socket directory",
            Self::PidFile => "PID-file directory",
            Self::Store(_) => "store directory",
        }
    }

    pub(super) fn path_name(self) -> &'static str {
        match self {
            Self::Socket => "socket path",
            Self::PidFile => "PID-file path",
            Self::Store(_) => "store path",
        }
    }

    pub(super) fn path_component_name(self) -> &'static str {
        match self {
            Self::Socket => "socket-path",
            Self::PidFile => "PID-file-path",
            Self::Store(_) => "store-path",
        }
    }
}

/// Vet the socket's parent directory, re-permissioning it only when it is the
/// directory khive owns by convention.
///
/// `KHIVE_SOCKET` takes an arbitrary path, and the previous unconditional
/// chmod-0700 of its parent was wrong in both directions: pointed at a shared
/// parent like `/tmp` it either failed outright for an ordinary user, or —
/// worse — succeeded when privileged and stripped access for every other
/// process on the machine. A directory we did not create is never modified.
///
/// What the directory must actually prevent is a *takeover of the socket
/// path*: the connection gate is the 0600 socket plus the accept-time
/// peer-uid check, but both defend the daemon's own socket — neither helps
/// once another local user can put *their* listener at the path clients
/// resolve. There are two ways a shared directory allows that, and the
/// sticky bit closes neither: a writer can *pre-bind* the predictable path
/// before this daemon starts (the sticky bit restricts unlinking, not
/// creating), and the directory's *owner* can unlink and rebind even in a
/// 1777 directory (sticky exempts the directory owner). So a caller-chosen
/// directory is served only when it is trusted end to end: owned by this
/// daemon's euid or root, and not writable by group or other at all. The
/// umask-default 0755 stays acceptable; shared sticky directories like
/// `/tmp` do not.
#[cfg(unix)]
pub(crate) fn ensure_socket_dir_is_trusted(parent: &std::path::Path) -> anyhow::Result<()> {
    // SAFETY: `geteuid` is always successful and takes no arguments.
    let daemon_euid = unsafe { libc::geteuid() } as u32;
    let default_rendezvous = super::lifecycle::path_override(SOCKET_PATH_ENV).is_none()
        && super::lifecycle::path_override(PID_PATH_ENV).is_none();
    ensure_rendezvous_dir_is_trusted(
        parent,
        RendezvousPathRole::Socket,
        daemon_euid,
        default_rendezvous,
    )
}

/// Apply the existing directory trust and default-root repair rules to an events store.
#[cfg(unix)]
pub(crate) fn ensure_store_dir_is_trusted(
    parent: &std::path::Path,
    db_path: &std::path::Path,
) -> anyhow::Result<()> {
    // SAFETY: `geteuid` is always successful and takes no arguments.
    let daemon_euid = unsafe { libc::geteuid() } as u32;
    ensure_rendezvous_dir_is_trusted(
        parent,
        RendezvousPathRole::Store(db_path),
        daemon_euid,
        true,
    )
}

/// Vet the parent directory of a PID file before reading, locking, or writing
/// it. The file's lock only protects the inode currently named by its path;
/// every directory component must therefore be as swap-resistant as the
/// socket rendezvous.
#[cfg(unix)]
pub fn ensure_pid_file_dir_is_trusted(pid_file: &std::path::Path) -> anyhow::Result<()> {
    let parent = pid_file
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or_else(|| std::path::Path::new("."));
    // SAFETY: `geteuid` is always successful and takes no arguments.
    let daemon_euid = unsafe { libc::geteuid() } as u32;
    ensure_rendezvous_dir_is_trusted(parent, RendezvousPathRole::PidFile, daemon_euid, false)
}

/// Secure the default rendezvous directory during a mutating recovery attempt.
/// Read-only daemon probes must use `ensure_pid_file_dir_is_trusted` instead.
#[cfg(unix)]
pub fn prepare_default_rendezvous_for_recovery() -> anyhow::Result<()> {
    let explicit_rendezvous = super::lifecycle::path_override(PID_PATH_ENV).is_some()
        || super::lifecycle::path_override(SOCKET_PATH_ENV).is_some();
    let parent = khive_dir();
    let mut marker_lock = supervisor_marker_path().into_os_string();
    marker_lock.push(".lock");
    let locks = [
        lock_path(),
        recoverer_lock_path(),
        std::path::PathBuf::from(marker_lock),
    ];
    for lock in &locks {
        if lock.file_name().is_none() {
            anyhow::bail!(
                "refusing recovery lock {} without a filename",
                lock.display()
            );
        }
    }
    if explicit_rendezvous
        && !locks
            .iter()
            .any(|lock| lock.parent() == Some(parent.as_path()))
    {
        return Ok(());
    }
    if !prepare_default_rendezvous_directory()? {
        return Ok(());
    }
    // SAFETY: `geteuid` is always successful and takes no arguments.
    let daemon_euid = unsafe { libc::geteuid() } as u32;
    for lock in locks {
        if lock.parent() == Some(parent.as_path()) {
            tighten_owned_recovery_lock(&lock, daemon_euid)?;
        }
    }
    Ok(())
}

/// Prepare the default parent only when this particular recovery lock needs it.
#[cfg(unix)]
pub fn prepare_default_rendezvous_for_lock(lock: &std::path::Path) -> anyhow::Result<()> {
    let parent = khive_dir();
    if lock.parent() != Some(parent.as_path()) {
        return Ok(());
    }
    if lock.file_name().is_none() {
        anyhow::bail!(
            "refusing recovery lock {} without a filename",
            lock.display()
        );
    }
    if prepare_default_rendezvous_directory()? {
        // SAFETY: `geteuid` is always successful and takes no arguments.
        let daemon_euid = unsafe { libc::geteuid() } as u32;
        tighten_owned_recovery_lock(lock, daemon_euid)?;
    }
    Ok(())
}

/// Prepare the default directory without touching any lock in it.
#[cfg(unix)]
pub(super) fn prepare_default_rendezvous_directory() -> anyhow::Result<bool> {
    use std::os::unix::fs::DirBuilderExt;

    let explicit_rendezvous = super::lifecycle::path_override(PID_PATH_ENV).is_some()
        || super::lifecycle::path_override(SOCKET_PATH_ENV).is_some();
    let parent = khive_dir();
    // An explicitly selected rendezvous is not ours to repair. If a default
    // lock still needs this parent, create it only when absent; an existing
    // parent must already pass the normal trust checks at the checked opener.
    if explicit_rendezvous {
        if let Ok(metadata) = std::fs::symlink_metadata(&parent) {
            use std::os::unix::fs::MetadataExt;
            // SAFETY: geteuid takes no arguments and always succeeds.
            let uid = unsafe { libc::geteuid() } as u32;
            if metadata.is_dir() && metadata.uid() == uid && metadata.mode() & 0o7777 == 0 {
                anyhow::bail!("cannot access default lock directory {} (mode 0000); verify ownership and set this directory to mode 0700 by hand, then retry", parent.display());
            }
            return Ok(false);
        }
    }
    // SAFETY: `geteuid` is always successful and takes no arguments.
    let daemon_euid = unsafe { libc::geteuid() } as u32;
    let ancestors = parent
        .parent()
        .filter(|path| !path.as_os_str().is_empty())
        .unwrap_or_else(|| std::path::Path::new("."));
    ensure_rendezvous_path_is_swap_resistant(ancestors, daemon_euid, RendezvousPathRole::PidFile)?;
    let mut builder = std::fs::DirBuilder::new();
    builder.mode(0o700);
    let created = match builder.create(&parent) {
        Ok(()) => true,
        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists && explicit_rendezvous => {
            return Ok(false)
        }
        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => false,
        Err(error) => {
            return Err(anyhow::anyhow!(
                "refusing to inspect default rendezvous directory {}: {error}",
                parent.display()
            ))
        }
    };
    repair_default_dir_with_recovery_guidance(&parent, daemon_euid, created)?;

    Ok(true)
}

#[cfg(unix)]
fn repair_default_dir_with_recovery_guidance(
    parent: &std::path::Path,
    daemon_euid: u32,
    created: bool,
) -> anyhow::Result<()> {
    use std::os::unix::fs::MetadataExt;
    repair_owned_default_dir(parent, RendezvousPathRole::PidFile, daemon_euid).map_err(|error| {
        let owned_inaccessible = std::fs::symlink_metadata(parent).is_ok_and(|metadata| {
            metadata.is_dir() && metadata.uid() == daemon_euid && metadata.mode() & 0o7777 == 0
        });
        if owned_inaccessible {
            let context = if created { "newly created" } else { "existing" };
            anyhow::anyhow!(
                "failed to prepare {context} default directory {}: {error:#}; verify ownership and set this directory to mode 0700 by hand, then retry",
                parent.display()
            )
        } else {
            error
        }
    })
}

#[cfg(unix)]
fn tighten_owned_recovery_lock(lock: &std::path::Path, daemon_euid: u32) -> anyhow::Result<()> {
    tighten_owned_recovery_lock_with_hook(lock, daemon_euid, || {})
}

#[cfg(unix)]
fn tighten_owned_recovery_lock_with_hook(
    lock: &std::path::Path,
    daemon_euid: u32,
    after_validation: impl FnOnce(),
) -> anyhow::Result<()> {
    use std::os::unix::fs::MetadataExt;

    let observed = match std::fs::symlink_metadata(lock) {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(error) => anyhow::bail!("cannot inspect recovery lock {}: {error}", lock.display()),
    };
    let mode = observed.permissions().mode() & 0o7777;
    if !observed.is_file() || observed.uid() != daemon_euid || observed.nlink() != 1 {
        anyhow::bail!(
            "refusing recovery lock {}: expected a single-link regular file owned by uid {daemon_euid}, found uid {} and mode {mode:04o}",
            lock.display(),
            observed.uid()
        );
    }
    super::locks::checked_open_lock_with_hooks(lock, false, false, true, || {}, after_validation)?
        .ok_or_else(|| anyhow::anyhow!("recovery lock {} disappeared", lock.display()))?;
    Ok(())
}

#[cfg(unix)]
fn repair_owned_default_dir(
    parent: &std::path::Path,
    role: RendezvousPathRole<'_>,
    daemon_euid: u32,
) -> anyhow::Result<()> {
    repair_owned_default_dir_with_hooks(parent, role, daemon_euid, || {}, || {})
}

#[cfg(unix)]
fn repair_owned_default_dir_with_hooks(
    parent: &std::path::Path,
    role: RendezvousPathRole<'_>,
    daemon_euid: u32,
    before_open: impl FnOnce(),
    after_validation: impl FnOnce(),
) -> anyhow::Result<()> {
    use std::os::unix::fs::{MetadataExt, OpenOptionsExt};

    let ancestors = parent
        .parent()
        .filter(|path| !path.as_os_str().is_empty())
        .unwrap_or_else(|| std::path::Path::new("."));
    ensure_rendezvous_path_is_swap_resistant(ancestors, daemon_euid, role)?;

    let observed = std::fs::symlink_metadata(parent).map_err(|error| {
        anyhow::anyhow!(
            "refusing to stat default rendezvous directory {}: {error}",
            parent.display()
        )
    })?;
    let observed_mode = observed.permissions().mode() & 0o7777;
    if !observed.is_dir() {
        anyhow::bail!(
            "refusing non-directory or symlink default rendezvous path {} (mode {observed_mode:04o})",
            parent.display()
        );
    }
    before_open();
    // The metadata check and permission change operate on this exact opened
    // directory; opening the leaf with NOFOLLOW refuses a symlink.
    let directory = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW)
        .open(parent)
        .map_err(|error| anyhow::anyhow!(
            "refusing to open default rendezvous directory {} (observed mode {observed_mode:04o}) without following a symlink: {error}",
            parent.display()
        ))?;
    let metadata = directory.metadata().map_err(|error| {
        anyhow::anyhow!(
            "refusing to stat default rendezvous directory {}: {error}",
            parent.display()
        )
    })?;
    if observed.dev() != metadata.dev() || observed.ino() != metadata.ino() {
        anyhow::bail!(
            "default rendezvous directory {} changed before it was opened",
            parent.display()
        );
    }
    let mode = metadata.permissions().mode() & 0o7777;
    if !metadata.is_dir() || metadata.uid() != daemon_euid {
        anyhow::bail!(
            "refusing to repair default rendezvous directory {}: owner uid {}, mode {mode:04o}; expected uid {daemon_euid}",
            parent.display(),
            metadata.uid()
        );
    }
    after_validation();
    let latest = directory.metadata().map_err(|error| {
        anyhow::anyhow!(
            "refusing to restat default rendezvous directory {}: {error}",
            parent.display()
        )
    })?;
    let latest_mode = latest.permissions().mode() & 0o7777;
    if !latest.is_dir() || latest.uid() != daemon_euid {
        anyhow::bail!(
            "refusing to repair default rendezvous directory {}: owner uid {}, mode {latest_mode:04o}; expected uid {daemon_euid}",
            parent.display(),
            latest.uid()
        );
    }
    // The daemon creates its lock, pid and socket files here, so the owner keeps
    // full access and every other bit is cleared.
    let tightened = 0o700;
    if tightened != latest_mode {
        directory
            .set_permissions(std::fs::Permissions::from_mode(tightened))
            .map_err(|error| anyhow::anyhow!(
                "refusing to tighten default rendezvous directory {} from mode {latest_mode:04o}: {error}",
                parent.display()
            ))?;
    }
    let current = std::fs::symlink_metadata(parent).map_err(|error| {
        anyhow::anyhow!(
            "refusing changed default rendezvous directory {}: {error}",
            parent.display()
        )
    })?;
    if !current.is_dir() || metadata.dev() != current.dev() || metadata.ino() != current.ino() {
        anyhow::bail!(
            "default rendezvous directory {} changed during repair",
            parent.display()
        );
    }
    ensure_rendezvous_path_is_swap_resistant(parent, daemon_euid, role)
}

#[cfg(unix)]
pub(super) fn ensure_rendezvous_dir_is_trusted(
    parent: &std::path::Path,
    role: RendezvousPathRole<'_>,
    daemon_euid: u32,
    repair_owned_default: bool,
) -> anyhow::Result<()> {
    let env_name = role.env_name();
    let directory_name = role.directory_name();

    if repair_owned_default && parent == khive_dir() {
        return repair_owned_default_dir(parent, role, daemon_euid).map_err(|error| {
            role.refusal(
                format_args!("{error:#}"),
                format_args!(
                    "cannot safely repair default store directory {}: {error:#}",
                    parent.display()
                ),
            )
        });
    }

    // Fail closed on the stat itself: not being able to read the metadata is
    // not the same as the directory passing.
    let meta = std::fs::metadata(parent).map_err(|e| {
        role.refusal(
            format_args!(
                "refusing to start: cannot stat {directory_name} {} for {env_name}: {e}. \
             It gates rendezvous-path safety, and unreadable metadata is not a passing state.",
                parent.display()
            ),
            format_args!(
                "cannot stat store directory {}: {e}; unreadable metadata is not a passing state",
                parent.display()
            ),
        )
    })?;

    use std::os::unix::fs::MetadataExt;
    let owner = meta.uid();
    if owner != daemon_euid && owner != 0 {
        return Err(role.refusal(
            format_args!(
                "refusing to start: {directory_name} {} for {env_name} is owned by uid {owner}, \
             not this daemon's uid ({daemon_euid}) or root. A directory owner can replace \
             the rendezvous path regardless of mode bits. Point {env_name} at a directory \
             you own, or unset it for the default.",
                parent.display()
            ),
            format_args!(
                "store directory {} is owned by uid {owner}, not this process's uid \
                 ({daemon_euid}) or root; its owner can replace the database path",
                parent.display()
            ),
        ));
    }

    let mode = meta.permissions().mode();
    if mode & 0o022 != 0 {
        if role == RendezvousPathRole::PidFile
            && super::lifecycle::path_override(PID_PATH_ENV).is_none()
            && parent == khive_dir()
        {
            anyhow::bail!(
                "refusing to start: default PID-file directory {} is mode {:04o} — writable by group or other",
                parent.display(),
                mode & 0o7777
            );
        }
        return Err(role.refusal(
            format_args!(
                "refusing to start: {directory_name} {} for {env_name} is mode {:04o} — writable \
             by group or other, so another local user could replace the rendezvous path. \
             Use a directory only you can write, or unset {env_name} for the default. \
             This daemon is not changing the permissions of a directory it does not own.",
                parent.display(),
                mode & 0o7777
            ),
            format_args!(
                "store directory {} is mode {:04o}, writable by group or other, so another local \
                 user could replace the database path",
                parent.display(),
                mode & 0o7777
            ),
        ));
    }

    ensure_rendezvous_path_is_swap_resistant(parent, daemon_euid, role)
}

/// Socket-role form of [`ensure_rendezvous_path_is_swap_resistant`], used by the
/// socket-path tests.
#[cfg(all(unix, test))]
pub(super) fn ensure_socket_path_is_swap_resistant(
    parent: &std::path::Path,
    daemon_euid: u32,
) -> anyhow::Result<()> {
    ensure_rendezvous_path_is_swap_resistant(parent, daemon_euid, RendezvousPathRole::Socket)
}

/// Walk the socket directory path exactly as the kernel will traverse it at
/// bind time — component by component, following symlinks — and refuse any
/// node another local user could swap after this validation.
///
/// Checking only the canonicalized result is not enough: bind and every
/// client traverse the *original* path, so a symlink component owned by
/// another user can resolve somewhere trusted while it is being validated
/// and be retargeted before the socket is bound. Validating the nodes the
/// traversal actually visits closes that gap: a symlink component is
/// acceptable only when its owner — the only party besides root who can
/// retarget it — is this daemon's euid or root, and every directory
/// component is held to the ancestor rule below.
///
/// The directory rule is deliberately weaker than the immediate parent's.
/// The parent hosts the socket file, where the threat is *creation* of the
/// predictable path — the sticky bit does not restrict creating, so no
/// sticky exception is sound there. An ancestor only threatens via
/// *rename/unlink of an existing entry we own*, which the sticky bit does
/// restrict: in a sticky directory, only the entry's owner, the directory's
/// owner, or root may rename it. So a root-owned `/tmp` (1777) is an
/// acceptable ancestor of a user-owned 0700 socket directory, while a
/// non-sticky group/other-writable ancestor, or one owned by a third uid
/// (who could rename the entry, or chmod the directory first), is refused.
/// Every stat failure fails closed.
#[cfg(unix)]
pub(super) fn ensure_rendezvous_path_is_swap_resistant(
    parent: &std::path::Path,
    daemon_euid: u32,
    role: RendezvousPathRole<'_>,
) -> anyhow::Result<()> {
    use std::os::unix::fs::MetadataExt;

    let env_name = role.env_name();
    let directory_name = role.directory_name();
    let path_name = role.path_name();
    let component_name = role.path_component_name();

    let absolute = if parent.is_absolute() {
        parent.to_path_buf()
    } else {
        std::env::current_dir()
            .map_err(|e| {
                role.refusal(
                    format_args!(
                        "refusing to start: cannot resolve the working directory to absolutize \
                     {directory_name} {} for {env_name}: {e}.",
                        parent.display()
                    ),
                    format_args!(
                        "cannot resolve the working directory for store directory {}: {e}",
                        parent.display()
                    ),
                )
            })?
            .join(parent)
    };

    fn push_components(stack: &mut Vec<std::ffi::OsString>, path: &std::path::Path) {
        let components: Vec<_> = path
            .components()
            .map(|c| c.as_os_str().to_os_string())
            .collect();
        stack.extend(components.into_iter().rev());
    }

    let mut stack: Vec<std::ffi::OsString> = Vec::new();
    push_components(&mut stack, &absolute);
    let mut resolved = std::path::PathBuf::new();
    let mut symlinks_followed = 0u32;

    while let Some(component) = stack.pop() {
        if component == "/" {
            resolved = std::path::PathBuf::from("/");
            continue;
        }
        if component == "." {
            continue;
        }
        if component == ".." {
            resolved.pop();
            continue;
        }
        let candidate = resolved.join(&component);
        let meta = std::fs::symlink_metadata(&candidate).map_err(|e| {
            role.refusal(
                format_args!(
                    "refusing to start: cannot stat {component_name} component {} for {env_name}: \
                 {e}. An unreadable component is not a passing one.",
                    candidate.display()
                ),
                format_args!(
                    "cannot stat store-path component {}: {e}; unreadable metadata is not a \
                     passing state",
                    candidate.display()
                ),
            )
        })?;
        let owner = meta.uid();

        if meta.file_type().is_symlink() {
            symlinks_followed += 1;
            if symlinks_followed > 40 {
                return Err(role.refusal(
                    format_args!(
                        "refusing to start: {path_name} for {env_name} resolves through more than \
                     40 symlinks at {} — treating this as a loop.",
                        candidate.display()
                    ),
                    format_args!(
                        "store path resolves through more than 40 symlinks at {}; treating this as \
                         a loop",
                        candidate.display()
                    ),
                ));
            }
            if owner != daemon_euid && owner != 0 {
                return Err(role.refusal(
                    format_args!(
                        "refusing to start: {component_name} symlink component {} for {env_name} \
                     is owned by uid {owner}, not this daemon's uid ({daemon_euid}) or root — \
                     its owner could retarget it after this check and re-root the {path_name}. \
                     Point {env_name} somewhere trusted end to end, or unset it for the default.",
                        candidate.display()
                    ),
                    format_args!(
                        "store-path symlink component {} is owned by uid {owner}, not this \
                         process's uid ({daemon_euid}) or root; its owner could retarget the \
                         database path",
                        candidate.display()
                    ),
                ));
            }
            let target = std::fs::read_link(&candidate).map_err(|e| {
                role.refusal(
                    format_args!(
                        "refusing to start: cannot read {component_name} symlink component {} \
                     for {env_name}: {e}.",
                        candidate.display()
                    ),
                    format_args!(
                        "cannot read store-path symlink component {}: {e}",
                        candidate.display()
                    ),
                )
            })?;
            push_components(&mut stack, &target);
            continue;
        }

        if meta.is_dir() {
            let mode = meta.permissions().mode();
            let sticky = mode & 0o1000 != 0;
            if owner != daemon_euid && owner != 0 {
                return Err(role.refusal(
                    format_args!(
                    "refusing to start: {component_name} ancestor {} for {env_name} is owned by \
                     uid {owner}, not this daemon's uid ({daemon_euid}) or root — its owner \
                     could rename the next path component and re-root the {path_name}. Point \
                     {env_name} somewhere trusted end to end, or unset it for the default.",
                    candidate.display()
                    ),
                    format_args!(
                        "store-path ancestor {} is owned by uid {owner}, not this process's uid \
                         ({daemon_euid}) or root; its owner could rename the next path component",
                        candidate.display()
                    ),
                ));
            }
            if mode & 0o022 != 0 && !sticky {
                return Err(role.refusal(
                    format_args!(
                        "refusing to start: {component_name} ancestor {} for {env_name} is mode \
                     {:04o} — writable by group or other without the sticky bit, so another \
                     local user could rename the next path component and re-root the {path_name}. \
                     Point {env_name} somewhere trusted end to end, or unset it for the default.",
                        candidate.display(),
                        mode & 0o7777
                    ),
                    format_args!(
                        "store-path ancestor {} is mode {:04o}, writable by group or other without \
                         the sticky bit, so another local user could rename the next path \
                         component",
                        candidate.display(), mode & 0o7777
                    ),
                ));
            }
            resolved = candidate;
            continue;
        }

        return Err(role.refusal(
            format_args!(
                "refusing to start: {component_name} component {} for {env_name} is neither a \
             directory nor a symlink — the {path_name} cannot traverse it.",
                candidate.display()
            ),
            format_args!(
                "store-path component {} is neither a directory nor a symlink; the database path \
                 cannot traverse it",
                candidate.display()
            ),
        ));
    }

    Ok(())
}

#[cfg(all(test, unix))]
mod default_directory_repair_tests {
    use super::{
        ensure_pid_file_dir_is_trusted, ensure_socket_dir_is_trusted,
        repair_default_dir_with_recovery_guidance, repair_owned_default_dir,
        repair_owned_default_dir_with_hooks, tighten_owned_recovery_lock,
        tighten_owned_recovery_lock_with_hook, RendezvousPathRole,
    };
    use std::os::unix::fs::{MetadataExt, PermissionsExt};
    use std::os::unix::io::AsRawFd;

    fn hold_lock(file: &std::fs::File) {
        // SAFETY: the fixture owns this live file descriptor.
        assert_eq!(
            unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
            0
        );
    }

    #[derive(Clone)]
    struct EmptyDispatcher;

    #[async_trait::async_trait]
    impl super::super::DaemonDispatch for EmptyDispatcher {
        fn plan(&self, _ops: &str) -> String {
            String::new()
        }

        async fn dispatch(
            &self,
            _ops: String,
            _presentation: Option<String>,
            _presentation_per_op: Option<Vec<Option<String>>>,
            _format: Option<String>,
            _format_per_op: Option<Vec<Option<String>>>,
            _from_wire: bool,
            _identity: Option<super::super::RequestIdentity>,
        ) -> Result<String, String> {
            Ok("{}".to_owned())
        }

        async fn warm_all(&self) {}
        fn namespace(&self) -> &str {
            "test"
        }
        fn config_id(&self) -> &str {
            "test"
        }
    }

    #[test]
    #[serial_test::serial]
    fn pid_directory_diagnostic_depends_on_the_checked_path_and_override() {
        if crate::test_process::run_in_child() {
            return;
        }
        let root = tempfile::Builder::new()
            .prefix("khive-pid-diagnostic-")
            .tempdir_in("/tmp")
            .unwrap();
        let home = root.path().join("home");
        let default = home.join(".khive");
        let other = root.path().join("other");
        std::fs::create_dir_all(&default).unwrap();
        std::fs::create_dir(&other).unwrap();
        std::fs::set_permissions(&default, std::fs::Permissions::from_mode(0o775)).unwrap();
        std::fs::set_permissions(&other, std::fs::Permissions::from_mode(0o775)).unwrap();
        std::env::set_var("HOME", &home);
        std::env::remove_var("KHIVE_PID");
        std::env::remove_var("KHIVE_SOCKET");

        let other_message = ensure_pid_file_dir_is_trusted(&other.join("daemon.pid"))
            .unwrap_err()
            .to_string();
        assert!(
            other_message.contains("PID-file directory") && other_message.contains("for KHIVE_PID"),
            "{other_message}"
        );
        let default_message = ensure_pid_file_dir_is_trusted(&default.join("khived.pid"))
            .unwrap_err()
            .to_string();
        assert!(
            default_message.contains("default PID-file directory"),
            "{default_message}"
        );

        std::env::set_var("KHIVE_PID", default.join("khived.pid"));
        let explicit_message = ensure_pid_file_dir_is_trusted(&default.join("khived.pid"))
            .unwrap_err()
            .to_string();
        assert!(
            explicit_message.contains("for KHIVE_PID"),
            "{explicit_message}"
        );
        assert!(
            !explicit_message.contains("default PID-file directory"),
            "{explicit_message}"
        );
        assert_eq!(
            std::fs::metadata(&other).unwrap().permissions().mode() & 0o777,
            0o775
        );
        assert_eq!(
            std::fs::metadata(&default).unwrap().permissions().mode() & 0o777,
            0o775
        );
    }

    #[test]
    #[serial_test::serial]
    fn explicit_boot_lock_does_not_prepare_an_unrelated_default_home() {
        if crate::test_process::run_in_child() {
            return;
        }
        let root = tempfile::Builder::new()
            .prefix("khive-explicit-boot-")
            .tempdir_in("/tmp")
            .unwrap();
        let home = root.path().join("missing-home");
        let lock = root.path().join("boot.lock");
        std::env::set_var("HOME", &home);
        std::env::set_var("KHIVE_PID", root.path().join("daemon.pid"));
        std::env::set_var("KHIVE_SOCKET", root.path().join("daemon.sock"));
        std::env::set_var("KHIVE_LOCK", &lock);
        std::env::remove_var("KHIVE_RECOVERER_LOCK");
        std::env::remove_var("KHIVE_SUPERVISOR_MARKER");
        let opened = super::super::locks::open_mutating_daemon_lock(&lock, false)
            .expect("the explicit lock parent exists and is trusted");
        assert!(lock.exists());
        assert!(
            !home.exists(),
            "an unrelated default HOME must remain absent"
        );
        drop(opened);

        let unsafe_parent = root.path().join("unsafe-parent");
        std::fs::create_dir(&unsafe_parent).unwrap();
        std::fs::set_permissions(&unsafe_parent, std::fs::Permissions::from_mode(0o775)).unwrap();
        let unsafe_lock = unsafe_parent.join("boot.lock");
        assert!(super::super::locks::open_mutating_daemon_lock(&unsafe_lock, false).is_err());
        assert!(
            !unsafe_lock.exists(),
            "an untrusted explicit parent must remain refused"
        );
        assert!(!home.exists());
    }

    #[test]
    #[serial_test::serial]
    fn explicit_boot_lock_creates_its_missing_pid_parent() {
        if crate::test_process::run_in_child() {
            return;
        }
        let root = tempfile::Builder::new()
            .prefix("khive-explicit-missing-parent-")
            .tempdir_in("/tmp")
            .unwrap();
        let home = root.path().join("missing-home");
        let parent = root.path().join("new").join("rendezvous");
        let lock = parent.join("boot.lock");
        std::env::set_var("HOME", &home);
        std::env::set_var("KHIVE_PID", parent.join("daemon.pid"));
        std::env::set_var("KHIVE_SOCKET", parent.join("daemon.sock"));
        std::env::set_var("KHIVE_LOCK", &lock);
        std::env::remove_var("KHIVE_RECOVERER_LOCK");
        std::env::remove_var("KHIVE_SUPERVISOR_MARKER");
        assert!(!parent.exists());
        // SAFETY: this fixture runs alone in a dedicated child process.
        let previous_umask = unsafe { libc::umask(0o077) };
        let opened = super::super::locks::open_mutating_daemon_lock(&lock, false);
        // SAFETY: restore the process umask immediately after the operation.
        unsafe { libc::umask(previous_umask) };
        let opened = opened.expect("the explicitly selected lock parent is created");
        assert!(parent.is_dir());
        assert!(lock.is_file());
        assert!(!home.exists());
        drop(opened);
    }

    #[test]
    #[serial_test::serial]
    fn private_lock_with_default_rendezvous_does_not_prepare_home() {
        if crate::test_process::run_in_child() {
            return;
        }
        let root = tempfile::Builder::new()
            .prefix("khive-private-lock-default-rendezvous-")
            .tempdir_in("/tmp")
            .unwrap();
        let home = root.path().join("home");
        std::fs::create_dir(&home).unwrap();
        let lock = root.path().join("boot.lock");
        std::env::set_var("HOME", &home);
        std::env::remove_var("KHIVE_PID");
        std::env::remove_var("KHIVE_SOCKET");
        std::env::set_var("KHIVE_LOCK", &lock);
        std::env::remove_var("KHIVE_RECOVERER_LOCK");
        std::env::remove_var("KHIVE_SUPERVISOR_MARKER");
        let opened = super::super::locks::open_mutating_daemon_lock(&lock, false)
            .expect("the private lock must open");
        hold_lock(&opened);
        assert!(lock.is_file());
        assert!(
            std::fs::read_dir(&home).unwrap().next().is_none(),
            "opening a private lock must not prepare the default rendezvous"
        );
        drop(opened);
    }

    #[test]
    #[serial_test::serial]
    fn default_lock_preparation_only_inspects_the_selected_lock() {
        if crate::test_process::run_in_child() {
            return;
        }
        let root = tempfile::Builder::new()
            .prefix("khive-selected-default-lock-")
            .tempdir_in("/tmp")
            .unwrap();
        let home = root.path().join("home");
        let default = home.join(".khive");
        std::fs::create_dir_all(&default).unwrap();
        std::fs::set_permissions(&default, std::fs::Permissions::from_mode(0o700)).unwrap();
        std::env::set_var("HOME", &home);
        std::env::remove_var("KHIVE_PID");
        std::env::remove_var("KHIVE_SOCKET");
        std::env::remove_var("KHIVE_LOCK");
        std::env::remove_var("KHIVE_RECOVERER_LOCK");
        std::env::remove_var("KHIVE_SUPERVISOR_MARKER");
        let unrelated = default.join("khived.recoverer.lock");
        std::os::unix::fs::symlink(root.path().join("missing"), &unrelated).unwrap();
        let selected = default.join("khived.recovery.lock");
        super::prepare_default_rendezvous_for_lock(&selected)
            .expect("unrelated recovery lock must not be examined");
        let opened = super::super::locks::open_mutating_daemon_lock(&selected, false)
            .expect("selected default lock must open");
        hold_lock(&opened);
        assert_eq!(
            opened.metadata().unwrap().permissions().mode() & 0o777,
            0o600
        );
        assert!(std::fs::symlink_metadata(unrelated)
            .unwrap()
            .file_type()
            .is_symlink());
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn default_rendezvous_is_prepared_with_an_external_boot_lock() {
        if crate::test_process::run_in_child() {
            return;
        }
        let root = tempfile::Builder::new()
            .prefix("khive-default-with-external-lock-")
            .tempdir_in("/tmp")
            .unwrap();
        let home = root.path().join("home");
        std::fs::create_dir(&home).unwrap();
        let lock = root.path().join("boot.lock");
        std::env::set_var("HOME", &home);
        std::env::remove_var("KHIVE_PID");
        std::env::remove_var("KHIVE_SOCKET");
        std::env::set_var("KHIVE_LOCK", &lock);
        std::env::remove_var("KHIVE_RECOVERER_LOCK");
        std::env::remove_var("KHIVE_SUPERVISOR_MARKER");
        // SAFETY: the test runs in a dedicated child process.
        let previous_umask = unsafe { libc::umask(0o002) };
        let default = home.join(".khive");
        let guard = super::super::acquire_daemon_boot_guard().expect("external boot guard");
        assert_eq!(
            std::fs::metadata(&default).unwrap().permissions().mode() & 0o777,
            0o700,
            "the default rendezvous must be private before boot"
        );
        let daemon = tokio::spawn(super::super::run_daemon_with_boot_guard_and_start(
            EmptyDispatcher,
            Some(guard),
            |_| {},
        ));
        let pid = default.join("khived.pid");
        let socket = default.join("khived.sock");
        let ready = tokio::time::timeout(std::time::Duration::from_secs(5), async {
            loop {
                assert!(!daemon.is_finished(), "daemon exited before boot");
                if lock.exists() && pid.exists() && socket.exists() {
                    break;
                }
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            }
        })
        .await;
        // SAFETY: restore the process umask immediately after the boot witness.
        unsafe { libc::umask(previous_umask) };
        ready.expect("default daemon must bind with its external boot lock");
        assert_eq!(
            std::fs::metadata(default).unwrap().permissions().mode() & 0o777,
            0o700
        );
        daemon.abort();
        assert!(daemon
            .await
            .expect_err("daemon task must be cancelled")
            .is_cancelled());
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn supplied_external_guard_boots_with_private_default_rendezvous() {
        use std::os::unix::fs::FileTypeExt;

        if crate::test_process::run_in_child() {
            return;
        }
        let root = tempfile::Builder::new()
            .prefix("khive-supplied-guard-default-")
            .tempdir_in("/tmp")
            .unwrap();
        let home = root.path().join("home");
        std::fs::create_dir(&home).unwrap();
        let lock = root.path().join("boot.lock");
        std::env::set_var("HOME", &home);
        std::env::remove_var("KHIVE_PID");
        std::env::remove_var("KHIVE_SOCKET");
        std::env::set_var("KHIVE_LOCK", &lock);
        std::env::remove_var("KHIVE_RECOVERER_LOCK");
        std::env::remove_var("KHIVE_SUPERVISOR_MARKER");
        let guard = super::super::locks::open_mutating_daemon_lock(&lock, false)
            .expect("external guard file must open");
        hold_lock(&guard);
        assert!(std::fs::read_dir(&home).unwrap().next().is_none());

        let default = home.join(".khive");
        let pid = default.join("khived.pid");
        let socket = default.join("khived.sock");
        let entered = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let entered_at_hook = std::sync::Arc::clone(&entered);
        let observed_mode = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(u32::MAX));
        let mode_at_hook = std::sync::Arc::clone(&observed_mode);
        let socket_absent = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let socket_absent_at_hook = std::sync::Arc::clone(&socket_absent);
        let directory_at_hook = default.clone();
        let socket_at_hook = socket.clone();
        *super::DEFAULT_RENDEZVOUS_PREBIND_HOOK.lock().unwrap() = Some(Box::new(move || {
            let mode = std::fs::metadata(&directory_at_hook)
                .map(|metadata| metadata.permissions().mode() & 0o777)
                .unwrap_or(u32::MAX);
            mode_at_hook.store(mode, std::sync::atomic::Ordering::SeqCst);
            socket_absent_at_hook.store(
                !socket_at_hook.exists(),
                std::sync::atomic::Ordering::SeqCst,
            );
            entered_at_hook.store(true, std::sync::atomic::Ordering::SeqCst);
        }));
        // SAFETY: the test runs in a dedicated child process.
        let previous_umask = unsafe { libc::umask(0o002) };
        let daemon = tokio::spawn(super::super::run_daemon_with_boot_guard_and_start(
            EmptyDispatcher,
            Some(guard),
            |_| {},
        ));
        let hook_reached = tokio::time::timeout(std::time::Duration::from_secs(5), async {
            while !entered.load(std::sync::atomic::Ordering::SeqCst) && !daemon.is_finished() {
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            }
        })
        .await;
        assert!(hook_reached.is_ok(), "daemon must reach pre-bind observer");
        assert!(
            entered.load(std::sync::atomic::Ordering::SeqCst),
            "pre-bind observer must execute"
        );
        assert_eq!(
            observed_mode.load(std::sync::atomic::Ordering::SeqCst),
            0o700,
            "default rendezvous must be private before binding; u32::MAX means absent or unreadable"
        );
        assert!(
            socket_absent.load(std::sync::atomic::Ordering::SeqCst),
            "witness must precede socket bind"
        );
        let ready = tokio::time::timeout(std::time::Duration::from_secs(5), async {
            loop {
                assert!(!daemon.is_finished(), "daemon exited before boot");
                if pid.exists() && socket.exists() {
                    break;
                }
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            }
        })
        .await;
        // SAFETY: restore the process umask immediately after the boot witness.
        unsafe { libc::umask(previous_umask) };
        ready.expect("daemon must bind with the caller-supplied guard");
        assert!(std::fs::metadata(&socket).unwrap().file_type().is_socket());
        assert_eq!(
            std::fs::metadata(default).unwrap().permissions().mode() & 0o777,
            0o700
        );
        daemon.abort();
        assert!(daemon
            .await
            .expect_err("daemon task must be cancelled")
            .is_cancelled());
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn explicit_daemon_boot_keeps_private_home_empty() {
        use std::os::unix::fs::FileTypeExt;

        if crate::test_process::run_in_child() {
            return;
        }
        let root = tempfile::Builder::new()
            .prefix("khive-explicit-daemon-")
            .tempdir_in("/tmp")
            .expect("private synthetic root");
        let home = root.path().join("home");
        let rendezvous = root.path().join("run");
        std::fs::create_dir(&home).unwrap();
        std::fs::create_dir(&rendezvous).unwrap();
        std::fs::set_permissions(&home, std::fs::Permissions::from_mode(0o700)).unwrap();
        std::fs::set_permissions(&rendezvous, std::fs::Permissions::from_mode(0o700)).unwrap();
        let lock = rendezvous.join("boot.lock");
        let pid = rendezvous.join("daemon.pid");
        let socket = rendezvous.join("daemon.sock");
        std::env::set_var("HOME", &home);
        std::env::set_var("KHIVE_LOCK", &lock);
        std::env::set_var("KHIVE_PID", &pid);
        std::env::set_var("KHIVE_SOCKET", &socket);
        std::env::remove_var("KHIVE_RECOVERER_LOCK");
        std::env::remove_var("KHIVE_SUPERVISOR_MARKER");
        assert!(std::fs::read_dir(&home).unwrap().next().is_none());

        let daemon = tokio::spawn(super::run_daemon(EmptyDispatcher));
        tokio::time::timeout(std::time::Duration::from_secs(5), async {
            loop {
                assert!(
                    !daemon.is_finished(),
                    "daemon exited before the boot witness"
                );
                if lock.exists() && pid.exists() && socket.exists() {
                    break;
                }
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("daemon must create its explicit boot lock, PID and socket");
        assert!(std::fs::metadata(&socket).unwrap().file_type().is_socket());
        assert!(
            std::fs::read_dir(&home).unwrap().next().is_none(),
            "explicit daemon boot must leave its private HOME empty"
        );
        daemon.abort();
        let error = daemon.await.expect_err("the daemon task must be cancelled");
        assert!(
            error.is_cancelled(),
            "daemon task failed before cancellation: {error}"
        );
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn direct_daemon_boot_refuses_unsafe_ancestor_before_lock_creation() {
        if crate::test_process::run_in_child() {
            return;
        }
        let root = tempfile::Builder::new()
            .prefix("khive-boot-unsafe-")
            .tempdir_in("/tmp")
            .expect("private synthetic root");
        let unsafe_ancestor = root.path().join("unsafe");
        let home = unsafe_ancestor.join("home");
        std::fs::create_dir_all(&home).unwrap();
        std::fs::set_permissions(&unsafe_ancestor, std::fs::Permissions::from_mode(0o775)).unwrap();
        std::fs::set_permissions(&home, std::fs::Permissions::from_mode(0o700)).unwrap();
        std::env::set_var("HOME", &home);
        for key in [
            "KHIVE_PID",
            "KHIVE_SOCKET",
            "KHIVE_LOCK",
            "KHIVE_RECOVERER_LOCK",
            "KHIVE_SUPERVISOR_MARKER",
        ] {
            std::env::remove_var(key);
        }
        let directory = home.join(".khive");
        assert!(!directory.exists());

        let outcome = tokio::time::timeout(
            std::time::Duration::from_secs(2),
            super::run_daemon(EmptyDispatcher),
        )
        .await;

        assert!(
            matches!(outcome, Ok(Err(_))),
            "unsafe direct boot must refuse promptly"
        );
        assert!(
            !directory.exists(),
            "no lock directory may be created under an unsafe ancestor"
        );
        assert_eq!(
            std::fs::metadata(&unsafe_ancestor)
                .unwrap()
                .permissions()
                .mode()
                & 0o777,
            0o775
        );

        std::fs::set_permissions(&unsafe_ancestor, std::fs::Permissions::from_mode(0o700)).unwrap();
        std::fs::create_dir(&directory).unwrap();
        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700)).unwrap();
        let existing_lock = directory.join("khived.recovery.lock");
        std::fs::write(&existing_lock, b"").unwrap();
        std::fs::set_permissions(&existing_lock, std::fs::Permissions::from_mode(0o644)).unwrap();
        let guard = super::super::acquire_daemon_boot_guard().expect("trusted boot-lock baseline");
        assert_eq!(
            guard.metadata().unwrap().permissions().mode() & 0o777,
            0o600
        );
        assert_eq!(
            std::fs::metadata(&existing_lock)
                .unwrap()
                .permissions()
                .mode()
                & 0o777,
            0o600
        );
        drop(guard);
    }

    #[test]
    #[serial_test::serial]
    fn foreign_owner_is_refused_before_permissions_change() {
        let directory = tempfile::Builder::new()
            .prefix("khive-foreign-owner-")
            .tempdir_in("/tmp")
            .expect("private synthetic directory");
        std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o775)).unwrap();
        let actual_owner = std::fs::metadata(directory.path()).unwrap().uid();
        let other_owner = actual_owner.wrapping_add(1);
        let tmp_owner = std::fs::metadata("/tmp").unwrap().uid();

        let error =
            repair_owned_default_dir(directory.path(), RendezvousPathRole::PidFile, other_owner)
                .expect_err("directory owned by a different uid must not be repaired");

        let message = error.to_string();
        if tmp_owner != 0 && tmp_owner != other_owner {
            assert!(
                message.contains(&format!(
                    "PID-file-path ancestor /tmp for KHIVE_PID is owned by uid {tmp_owner}, not this daemon's uid ({other_owner}) or root"
                )),
                "{message}"
            );
        } else {
            assert!(
                message.contains(&format!(
                    "refusing to repair default rendezvous directory {}: owner uid {actual_owner}, mode 0775; expected uid {other_owner}",
                    directory.path().display()
                )),
                "{message}"
            );
        }
        assert_eq!(
            std::fs::metadata(directory.path())
                .unwrap()
                .permissions()
                .mode()
                & 0o777,
            0o775
        );
    }

    #[test]
    #[serial_test::serial]
    fn repair_does_not_chmod_a_replacement_path() {
        let root = tempfile::Builder::new()
            .prefix("khive-default-swap-")
            .tempdir_in("/tmp")
            .expect("private synthetic directory");
        let directory = root.path().join("rendezvous");
        let original = root.path().join("original");
        let replacement = root.path().join("replacement");
        std::fs::create_dir(&directory).unwrap();
        std::fs::create_dir(&replacement).unwrap();
        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o775)).unwrap();
        std::fs::set_permissions(&replacement, std::fs::Permissions::from_mode(0o755)).unwrap();
        let owner = std::fs::metadata(&directory).unwrap().uid();

        let outcome = repair_owned_default_dir_with_hooks(
            &directory,
            RendezvousPathRole::PidFile,
            owner,
            || {},
            || {
                std::fs::rename(&directory, &original).unwrap();
                std::fs::rename(&replacement, &directory).unwrap();
            },
        );

        assert!(outcome.is_err(), "a path replacement must be reported");
        assert_eq!(
            std::fs::metadata(&directory).unwrap().permissions().mode() & 0o777,
            0o755
        );
        assert_eq!(
            std::fs::metadata(&original).unwrap().permissions().mode() & 0o777,
            0o700
        );
    }

    #[test]
    #[serial_test::serial]
    fn repair_does_not_follow_symlink_replacing_the_leaf_before_open() {
        use std::os::unix::fs::symlink;

        let root = tempfile::Builder::new()
            .prefix("khive-default-symlink-")
            .tempdir_in("/tmp")
            .expect("private synthetic directory");
        let directory = root.path().join("rendezvous");
        let target = root.path().join("target");
        std::fs::create_dir(&directory).unwrap();
        std::fs::create_dir(&target).unwrap();
        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o775)).unwrap();
        std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o775)).unwrap();
        let owner = std::fs::metadata(&directory).unwrap().uid();

        let outcome = repair_owned_default_dir_with_hooks(
            &directory,
            RendezvousPathRole::PidFile,
            owner,
            || {
                std::fs::remove_dir(&directory).unwrap();
                symlink(&target, &directory).unwrap();
            },
            || {},
        );

        assert!(outcome.is_err(), "a replacement symlink must be refused");
        assert_eq!(
            std::fs::metadata(&target).unwrap().permissions().mode() & 0o777,
            0o775
        );
    }

    #[test]
    #[serial_test::serial]
    fn repair_refuses_directory_replaced_before_open_without_chmod() {
        let root = tempfile::Builder::new()
            .prefix("khive-default-before-open-")
            .tempdir_in("/tmp")
            .expect("private synthetic directory");
        let directory = root.path().join("rendezvous");
        let original = root.path().join("original");
        let replacement = root.path().join("replacement");
        std::fs::create_dir(&directory).unwrap();
        std::fs::create_dir(&replacement).unwrap();
        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o775)).unwrap();
        std::fs::set_permissions(&replacement, std::fs::Permissions::from_mode(0o775)).unwrap();
        let owner = std::fs::metadata(&directory).unwrap().uid();

        let outcome = repair_owned_default_dir_with_hooks(
            &directory,
            RendezvousPathRole::PidFile,
            owner,
            || {
                std::fs::rename(&directory, &original).unwrap();
                std::fs::rename(&replacement, &directory).unwrap();
            },
            || {},
        );

        assert!(
            outcome.is_err(),
            "a directory swapped before open must be refused"
        );
        assert_eq!(
            std::fs::metadata(&directory).unwrap().permissions().mode() & 0o777,
            0o775
        );
        assert_eq!(
            std::fs::metadata(&original).unwrap().permissions().mode() & 0o777,
            0o775
        );
    }

    #[test]
    #[serial_test::serial]
    fn repair_restores_owner_access_removed_after_validation() {
        let root = tempfile::Builder::new()
            .prefix("khive-default-chmod-")
            .tempdir_in("/tmp")
            .expect("private synthetic directory");
        let directory = root.path().join("rendezvous");
        std::fs::create_dir(&directory).unwrap();
        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o775)).unwrap();
        let owner = std::fs::metadata(&directory).unwrap().uid();

        let outcome = repair_owned_default_dir_with_hooks(
            &directory,
            RendezvousPathRole::PidFile,
            owner,
            || {},
            || {
                std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o500))
                    .unwrap()
            },
        );

        let mode = std::fs::metadata(&directory).unwrap().permissions().mode() & 0o777;
        let created = std::fs::File::create(directory.join("daemon.lock"));
        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700)).unwrap();
        assert!(
            outcome.is_ok(),
            "an owned directory is repaired: {outcome:?}"
        );
        assert_eq!(mode, 0o700);
        assert!(
            created.is_ok(),
            "the daemon can create its files after repair: {created:?}"
        );
    }

    #[test]
    #[serial_test::serial]
    fn repair_makes_an_owner_read_only_directory_writable() {
        let root = tempfile::Builder::new()
            .prefix("khive-default-read-only-")
            .tempdir_in("/tmp")
            .expect("private synthetic directory");
        let directory = root.path().join("rendezvous");
        std::fs::create_dir(&directory).unwrap();
        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o550)).unwrap();
        let owner = std::fs::metadata(&directory).unwrap().uid();

        let outcome = repair_owned_default_dir(&directory, RendezvousPathRole::PidFile, owner);

        let mode = std::fs::metadata(&directory).unwrap().permissions().mode() & 0o777;
        let created = std::fs::File::create(directory.join("daemon.pid"));
        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700)).unwrap();
        assert!(
            outcome.is_ok(),
            "an owned directory is repaired: {outcome:?}"
        );
        assert_eq!(mode, 0o700);
        assert!(
            created.is_ok(),
            "the daemon can create its files after repair: {created:?}"
        );
    }

    #[test]
    #[serial_test::serial]
    fn newly_created_inaccessible_default_dir_reports_manual_recovery() {
        let root = tempfile::Builder::new()
            .prefix("khive-dir-recovery-")
            .tempdir_in("/tmp")
            .unwrap();
        let directory = root.path().join("rendezvous");
        std::fs::create_dir(&directory).unwrap();
        let uid = std::fs::metadata(&directory).unwrap().uid();
        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o000)).unwrap();
        // This is a fixture qualification, not semantic evidence on a privileged host.
        let denied = std::fs::File::open(&directory)
            .expect_err("fixture requires an unprivileged owner unable to open mode 0000");
        assert_eq!(denied.kind(), std::io::ErrorKind::PermissionDenied);
        let error = repair_default_dir_with_recovery_guidance(&directory, uid, true).unwrap_err();
        let message = format!("{error:#}");
        assert!(message.contains(&directory.display().to_string()));
        assert!(message.contains("0700") && message.contains("by hand"));
        let retry = repair_default_dir_with_recovery_guidance(&directory, uid, false).unwrap_err();
        let retry_message = format!("{retry:#}");
        assert!(retry_message.contains(&directory.display().to_string()));
        assert!(retry_message.contains("0700") && retry_message.contains("by hand"));
        let foreign =
            repair_default_dir_with_recovery_guidance(&directory, uid.wrapping_add(1), false)
                .unwrap_err();
        assert!(!format!("{foreign:#}").contains("by hand"));
        assert_eq!(
            std::fs::metadata(&directory).unwrap().permissions().mode() & 0o777,
            0
        );
        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700)).unwrap();
        repair_default_dir_with_recovery_guidance(&directory, uid, false).unwrap();
    }

    #[test]
    #[serial_test::serial]
    fn concurrent_lock_creation_reopens_the_validated_existing_entry() {
        let root = tempfile::Builder::new()
            .prefix("khive-lock-create-race-")
            .tempdir_in("/tmp")
            .unwrap();
        let lock = root.path().join("recovery.lock");

        let opened = super::super::locks::checked_open_lock_with_observe_hook(
            &lock,
            true,
            false,
            true,
            || {},
            || {},
            (false, false, || {
                std::fs::write(&lock, b"incumbent").unwrap();
                std::fs::set_permissions(&lock, std::fs::Permissions::from_mode(0o644)).unwrap();
            }),
        )
        .expect("concurrent valid lock must be reopened")
        .unwrap();

        let on_disk = std::fs::metadata(&lock).unwrap();
        assert_eq!(opened.metadata().unwrap().ino(), on_disk.ino());
        assert_eq!(on_disk.permissions().mode() & 0o777, 0o600);
        assert_eq!(std::fs::read(&lock).unwrap(), b"incumbent");
    }

    #[test]
    #[serial_test::serial]
    fn concurrent_lock_symlink_is_refused_before_opening_its_target() {
        use std::os::unix::fs::symlink;
        let root = tempfile::Builder::new()
            .prefix("khive-lock-create-symlink-")
            .tempdir_in("/tmp")
            .unwrap();
        let lock = root.path().join("recovery.lock");
        let target = root.path().join("target");
        std::fs::write(&target, b"untouched").unwrap();
        std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o644)).unwrap();

        let error = super::super::locks::checked_open_lock_with_observe_hook(
            &lock,
            true,
            false,
            true,
            || {},
            || {},
            (false, false, || symlink(&target, &lock).unwrap()),
        )
        .unwrap_err();

        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
        assert_eq!(std::fs::read(&target).unwrap(), b"untouched");
        assert_eq!(
            std::fs::metadata(&target).unwrap().permissions().mode() & 0o777,
            0o644
        );
    }

    #[test]
    #[serial_test::serial]
    fn created_lock_failures_leave_entry_and_report_manual_recovery() {
        let root = tempfile::Builder::new()
            .prefix("khive-lock-failure-")
            .tempdir_in("/tmp")
            .unwrap();
        for (label, fail_metadata, fail_chmod) in
            [("metadata", true, false), ("chmod", false, true)]
        {
            let lock = root.path().join(label);
            let error = super::super::locks::checked_open_lock_with_faults(
                &lock,
                true,
                false,
                true,
                || {},
                || {
                    if fail_chmod {
                        std::fs::set_permissions(&lock, std::fs::Permissions::from_mode(0o000))
                            .unwrap();
                    }
                },
                (fail_metadata, fail_chmod),
            )
            .unwrap_err();
            let message = error.to_string();
            assert!(message.contains(&lock.display().to_string()));
            assert!(
                message.contains("confirming no daemon")
                    && message.contains("verifying the entry is the leftover lock")
            );
            assert!(lock.exists(), "failure must not unlink the created entry");
            std::fs::remove_file(&lock).unwrap();
            let file = super::super::locks::checked_open_lock(&lock, true, false, true)
                .unwrap()
                .unwrap();
            assert_eq!(file.metadata().unwrap().permissions().mode() & 0o777, 0o600);
        }
    }

    #[test]
    #[serial_test::serial]
    fn created_lock_replacement_reports_inspection_without_removal_advice() {
        let root = tempfile::Builder::new()
            .prefix("khive-lock-created-swap-")
            .tempdir_in("/tmp")
            .unwrap();
        let lock = root.path().join("lock");
        let original = root.path().join("original");
        let replacement = root.path().join("replacement");
        std::fs::write(&replacement, b"replacement").unwrap();
        let error = super::super::locks::checked_open_lock_with_hooks(
            &lock,
            true,
            false,
            true,
            || {},
            || {
                std::fs::rename(&lock, &original).unwrap();
                std::fs::rename(&replacement, &lock).unwrap();
            },
        )
        .unwrap_err();
        let message = error.to_string();
        assert!(message.contains(&lock.display().to_string()));
        assert!(
            message.contains("inspect the path")
                && message.contains("do not remove the replacement")
        );
        assert!(!message.contains("remove it and retry"));
        assert_eq!(std::fs::read(&lock).unwrap(), b"replacement");
        assert!(original.exists());
    }

    #[test]
    #[serial_test::serial]
    fn newly_created_recovery_lock_is_owner_only_under_restrictive_umask() {
        if crate::test_process::run_in_child() {
            return;
        }
        let root = tempfile::Builder::new()
            .prefix("khive-lock-mode-")
            .tempdir_in("/tmp")
            .expect("private synthetic directory");
        std::env::set_var("HOME", root.path());
        std::env::set_var("KHIVE_PID", root.path().join("khived.pid"));
        std::env::set_var("KHIVE_SOCKET", root.path().join("khived.sock"));
        let lock = root.path().join("recovery.lock");
        // SAFETY: this test runs in an isolated child process.
        let old_umask = unsafe { libc::umask(0o777) };
        let opened = super::super::locks::open_lock_file(&lock);
        // SAFETY: restore the umask returned in this isolated process.
        unsafe { libc::umask(old_umask) };

        let file = opened.expect("create new recovery lock");
        assert_eq!(file.metadata().unwrap().permissions().mode() & 0o777, 0o600);
    }

    #[test]
    #[serial_test::serial]
    fn recovery_lock_opener_refuses_a_symlink() {
        use std::os::unix::fs::symlink;

        let root = tempfile::Builder::new()
            .prefix("khive-lock-symlink-")
            .tempdir_in("/tmp")
            .expect("private synthetic directory");
        if crate::test_process::run_in_child() {
            return;
        }
        std::env::set_var("HOME", root.path());
        std::env::set_var("KHIVE_PID", root.path().join("khived.pid"));
        std::env::set_var("KHIVE_SOCKET", root.path().join("khived.sock"));
        let lock = root.path().join("lock");
        let target = root.path().join("not-a-lock");
        symlink(&target, &lock).unwrap();

        let error = super::super::locks::open_lock_file(&lock).unwrap_err();

        assert!(error.to_string().contains(&lock.display().to_string()));
        assert!(
            !target.exists(),
            "opening a lock must not create a symlink target"
        );
    }

    #[test]
    #[serial_test::serial]
    fn foreign_owned_lock_is_refused_without_chmod() {
        let root = tempfile::Builder::new()
            .prefix("khive-foreign-lock-")
            .tempdir_in("/tmp")
            .expect("private synthetic directory");
        let lock = root.path().join("lock");
        std::fs::write(&lock, b"").unwrap();
        std::fs::set_permissions(&lock, std::fs::Permissions::from_mode(0o644)).unwrap();
        let owner = std::fs::metadata(&lock).unwrap().uid();

        let error = tighten_owned_recovery_lock(&lock, owner.wrapping_add(1)).unwrap_err();

        assert!(error.to_string().contains(&lock.display().to_string()));
        assert!(error.to_string().contains("0644"));
        assert_eq!(
            std::fs::metadata(&lock).unwrap().permissions().mode() & 0o777,
            0o644
        );
        tighten_owned_recovery_lock(&lock, owner).unwrap();
        assert_eq!(
            std::fs::metadata(&lock).unwrap().permissions().mode() & 0o777,
            0o600
        );
    }

    #[test]
    #[serial_test::serial]
    fn lock_tightening_does_not_chmod_a_replacement_path() {
        let root = tempfile::Builder::new()
            .prefix("khive-lock-swap-")
            .tempdir_in("/tmp")
            .expect("private synthetic directory");
        let lock = root.path().join("lock");
        let original = root.path().join("original");
        let replacement = root.path().join("replacement");
        std::fs::write(&lock, b"").unwrap();
        std::fs::write(&replacement, b"").unwrap();
        std::fs::set_permissions(&lock, std::fs::Permissions::from_mode(0o644)).unwrap();
        std::fs::set_permissions(&replacement, std::fs::Permissions::from_mode(0o644)).unwrap();
        let owner = std::fs::metadata(&lock).unwrap().uid();

        let outcome = tighten_owned_recovery_lock_with_hook(&lock, owner, || {
            std::fs::rename(&lock, &original).unwrap();
            std::fs::rename(&replacement, &lock).unwrap();
        });

        assert!(outcome.is_err());
        assert_eq!(
            std::fs::metadata(&lock).unwrap().permissions().mode() & 0o777,
            0o644
        );
        assert_eq!(
            std::fs::metadata(&original).unwrap().permissions().mode() & 0o777,
            0o644
        );
    }

    #[test]
    #[serial_test::serial]
    fn lock_open_refuses_parent_replaced_after_directory_fd_check() {
        let root = tempfile::Builder::new()
            .prefix("khive-lock-parent-swap-")
            .tempdir_in("/tmp")
            .expect("private synthetic directory");
        let directory = root.path().join("parent");
        let original = root.path().join("original");
        let replacement = root.path().join("replacement");
        std::fs::create_dir(&directory).unwrap();
        std::fs::create_dir(&replacement).unwrap();
        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700)).unwrap();
        std::fs::set_permissions(&replacement, std::fs::Permissions::from_mode(0o700)).unwrap();
        let lock = directory.join("lock");

        let outcome = super::super::locks::checked_open_lock_with_hooks(
            &lock,
            true,
            false,
            true,
            || {
                std::fs::rename(&directory, &original).unwrap();
                std::fs::rename(&replacement, &directory).unwrap();
            },
            || {},
        );

        assert!(outcome.is_err());
        assert!(!lock.exists(), "replacement parent must not receive a lock");
        assert!(
            !original.join("lock").exists(),
            "detected change must refuse before create"
        );
        std::fs::rename(&directory, &replacement).unwrap();
        std::fs::rename(&original, &directory).unwrap();
        let positive = super::super::locks::checked_open_lock(&lock, true, false, true)
            .expect("trusted-parent positive control")
            .expect("mutating opener creates the lock");
        assert_eq!(
            positive.metadata().unwrap().permissions().mode() & 0o777,
            0o600
        );
    }

    #[test]
    #[serial_test::serial]
    fn explicitly_selected_default_socket_directory_is_not_repaired_on_boot() {
        if crate::test_process::run_in_child() {
            return;
        }
        let home = tempfile::Builder::new()
            .prefix("khive-explicit-default-")
            .tempdir_in("/tmp")
            .expect("private synthetic home");
        std::env::set_var("HOME", home.path());
        let directory = home.path().join(".khive");
        std::fs::create_dir(&directory).unwrap();
        std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o775)).unwrap();
        std::env::set_var("KHIVE_PID", directory.join("khived.pid"));
        std::env::set_var("KHIVE_SOCKET", directory.join("khived.sock"));

        let outcome = ensure_socket_dir_is_trusted(&directory);

        assert!(outcome.is_err());
        assert_eq!(
            std::fs::metadata(&directory).unwrap().permissions().mode() & 0o777,
            0o775
        );
    }
}