phora 0.6.0

A git-based artifact package manager and multiplexer for content-addressed file distribution
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
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
//! Sync-owned persistent state through `StateStore` and `FileStateStore`.

use std::borrow::Borrow;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use thiserror::Error;

use super::{StateStore, durable::fsync_barrier, locking::StateLock};

#[cfg(all(test, target_os = "linux"))]
use super::locking::unescape_octal;
#[cfg(test)]
use super::locking::{STATE_LOCK_SERIAL, is_network_fs, network_lock_advisory};

/// Errors from sync-owned state and its file-backed implementation.
#[derive(Debug, Error)]
pub enum StateError {
    #[error("registry error: {0}")]
    StateStore(String),

    #[error("lock error: {0}")]
    Lock(String),

    #[error("{0}")]
    ReadOnly(String),
}

type Result<T> = std::result::Result<T, StateError>;
type History = bool;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RecordKind {
    File,
    #[default]
    Dir,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ArtifactKey {
    pub target: String,
    pub source: String,
    pub artifact: String,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ManifestEntryKind {
    #[default]
    File,
    Link,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ArtifactRecord {
    pub version: u32,
    pub key: ArtifactKey,
    #[serde(default)]
    pub source: String,
    pub commit: String,
    pub digest: String,
    pub projected_at: String,
    pub layout: String,
    #[serde(default)]
    pub kind: RecordKind,
    pub allow_symlinks: bool,
    pub preserve_executable: bool,
    pub files: Vec<ManifestFile>,
    /// Complete directory snapshot from trusted staging; absent on legacy records.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub directories: Option<Vec<DirectoryStamp>>,
    #[serde(default)]
    pub linked: bool,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub history: History,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub worktree_admin_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mirror_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_git_root: Option<String>,
    /// Digest of the full effective vars map at deploy time; `None` for feature-free artifacts.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vars_digest: Option<String>,
    /// Deploy-time snapshot of the target's expanded absolute path; never re-expanded at read time. `None` on legacy records.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deploy_root: Option<String>,
    /// Prefixed layout's separator, persisted so an orphan's path reconstructs exactly. `None` for non-prefixed and legacy records.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub layout_separator: Option<String>,
    /// The symlink a linked record's deployment points at; removal deletes the link only while
    /// it still reads this. `None` on copies and legacy linked records.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub link_target: Option<String>,
}

/// Inputs that make a history record's linked-worktree address complete at construction.
pub struct NewHistoryRecord {
    pub worktree_admin_id: String,
    pub mirror_key: String,
    pub cache_git_root: String,
}

/// Borrowed inputs shared by every record-construction site (`deploy_one`, `rebuild_one`).
pub struct NewArtifactRecord<'a> {
    pub key: ArtifactKey,
    pub underlying_source: &'a str,
    pub commit: &'a str,
    pub digest: String,
    pub layout: String,
    pub kind: RecordKind,
    pub allow_symlinks: bool,
    pub preserve_executable: bool,
    pub files: Vec<ManifestFile>,
    pub history: Option<NewHistoryRecord>,
    pub vars_digest: Option<String>,
    pub deploy_root: Option<String>,
    pub layout_separator: Option<String>,
}

impl ArtifactRecord {
    /// The underlying source this record was deployed from; legacy records carry only the key.
    #[must_use]
    pub fn source_name(&self) -> &str {
        if self.source.is_empty() {
            &self.key.source
        } else {
            &self.source
        }
    }

    /// Build a managed (`linked = false`) record, stamping `projected_at` to now.
    #[must_use]
    pub fn projected(p: NewArtifactRecord<'_>) -> Self {
        let NewArtifactRecord {
            key,
            underlying_source,
            commit,
            digest,
            layout,
            kind,
            allow_symlinks,
            preserve_executable,
            files,
            history,
            vars_digest,
            deploy_root,
            layout_separator,
        } = p;
        let (history, worktree_admin_id, mirror_key, cache_git_root) = match history {
            Some(NewHistoryRecord {
                worktree_admin_id,
                mirror_key,
                cache_git_root,
            }) => (
                true,
                Some(worktree_admin_id),
                Some(mirror_key),
                Some(cache_git_root),
            ),
            None => (false, None, None, None),
        };
        Self {
            version: 1,
            key,
            source: underlying_source.to_owned(),
            commit: commit.to_owned(),
            digest,
            projected_at: chrono::Utc::now().to_rfc3339(),
            layout,
            kind,
            allow_symlinks,
            preserve_executable,
            files,
            directories: None,
            linked: false,
            history,
            worktree_admin_id,
            mirror_key,
            cache_git_root,
            vars_digest,
            deploy_root,
            layout_separator,
            link_target: None,
        }
    }
}

/// Directory identity and full-resolution entry-change timestamp.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct DirectoryStamp {
    pub path: PathBuf,
    pub device: u64,
    pub inode: u64,
    pub mtime_secs: i64,
    pub mtime_nanos: i64,
}

impl DirectoryStamp {
    pub(crate) fn new(path: PathBuf, meta: &std::fs::Metadata) -> Self {
        use std::os::unix::fs::MetadataExt as _;
        Self {
            path,
            device: meta.dev(),
            inode: meta.ino(),
            mtime_secs: meta.mtime(),
            mtime_nanos: meta.mtime_nsec(),
        }
    }
}

/// `StateStore` record file entry (carries the content hash used by `phora verify`).
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ManifestFile {
    pub path: PathBuf,
    #[serde(default, skip_serializing_if = "is_file_entry")]
    pub kind: ManifestEntryKind,
    pub size: u64,
    pub mtime: u64,
    pub blake3: String,
}

fn is_file_entry(kind: impl Borrow<ManifestEntryKind>) -> bool {
    matches!(kind.borrow(), ManifestEntryKind::File)
}

pub use crate::sync::model::ScannedFile;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Ejection {
    pub source: String,
    pub artifact: String,
    pub ejected_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HookState {
    pub hook_id: String,
    pub last_success: std::collections::BTreeSet<String>,
}

pub use crate::digest::Digest;

/// `(target, source, artifact)` keys ejected across every target `records` span — lets readers tell a kept-but-ejected record from a managed one.
///
/// # Errors
///
/// Returns an error if the registry cannot be read.
pub fn ejected_index(
    registry: &dyn StateStore,
    records: &[ArtifactRecord],
) -> Result<std::collections::HashSet<(String, String, String)>> {
    let targets: std::collections::BTreeSet<&str> =
        records.iter().map(|r| r.key.target.as_str()).collect();
    let mut index = std::collections::HashSet::new();
    for target in targets {
        for entry in registry.ejections(target)? {
            index.insert((target.to_owned(), entry.source, entry.artifact));
        }
    }
    Ok(index)
}

pub struct FileStateStore {
    pub(super) state_root: PathBuf,
    pub(super) journal_root: PathBuf,
    pub(super) lock_timeout: std::time::Duration,
    pub(super) on_lock_wait: fn(),
}

const META_VERSION: u32 = 1;

#[derive(Serialize, Deserialize)]
struct TargetMeta {
    version: u32,
    #[serde(default)]
    ejected: Vec<Ejection>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    hooks: Vec<HookState>,
}

impl Default for TargetMeta {
    fn default() -> Self {
        Self {
            version: META_VERSION,
            ejected: Vec::new(),
            hooks: Vec::new(),
        }
    }
}

impl FileStateStore {
    pub fn open(state_root: PathBuf) -> Result<Self> {
        let journal_root = state_root.join("locks");
        Ok(Self {
            state_root,
            journal_root,
            lock_timeout: super::locking::DEFAULT_LOCK_TIMEOUT,
            on_lock_wait: || {},
        })
    }

    /// How long `acquire_lock` waits for a held `state.lock`; zero fails at once.
    #[must_use]
    pub fn with_lock_timeout(mut self, lock_timeout: std::time::Duration) -> Self {
        self.lock_timeout = lock_timeout;
        self
    }

    /// Runs `on_lock_wait` once when `acquire_lock` starts waiting for a held `state.lock`.
    #[must_use]
    pub fn on_lock_wait(mut self, on_lock_wait: fn()) -> Self {
        self.on_lock_wait = on_lock_wait;
        self
    }

    #[must_use]
    pub fn state_root(&self) -> &Path {
        &self.state_root
    }

    fn record_path(&self, key: &ArtifactKey) -> PathBuf {
        self.state_root
            .join("targets")
            .join(&key.target)
            .join("artifacts")
            .join(&key.source)
            .join(format!("{}.toml", key.artifact))
    }

    fn meta_path(&self, target: &str) -> PathBuf {
        self.state_root
            .join("targets")
            .join(target)
            .join("meta.toml")
    }

    fn read_meta(&self, target: &str) -> Result<TargetMeta> {
        let path = self.meta_path(target);
        match std::fs::read_to_string(&path) {
            Ok(text) => toml::from_str(&text)
                .map_err(|e| StateError::StateStore(format!("parse meta {}: {e}", path.display()))),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(TargetMeta::default()),
            Err(e) => Err(StateError::StateStore(format!(
                "read meta {}: {e}",
                path.display()
            ))),
        }
    }

    fn write_meta(&self, target: &str, mut meta: TargetMeta) -> Result<()> {
        meta.version = META_VERSION;
        let serialized = toml::to_string(&meta)
            .map_err(|e| StateError::StateStore(format!("serialize meta: {e}")))?;
        atomic_write(&self.meta_path(target), &serialized)
    }

    /// Full-replace helper that can clobber sibling hooks; `record_hook_success` is the safe seam.
    ///
    /// # Errors
    ///
    /// Returns an error if the target meta file cannot be read, parsed, or written.
    #[cfg(test)]
    pub(crate) fn save_hook_state(&self, target: &str, hooks: &[HookState]) -> Result<()> {
        let mut meta = self.read_meta(target)?;
        meta.hooks = hooks.to_vec();
        self.write_meta(target, meta)
    }
}

#[must_use]
pub fn readonly_root_error(root: &Path) -> StateError {
    StateError::ReadOnly(format!(
        "state root {} is read-only: a frozen sync cannot write here",
        root.display()
    ))
}

fn read_record(path: &Path) -> Result<ArtifactRecord> {
    let text = std::fs::read_to_string(path)
        .map_err(|e| StateError::StateStore(format!("read record {}: {e}", path.display())))?;
    toml::from_str(&text)
        .map_err(|e| StateError::StateStore(format!("parse record {}: {e}", path.display())))
}

fn atomic_write(path: &Path, contents: &str) -> Result<()> {
    atomic_write_with(path, contents, fsync_barrier)
}

fn atomic_write_with(
    path: &Path,
    contents: &str,
    sync: impl FnOnce(&std::fs::File) -> std::io::Result<()>,
) -> Result<()> {
    let parent = path
        .parent()
        .ok_or_else(|| StateError::StateStore(format!("path has no parent: {}", path.display())))?;
    std::fs::create_dir_all(parent)
        .map_err(|e| StateError::StateStore(format!("create dir {}: {e}", parent.display())))?;
    let file_name = path.file_name().and_then(|n| n.to_str()).ok_or_else(|| {
        StateError::StateStore(format!("path has no file name: {}", path.display()))
    })?;
    let tmp = parent.join(format!(".{file_name}.tmp"));
    {
        use std::io::Write as _;
        let mut handle = std::fs::File::create(&tmp)
            .map_err(|e| StateError::StateStore(format!("create temp {}: {e}", tmp.display())))?;
        handle
            .write_all(contents.as_bytes())
            .map_err(|e| StateError::StateStore(format!("write temp {}: {e}", tmp.display())))?;
        sync(&handle)
            .map_err(|e| StateError::StateStore(format!("fsync temp {}: {e}", tmp.display())))?;
    }
    std::fs::rename(&tmp, path).map_err(|e| {
        let _ = std::fs::remove_file(&tmp);
        StateError::StateStore(format!(
            "rename {} -> {}: {e}",
            tmp.display(),
            path.display()
        ))
    })
}

fn collect_records(artifacts_dir: &Path, out: &mut Vec<ArtifactRecord>) -> Result<()> {
    let source_dirs = match std::fs::read_dir(artifacts_dir) {
        Ok(rd) => rd,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(e) => {
            return Err(StateError::StateStore(format!(
                "read dir {}: {e}",
                artifacts_dir.display()
            )));
        }
    };
    for source in source_dirs {
        let source = source.map_err(|e| {
            StateError::StateStore(format!("read entry in {}: {e}", artifacts_dir.display()))
        })?;
        if !source.file_type().is_ok_and(|t| t.is_dir()) {
            continue;
        }
        collect_records_under(&source.path(), out)?;
    }
    Ok(())
}

fn collect_records_under(dir: &Path, out: &mut Vec<ArtifactRecord>) -> Result<()> {
    let entries = std::fs::read_dir(dir)
        .map_err(|e| StateError::StateStore(format!("read dir {}: {e}", dir.display())))?;
    for entry in entries {
        let entry = entry
            .map_err(|e| StateError::StateStore(format!("read entry in {}: {e}", dir.display())))?;
        let path = entry.path();
        if entry.file_type().is_ok_and(|t| t.is_dir()) {
            collect_records_under(&path, out)?;
        } else if path.extension().is_some_and(|ext| ext == "toml") {
            out.push(read_record(&path)?);
        }
    }
    Ok(())
}

fn sort_records(records: &mut [ArtifactRecord]) {
    records.sort_by(|a, b| {
        (&a.key.target, &a.key.source, &a.key.artifact).cmp(&(
            &b.key.target,
            &b.key.source,
            &b.key.artifact,
        ))
    });
}

impl StateStore for FileStateStore {
    fn artifact(&self, key: &ArtifactKey) -> Result<Option<ArtifactRecord>> {
        let path = self.record_path(key);
        if path.exists() {
            Ok(Some(read_record(&path)?))
        } else {
            Ok(None)
        }
    }

    fn put_artifact(&self, record: &ArtifactRecord) -> Result<()> {
        let path = self.record_path(&record.key);
        let serialized = toml::to_string(record)
            .map_err(|e| StateError::StateStore(format!("serialize record: {e}")))?;
        atomic_write(&path, &serialized)
    }

    fn put_artifact_journaled(&self, record: &ArtifactRecord, journal_dir: &Path) -> Result<()> {
        #[cfg(target_os = "macos")]
        {
            use std::os::unix::fs::MetadataExt as _;
            let path = self.record_path(&record.key);
            let parent = path.parent().expect("record path has parent");
            std::fs::create_dir_all(parent).map_err(|e| {
                StateError::StateStore(format!("create dir {}: {e}", parent.display()))
            })?;
            // A journal barrier cannot cover another device's cache.
            let same_device = std::fs::metadata(parent)
                .and_then(|record_meta| {
                    std::fs::metadata(journal_dir)
                        .map(|journal_meta| record_meta.dev() == journal_meta.dev())
                })
                .unwrap_or(false);
            if same_device {
                let serialized = toml::to_string(record)
                    .map_err(|e| StateError::StateStore(format!("serialize record: {e}")))?;
                return atomic_write_with(&path, &serialized, super::sync_to_device);
            }
        }
        #[cfg(not(target_os = "macos"))]
        let _ = journal_dir;
        self.put_artifact(record)
    }

    fn remove_artifact(&self, key: &ArtifactKey) -> Result<()> {
        let path = self.record_path(key);
        match std::fs::remove_file(&path) {
            Ok(()) => Ok(()),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(e) => Err(StateError::StateStore(format!(
                "remove record {}: {e}",
                path.display()
            ))),
        }
    }

    fn target_artifacts(&self, target: &str) -> Result<Vec<ArtifactRecord>> {
        let artifacts_dir = self
            .state_root
            .join("targets")
            .join(target)
            .join("artifacts");
        let mut records = Vec::new();
        collect_records(&artifacts_dir, &mut records)?;
        sort_records(&mut records);
        Ok(records)
    }

    fn all_artifacts(&self) -> Result<Vec<ArtifactRecord>> {
        let targets_dir = self.state_root.join("targets");
        let target_dirs = match std::fs::read_dir(&targets_dir) {
            Ok(rd) => rd,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
            Err(e) => {
                return Err(StateError::StateStore(format!(
                    "read dir {}: {e}",
                    targets_dir.display()
                )));
            }
        };
        let mut records = Vec::new();
        for target in target_dirs {
            let target = target.map_err(|e| {
                StateError::StateStore(format!("read entry in {}: {e}", targets_dir.display()))
            })?;
            if !target.file_type().is_ok_and(|t| t.is_dir()) {
                continue;
            }
            collect_records(&target.path().join("artifacts"), &mut records)?;
        }
        sort_records(&mut records);
        Ok(records)
    }

    fn ejections(&self, target: &str) -> Result<Vec<Ejection>> {
        Ok(self.read_meta(target)?.ejected)
    }

    fn save_ejections(&self, target: &str, ejected: &[Ejection]) -> Result<()> {
        let mut meta = self.read_meta(target)?;
        meta.ejected = ejected.to_vec();
        self.write_meta(target, meta)
    }

    fn hook_state(&self, target: &str) -> Result<Vec<HookState>> {
        Ok(self.read_meta(target)?.hooks)
    }

    fn record_hook_success(
        &self,
        target: &str,
        hook_id: &str,
        digest_set: &std::collections::BTreeSet<String>,
    ) -> Result<()> {
        let mut meta = self.read_meta(target)?;
        match meta.hooks.iter_mut().find(|hook| hook.hook_id == hook_id) {
            Some(existing) => existing.last_success.clone_from(digest_set),
            None => meta.hooks.push(HookState {
                hook_id: hook_id.to_owned(),
                last_success: digest_set.clone(),
            }),
        }
        self.write_meta(target, meta)
    }

    fn acquire_lock(&self) -> Result<StateLock> {
        self.acquire_state_lock()
    }

    fn journal_root(&self) -> PathBuf {
        self.journal_root.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sync::state::ProjectId;
    use std::time::{Duration, Instant};
    use tempfile::TempDir;

    #[test]
    fn failed_flush_does_not_publish_the_new_record() {
        let dir = TempDir::new().expect("state");
        let path = dir.path().join("record.toml");
        std::fs::write(&path, "old record").expect("seed");
        let result = atomic_write_with(&path, "new record", |file| {
            assert_eq!(file.metadata()?.len(), 10);
            assert_eq!(std::fs::read_to_string(&path)?, "old record");
            Err(std::io::Error::other("injected flush failure"))
        });
        assert!(
            result
                .expect_err("flush must fail")
                .to_string()
                .contains("injected flush failure")
        );
        assert_eq!(std::fs::read_to_string(&path).expect("read"), "old record");
    }

    #[test]
    fn digest_requires_strict_sixty_four_hex_body() {
        use std::str::FromStr as _;
        let hex = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
        assert!(
            Digest::from_str(&format!("blake3:{hex}")).is_ok(),
            "a strict 64-hex blake3 body must parse"
        );
        assert!(
            Digest::from_str(&format!("sha256:{hex}")).is_ok(),
            "the unified Digest now also accepts sha256"
        );
        assert!(
            Digest::from_str("blake3:abc").is_err(),
            "a short body must be rejected (the unified Digest is strict)"
        );
        assert!(
            Digest::from_str("blake3:").is_err(),
            "an empty body must be rejected"
        );
    }

    // ── linked marker (DLD-005) ────────────────────────────────────

    /// A linked record carries no files and sentinel commit/digest; it must survive a
    /// TOML round-trip with `linked = true` intact and the empty `files` preserved.
    #[test]
    fn linked_record_round_trips_with_sentinels_and_empty_files() {
        let rec = ArtifactRecord {
            version: 1,
            key: ArtifactKey {
                target: "vscode".to_owned(),
                source: "local-overlay".to_owned(),
                artifact: "snippets".to_owned(),
            },
            source: "local-overlay".to_owned(),
            commit: "link".to_owned(),
            digest: "link:".to_owned(),
            projected_at: "2026-06-08T12:00:00Z".to_owned(),
            layout: "flat".to_owned(),
            kind: RecordKind::Dir,
            allow_symlinks: false,
            preserve_executable: true,
            files: vec![],
            directories: None,
            linked: true,
            history: false,
            worktree_admin_id: None,
            mirror_key: None,
            cache_git_root: None,
            vars_digest: None,
            deploy_root: None,
            layout_separator: None,
            link_target: None,
        };

        let toml = toml::to_string(&rec).expect("serialize linked record");
        let back: ArtifactRecord = toml::from_str(&toml).expect("deserialize linked record");

        assert_eq!(
            back, rec,
            "a linked record must round-trip field-for-field through TOML"
        );
        assert!(back.linked, "linked flag must survive serde");
        assert!(
            back.files.is_empty(),
            "a linked record carries no manifest files"
        );
        assert_eq!(back.commit, "link", "sentinel commit must round-trip");
        assert_eq!(back.digest, "link:", "sentinel digest must round-trip");
    }

    /// Records written before the linked marker existed have no `linked` key; serde
    /// `#[serde(default)]` must deserialize them with `linked = false` (back-compat).
    #[test]
    fn record_without_linked_field_deserializes_as_not_linked() {
        let legacy = r#"
version = 1
commit = "def456789abc123"
digest = "blake3:d4e5f6"
projected_at = "2026-01-31T12:34:56Z"
layout = "flat"
allow_symlinks = false
preserve_executable = true
files = []

[key]
target = "vscode"
source = "company-configs"
artifact = "snippets"
"#;

        let rec: ArtifactRecord =
            toml::from_str(legacy).expect("legacy record without `linked` must still parse");

        assert!(
            !rec.linked,
            "a record predating the linked marker must default to linked = false"
        );
    }

    // ── underlying source field (PBR-004) ─────────────────────────

    /// An aliased binding keys `key.source` by IDENTITY (the `as`) but must record
    /// the UNDERLYING source name in the new `source` field. Both must survive a
    /// TOML round-trip independently so `rebuild-registry` can reconstruct provenance.
    #[test]
    fn record_round_trips_underlying_source_distinct_from_identity() {
        let rec = ArtifactRecord {
            version: 1,
            key: ArtifactKey {
                target: "dest".to_owned(),
                source: "nvim".to_owned(),
                artifact: "init".to_owned(),
            },
            source: "dotfiles".to_owned(),
            commit: "def456789abc123".to_owned(),
            digest: "blake3:d4e5f6".to_owned(),
            projected_at: "2026-01-31T12:34:56Z".to_owned(),
            layout: "by-source".to_owned(),
            kind: RecordKind::Dir,
            allow_symlinks: false,
            preserve_executable: true,
            files: vec![],
            directories: None,
            linked: false,
            history: false,
            worktree_admin_id: None,
            mirror_key: None,
            cache_git_root: None,
            vars_digest: None,
            deploy_root: None,
            layout_separator: None,
            link_target: None,
        };

        let toml = toml::to_string(&rec).expect("serialize aliased record");
        let back: ArtifactRecord = toml::from_str(&toml).expect("deserialize aliased record");

        assert_eq!(
            back, rec,
            "an aliased record must round-trip field-for-field through TOML"
        );
        assert_eq!(
            back.key.source, "nvim",
            "key.source carries the binding IDENTITY (the `as`)"
        );
        assert_eq!(
            back.source, "dotfiles",
            "the new `source` field carries the UNDERLYING source name, distinct from identity"
        );
    }

    /// Records written before the `source` field existed have no `source` key; serde
    /// `#[serde(default)]` must deserialize them with an empty source (back-compat).
    #[test]
    fn record_without_source_field_deserializes_with_default_source() {
        let legacy = r#"
version = 1
commit = "def456789abc123"
digest = "blake3:d4e5f6"
projected_at = "2026-01-31T12:34:56Z"
layout = "flat"
allow_symlinks = false
preserve_executable = true
files = []

[key]
target = "vscode"
source = "company-configs"
artifact = "snippets"
"#;

        let rec: ArtifactRecord =
            toml::from_str(legacy).expect("legacy record without `source` must still parse");

        assert_eq!(
            rec.source, "",
            "a record predating the underlying-source field must default to an empty `source`"
        );
    }

    // ── record kind: file vs dir (SMR-001) ─────────────────────────

    #[test]
    fn record_kind_defaults_to_dir() {
        assert_eq!(
            RecordKind::default(),
            RecordKind::Dir,
            "an unspecified record kind must default to a directory tree (the legacy shape)"
        );
    }

    #[test]
    fn record_without_kind_field_deserializes_as_dir() {
        let legacy = r#"
version = 1
commit = "def456789abc123"
digest = "blake3:d4e5f6"
projected_at = "2026-01-31T12:34:56Z"
layout = "flat"
allow_symlinks = false
preserve_executable = true
files = []

[key]
target = "vscode"
source = "company-configs"
artifact = "snippets"
"#;

        let rec: ArtifactRecord =
            toml::from_str(legacy).expect("legacy record without `kind` must still parse");

        assert_eq!(
            rec.kind,
            RecordKind::Dir,
            "a record predating the kind field must default to RecordKind::Dir"
        );
    }

    #[test]
    fn file_kind_record_round_trips_as_lowercase_file() {
        let rec = ArtifactRecord {
            version: 1,
            key: ArtifactKey {
                target: "dest".to_owned(),
                source: "agents-src".to_owned(),
                artifact: "CLAUDE.md".to_owned(),
            },
            source: "agents-src".to_owned(),
            commit: "def456789abc123".to_owned(),
            digest: "blake3:d4e5f6".to_owned(),
            projected_at: "2026-01-31T12:34:56Z".to_owned(),
            layout: "flat".to_owned(),
            kind: RecordKind::File,
            allow_symlinks: false,
            preserve_executable: true,
            files: vec![],
            directories: None,
            linked: false,
            history: false,
            worktree_admin_id: None,
            mirror_key: None,
            cache_git_root: None,
            vars_digest: None,
            deploy_root: None,
            layout_separator: None,
            link_target: None,
        };

        let toml = toml::to_string(&rec).expect("serialize file-kind record");
        assert!(
            toml.contains("kind = \"file\""),
            "a file-kind record must serialize the lowercase tag `kind = \"file\"`, got:\n{toml}"
        );

        let back: ArtifactRecord = toml::from_str(&toml).expect("deserialize file-kind record");
        assert_eq!(
            back.kind,
            RecordKind::File,
            "a file-kind record must round-trip its kind through serde"
        );
        assert_eq!(
            back, rec,
            "a file-kind record must round-trip field-for-field"
        );
    }

    #[test]
    fn dir_kind_record_serializes_as_lowercase_dir() {
        let rec = ArtifactRecord {
            version: 1,
            key: ArtifactKey {
                target: "dest".to_owned(),
                source: "dotfiles".to_owned(),
                artifact: "nvim".to_owned(),
            },
            source: "dotfiles".to_owned(),
            commit: "def456789abc123".to_owned(),
            digest: "blake3:d4e5f6".to_owned(),
            projected_at: "2026-01-31T12:34:56Z".to_owned(),
            layout: "by-source".to_owned(),
            kind: RecordKind::Dir,
            allow_symlinks: false,
            preserve_executable: true,
            files: vec![],
            directories: None,
            linked: false,
            history: false,
            worktree_admin_id: None,
            mirror_key: None,
            cache_git_root: None,
            vars_digest: None,
            deploy_root: None,
            layout_separator: None,
            link_target: None,
        };

        let toml = toml::to_string(&rec).expect("serialize dir-kind record");
        assert!(
            toml.contains("kind = \"dir\""),
            "a dir-kind record must serialize the lowercase tag `kind = \"dir\"`, got:\n{toml}"
        );

        let back: ArtifactRecord = toml::from_str(&toml).expect("deserialize dir-kind record");
        assert_eq!(
            back.kind,
            RecordKind::Dir,
            "a dir-kind record must round-trip its kind through serde"
        );
    }

    #[test]
    fn projected_threads_file_kind_from_projected_record() {
        let projected = NewArtifactRecord {
            key: ArtifactKey {
                target: "dest".to_owned(),
                source: "agents-src".to_owned(),
                artifact: "CLAUDE.md".to_owned(),
            },
            underlying_source: "agents-src",
            commit: "def456789abc123",
            digest: "blake3:d4e5f6".to_owned(),
            layout: "flat".to_owned(),
            kind: RecordKind::File,
            allow_symlinks: false,
            preserve_executable: true,
            files: vec![],
            history: None,
            vars_digest: None,
            deploy_root: None,
            layout_separator: None,
        };

        let rec = ArtifactRecord::projected(projected);

        assert_eq!(
            rec.kind,
            RecordKind::File,
            "projected() must carry the kind from the NewArtifactRecord verbatim"
        );
    }

    // ── per-artifact vars digest (TPH-010) ─────────────────────────

    fn vars_digest_record(vars_digest: Option<&str>) -> ArtifactRecord {
        ArtifactRecord {
            version: 1,
            key: ArtifactKey {
                target: "vscode".to_owned(),
                source: "company-configs".to_owned(),
                artifact: "snippets".to_owned(),
            },
            source: "company-configs".to_owned(),
            commit: "def456789abc123".to_owned(),
            digest: "blake3:d4e5f6".to_owned(),
            projected_at: "2026-01-31T12:34:56Z".to_owned(),
            layout: "flat".to_owned(),
            kind: RecordKind::Dir,
            allow_symlinks: false,
            preserve_executable: true,
            files: vec![],
            directories: None,
            linked: false,
            history: false,
            worktree_admin_id: None,
            mirror_key: None,
            cache_git_root: None,
            vars_digest: vars_digest.map(str::to_owned),
            deploy_root: None,
            layout_separator: None,
            link_target: None,
        }
    }

    /// INV-8 (byte-stability): a feature-free record (rendered no template, so
    /// `vars_digest` is None) must serialize with NO `vars_digest` key, byte-identical
    /// to the pre-feature format.
    #[test]
    fn feature_free_record_serializes_without_vars_digest_key() {
        let rec = vars_digest_record(None);

        let toml = toml::to_string(&rec).expect("serialize feature-free record");

        assert!(
            !toml.contains("vars_digest"),
            "a record whose vars_digest is None must omit the key entirely (skip_serializing_if), \
             so feature-free records stay byte-identical to the pre-feature format (INV-8), got:\n{toml}"
        );

        let back: ArtifactRecord = toml::from_str(&toml).expect("deserialize feature-free record");
        assert_eq!(
            back, rec,
            "a None vars_digest must round-trip field-for-field through TOML"
        );
        assert_eq!(
            back.vars_digest, None,
            "a record with no vars_digest key must deserialize back to None"
        );
    }

    /// A templated record carries a `vars_digest`; the key must serialize and round-trip.
    #[test]
    fn templated_record_round_trips_vars_digest() {
        let rec = vars_digest_record(Some("blake3:abc123"));

        let toml = toml::to_string(&rec).expect("serialize templated record");

        assert!(
            toml.contains("vars_digest"),
            "a record whose vars_digest is Some(..) must serialize the key, got:\n{toml}"
        );

        let back: ArtifactRecord = toml::from_str(&toml).expect("deserialize templated record");
        assert_eq!(
            back, rec,
            "a Some(vars_digest) record must round-trip field-for-field through TOML"
        );
        assert_eq!(
            back.vars_digest.as_deref(),
            Some("blake3:abc123"),
            "the vars_digest value must survive serde"
        );
    }

    /// Records written before the vars-digest field existed have no `vars_digest` key;
    /// serde `#[serde(default)]` must deserialize them as None (back-compat).
    #[test]
    fn record_without_vars_digest_field_deserializes_as_none() {
        let legacy = r#"
version = 1
commit = "def456789abc123"
digest = "blake3:d4e5f6"
projected_at = "2026-01-31T12:34:56Z"
layout = "flat"
allow_symlinks = false
preserve_executable = true
files = []

[key]
target = "vscode"
source = "company-configs"
artifact = "snippets"
"#;

        let rec: ArtifactRecord =
            toml::from_str(legacy).expect("legacy record without `vars_digest` must still parse");

        assert_eq!(
            rec.vars_digest, None,
            "a record predating the vars-digest field must default to None"
        );
    }

    // ── persisted deploy root (CLIFF-DEPLOYROOT-007) ───────────────

    /// A record must persist the target's expanded absolute deploy root so an
    /// orphaned record (its config `Target` gone) stays locatable; the field
    /// and its value must survive a TOML round-trip.
    #[test]
    fn record_persists_deploy_root_through_toml_round_trip() {
        let stored = r#"
version = 1
source = "nvim-src"
commit = "def456789abc123"
digest = "blake3:d4e5f6"
projected_at = "2026-01-31T12:34:56Z"
layout = "by-source"
allow_symlinks = false
preserve_executable = true
files = []
deploy_root = "/home/alice/.config/nvim"

[key]
target = "home"
source = "nvim"
artifact = "init"
"#;

        let rec: ArtifactRecord =
            toml::from_str(stored).expect("a record carrying deploy_root must deserialize");
        let round_tripped = toml::to_string(&rec).expect("re-serialize record");

        assert!(
            round_tripped.contains("deploy_root"),
            "a record's persisted deploy_root must survive a TOML round-trip (the field is dropped \
             until CLIFF-DEPLOYROOT-007 adds it), got:\n{round_tripped}"
        );
        assert!(
            round_tripped.contains("/home/alice/.config/nvim"),
            "the expanded absolute deploy root value must survive the round-trip, got:\n{round_tripped}"
        );
    }

    #[test]
    fn deploy_root_snapshots_targets_expanded_path() {
        let target = crate::config::Config::parse(
            "version = 1\n\n[targets.home]\npath = \"~/.config/nvim\"\n",
        )
        .expect("minimal config parses")
        .targets
        .remove("home")
        .expect("target `home` present");
        let expanded = target.expanded_path();
        let expanded_str = expanded.to_string_lossy().into_owned();
        assert!(
            expanded.is_absolute() && !expanded_str.contains('~'),
            "premise: a `~/`-target must expand to an absolute tilde-free path (home resolved), got {expanded_str}"
        );
        assert_ne!(
            expanded_str, "~/.config/nvim",
            "premise: expanded_path must actually expand the tilde, not echo the raw config path"
        );

        let stored = format!(
            "version = 1\n\
             source = \"nvim-src\"\n\
             commit = \"def456789abc123\"\n\
             digest = \"blake3:d4e5f6\"\n\
             projected_at = \"2026-01-31T12:34:56Z\"\n\
             layout = \"by-source\"\n\
             allow_symlinks = false\n\
             preserve_executable = true\n\
             files = []\n\
             deploy_root = \"{expanded_str}\"\n\n\
             [key]\n\
             target = \"home\"\n\
             source = \"nvim\"\n\
             artifact = \"init\"\n"
        );

        let rec: ArtifactRecord =
            toml::from_str(&stored).expect("record with expanded deploy_root must deserialize");
        let round_tripped = toml::to_string(&rec).expect("re-serialize record");
        let value: toml::Value =
            toml::from_str(&round_tripped).expect("re-parse serialized record as a table");

        let persisted = value
            .get("deploy_root")
            .and_then(toml::Value::as_str)
            .expect("re-serialized record must expose a deploy_root string");
        assert_eq!(
            persisted, expanded_str,
            "the persisted deploy root must equal the target's expanded absolute path (post tilde expansion)"
        );
    }

    /// Records written before the deploy-root field existed have no
    /// `deploy_root` key; adding the field must not break them (additive, no
    /// migration) — a legacy record must still deserialize cleanly.
    #[test]
    fn legacy_record_without_deploy_root_still_loads() {
        let legacy = r#"
version = 1
commit = "def456789abc123"
digest = "blake3:d4e5f6"
projected_at = "2026-01-31T12:34:56Z"
layout = "flat"
allow_symlinks = false
preserve_executable = true
files = []

[key]
target = "vscode"
source = "company-configs"
artifact = "snippets"
"#;

        let rec: ArtifactRecord =
            toml::from_str(legacy).expect("legacy record without `deploy_root` must still parse");

        assert_eq!(
            rec.key.artifact, "snippets",
            "a record predating the deploy-root field must load with its other fields intact"
        );
    }

    // ── network-filesystem lock advisory (CLIFF-NFSDOC-006) ────────

    #[test]
    fn known_network_fstype_yields_a_single_line_lock_advisory() {
        for fstype in ["nfs", "smbfs", "cifs"] {
            let advisory = network_lock_advisory(fstype).unwrap_or_else(|| {
                panic!("a known network fstype ({fstype}) must yield a lock advisory")
            });
            let lower = advisory.to_lowercase();
            assert!(
                lower.contains("lock"),
                "the {fstype} advisory must be about locking, got: {advisory:?}"
            );
            assert!(
                lower.contains("network") || lower.contains("nfs") || lower.contains("smb"),
                "the {fstype} advisory must name the network-filesystem limitation, got: {advisory:?}"
            );
            assert!(
                !advisory.trim_end().contains('\n'),
                "the advisory must be a single line, got: {advisory:?}"
            );
        }
    }

    #[test]
    fn local_fstype_yields_no_lock_advisory() {
        for fstype in ["apfs", "ext4", "xfs", "btrfs", "tmpfs"] {
            assert_eq!(
                network_lock_advisory(fstype),
                None,
                "a local fstype ({fstype}) must not trigger the network lock advisory"
            );
        }
    }

    #[test]
    fn local_temp_dir_is_not_falsely_flagged_as_network() {
        let dir = TempDir::new().expect("temp state root");
        assert!(
            !is_network_fs(dir.path()),
            "the real detection call on a real local path must not misfire — the local temp dir \
             every test uses must never be classified as a network filesystem"
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn unescape_octal_reassembles_multibyte_utf8_mount_points() {
        assert_eq!(
            unescape_octal(r"/mnt/caf\303\251"),
            "/mnt/café",
            "octal-escaped multi-byte UTF-8 bytes must reassemble, not decode byte-by-byte as Latin-1"
        );
        assert_eq!(
            unescape_octal(r"/mnt/space\040dir"),
            "/mnt/space dir",
            "single-byte ASCII escapes must still round-trip"
        );
    }

    fn record(target: &str, source: &str, artifact: &str) -> ArtifactRecord {
        ArtifactRecord {
            version: 1,
            key: ArtifactKey {
                target: target.to_owned(),
                source: source.to_owned(),
                artifact: artifact.to_owned(),
            },
            source: source.to_owned(),
            commit: "def456789abc123".to_owned(),
            digest: "blake3:d4e5f6".to_owned(),
            projected_at: "2026-01-31T12:34:56Z".to_owned(),
            layout: "flat".to_owned(),
            kind: RecordKind::Dir,
            allow_symlinks: false,
            preserve_executable: true,
            files: vec![ManifestFile {
                path: PathBuf::from("python.json"),
                kind: crate::sync::state::ManifestEntryKind::File,
                size: 12345,
                mtime: 1_738_329_296,
                blake3: "9e8d7c6b5a4f3e2d".to_owned(),
            }],
            directories: None,
            linked: false,
            history: false,
            worktree_admin_id: None,
            mirror_key: None,
            cache_git_root: None,
            vars_digest: None,
            deploy_root: None,
            layout_separator: None,
            link_target: None,
        }
    }

    fn registry() -> (TempDir, FileStateStore) {
        let dir = TempDir::new().expect("temp state root");
        let reg = FileStateStore::open(dir.path().to_path_buf()).expect("open registry");
        (dir, reg)
    }

    // project_id

    #[test]
    fn project_id_is_blake3_of_canonical_root_first_sixteen_hex() {
        let dir = TempDir::new().expect("temp project root");
        let canonical = dir.path().canonicalize().expect("canonicalize root");
        let expected = blake3::hash(canonical.to_string_lossy().as_bytes());

        let id = ProjectId::for_path(dir.path()).expect("project id");

        assert_eq!(
            id.as_str(),
            &expected.to_hex()[..16],
            "project id must be the first 16 hex chars of blake3(canonical root)"
        );
    }

    #[test]
    fn project_id_is_deterministic_for_same_canonical_path() {
        let dir = TempDir::new().expect("temp project root");

        let first = ProjectId::for_path(dir.path()).expect("first id");
        let second = ProjectId::for_path(dir.path()).expect("second id");

        assert_eq!(first, second, "same canonical path => same project id");
    }

    // put / get / remove

    #[test]
    fn get_on_absent_key_is_none() {
        let (_dir, reg) = registry();
        let key = ArtifactKey {
            target: "vscode".to_owned(),
            source: "company-configs".to_owned(),
            artifact: "snippets".to_owned(),
        };

        let got = reg
            .artifact(&key)
            .expect("get must not error on absent key");

        assert!(got.is_none(), "absent key yields Ok(None)");
    }

    #[test]
    fn put_then_get_round_trips_the_record() {
        let (_dir, reg) = registry();
        let rec = record("vscode", "company-configs", "snippets");

        reg.put_artifact(&rec).expect("put record");
        let got = reg
            .artifact(&rec.key)
            .expect("get record")
            .expect("record present");

        assert_eq!(got, rec, "get must return the exact record that was put");
    }

    #[test]
    fn put_writes_record_at_target_source_artifact_path() {
        let (dir, reg) = registry();
        let rec = record("vscode", "company-configs", "snippets");

        reg.put_artifact(&rec).expect("put record");

        let expected = dir
            .path()
            .join("targets")
            .join("vscode")
            .join("artifacts")
            .join("company-configs")
            .join("snippets.toml");
        assert!(
            expected.is_file(),
            "record must land at <root>/targets/<target>/artifacts/<source>/<artifact>.toml, expected {}",
            expected.display()
        );
        assert_eq!(
            reg.artifact(&rec.key)
                .expect("get record")
                .expect("record present"),
            rec,
            "the record written at that path must round-trip back through get"
        );
    }

    #[test]
    fn put_creates_missing_parent_directories() {
        let (dir, reg) = registry();
        assert!(
            !dir.path().join("targets").exists(),
            "targets dir absent before first put (premise)"
        );
        let rec = record("vscode", "company-configs", "snippets");

        reg.put_artifact(&rec).expect("put must create parent dirs");

        let expected = dir
            .path()
            .join("targets")
            .join("vscode")
            .join("artifacts")
            .join("company-configs")
            .join("snippets.toml");
        assert!(
            expected.is_file(),
            "put must create the full parent chain and write the file at {}",
            expected.display()
        );
        assert_eq!(
            reg.artifact(&rec.key)
                .expect("get record")
                .expect("record present"),
            rec,
            "record written into freshly created dirs must round-trip"
        );
    }

    #[test]
    fn remove_deletes_the_record() {
        let (_dir, reg) = registry();
        let rec = record("vscode", "company-configs", "snippets");
        reg.put_artifact(&rec).expect("put record");

        reg.remove_artifact(&rec.key).expect("remove record");

        assert!(
            reg.artifact(&rec.key).expect("get after remove").is_none(),
            "removed record must no longer be found"
        );
    }

    #[test]
    fn put_leaves_no_temp_file() {
        let (dir, reg) = registry();

        reg.put_artifact(&record("vscode", "company-configs", "snippets"))
            .expect("put record");

        let artifact_dir = dir
            .path()
            .join("targets")
            .join("vscode")
            .join("artifacts")
            .join("company-configs");
        let entries: Vec<PathBuf> = std::fs::read_dir(&artifact_dir)
            .expect("artifact dir must exist after put")
            .map(|e| e.expect("dir entry").path())
            .collect();

        assert_eq!(
            entries,
            vec![artifact_dir.join("snippets.toml")],
            "atomic write must leave only <artifact>.toml — no temp/.tmp leftover, found {entries:?}"
        );
    }

    // list_target / list_all

    fn contains_artifact(records: &[ArtifactRecord], source: &str, artifact: &str) -> bool {
        records.iter().any(|r| {
            r.key.source == source && r.key.artifact == artifact && r.commit == "def456789abc123"
        })
    }

    #[test]
    fn list_target_returns_only_records_under_that_target() {
        let (_dir, reg) = registry();
        reg.put_artifact(&record("vscode", "company-configs", "snippets"))
            .expect("put a");
        reg.put_artifact(&record("vscode", "dotfiles", "settings"))
            .expect("put b");
        reg.put_artifact(&record("nvim", "dotfiles", "init"))
            .expect("put c");

        let vscode = reg.target_artifacts("vscode").expect("list vscode");

        assert_eq!(vscode.len(), 2, "two records under vscode");
        assert!(
            vscode.iter().all(|r| r.key.target == "vscode"),
            "list_target must not leak other targets"
        );
        assert!(
            contains_artifact(&vscode, "company-configs", "snippets"),
            "vscode list must contain company-configs/snippets"
        );
        assert!(
            contains_artifact(&vscode, "dotfiles", "settings"),
            "vscode list must contain dotfiles/settings"
        );
        assert!(
            !contains_artifact(&vscode, "dotfiles", "init"),
            "vscode list must exclude the nvim-only dotfiles/init record"
        );
    }

    #[test]
    fn list_target_on_absent_target_is_empty() {
        let (_dir, reg) = registry();

        let records = reg
            .target_artifacts("never-projected")
            .expect("listing an absent target must not error");

        assert_eq!(records, vec![], "absent target dir => empty record list");
    }

    #[test]
    fn list_all_returns_records_across_all_targets() {
        let (_dir, reg) = registry();
        reg.put_artifact(&record("vscode", "company-configs", "snippets"))
            .expect("put vscode");
        reg.put_artifact(&record("nvim", "dotfiles", "init"))
            .expect("put nvim");

        let all = reg.all_artifacts().expect("list all");

        assert_eq!(all.len(), 2, "records from every target appear");
        assert!(
            all.iter().any(|r| r.key.target == "vscode"
                && r.key.source == "company-configs"
                && r.key.artifact == "snippets"),
            "vscode company-configs/snippets present in list_all"
        );
        assert!(
            all.iter().any(|r| r.key.target == "nvim"
                && r.key.source == "dotfiles"
                && r.key.artifact == "init"),
            "nvim dotfiles/init present in list_all"
        );
    }

    #[test]
    fn list_target_orders_records_by_source_then_artifact() {
        let (_dir, reg) = registry();
        reg.put_artifact(&record("home", "second", "COPY.md"))
            .expect("put second");
        reg.put_artifact(&record("home", "dotfiles", "READER.md"))
            .expect("put dotfiles");

        let keys: Vec<(String, String)> = reg
            .target_artifacts("home")
            .expect("list home")
            .into_iter()
            .map(|r| (r.key.source, r.key.artifact))
            .collect();

        assert_eq!(
            keys,
            vec![
                ("dotfiles".to_owned(), "READER.md".to_owned()),
                ("second".to_owned(), "COPY.md".to_owned()),
            ],
            "list_target must order by (source, artifact), independent of filesystem read_dir order"
        );
    }

    #[test]
    fn list_all_orders_records_by_target_then_source_then_artifact() {
        let (_dir, reg) = registry();
        reg.put_artifact(&record("nvim", "dotfiles", "init"))
            .expect("put nvim");
        reg.put_artifact(&record("home", "second", "COPY.md"))
            .expect("put home second");
        reg.put_artifact(&record("home", "dotfiles", "READER.md"))
            .expect("put home dotfiles");

        let keys: Vec<(String, String, String)> = reg
            .all_artifacts()
            .expect("list all")
            .into_iter()
            .map(|r| (r.key.target, r.key.source, r.key.artifact))
            .collect();

        assert_eq!(
            keys,
            vec![
                (
                    "home".to_owned(),
                    "dotfiles".to_owned(),
                    "READER.md".to_owned()
                ),
                ("home".to_owned(), "second".to_owned(), "COPY.md".to_owned()),
                ("nvim".to_owned(), "dotfiles".to_owned(), "init".to_owned()),
            ],
            "list_all must order by (target, source, artifact), independent of read_dir order"
        );
    }

    // ejected meta

    #[test]
    fn load_ejected_on_missing_meta_is_empty() {
        let (_dir, reg) = registry();

        let ejected = reg
            .ejections("vscode")
            .expect("missing meta must not error");

        assert!(ejected.is_empty(), "no meta file => empty ejected list");
    }

    #[test]
    fn save_then_load_ejected_round_trips() {
        let (_dir, reg) = registry();
        let entries = vec![
            Ejection {
                source: "company-configs".to_owned(),
                artifact: "snippets".to_owned(),
                ejected_at: "2026-01-31T14:00:00Z".to_owned(),
            },
            Ejection {
                source: "dotfiles".to_owned(),
                artifact: "old-config".to_owned(),
                ejected_at: "2026-01-30T10:00:00Z".to_owned(),
            },
        ];

        reg.save_ejections("vscode", &entries)
            .expect("save ejected");
        let loaded = reg.ejections("vscode").expect("load ejected");

        assert_eq!(
            loaded, entries,
            "load_ejected must return every saved entry, in order, field-for-field"
        );
    }

    #[test]
    fn save_ejected_writes_meta_at_target_path() {
        let (dir, reg) = registry();
        let entries = vec![Ejection {
            source: "company-configs".to_owned(),
            artifact: "snippets".to_owned(),
            ejected_at: "2026-01-31T14:00:00Z".to_owned(),
        }];

        reg.save_ejections("vscode", &entries)
            .expect("save ejected");

        let expected = dir.path().join("targets").join("vscode").join("meta.toml");
        assert!(
            expected.is_file(),
            "ejected meta must land at <root>/targets/<target>/meta.toml, expected {}",
            expected.display()
        );
    }

    // state.lock

    #[test]
    fn lock_exclusive_succeeds_when_unheld() {
        let (_dir, reg) = registry();

        let guard = reg.acquire_lock();

        assert!(guard.is_ok(), "first exclusive lock must succeed");
    }

    #[test]
    fn lock_exclusive_creates_lock_file_at_locks_state_lock() {
        let (dir, reg) = registry();

        let _held = reg.acquire_lock().expect("first lock acquired");

        let expected = dir.path().join("locks").join("state.lock");
        assert!(
            expected.is_file(),
            "lock_exclusive must create <root>/locks/state.lock, expected {}",
            expected.display()
        );
    }

    #[test]
    fn second_exclusive_lock_fails_while_first_held() {
        let dir = TempDir::new().expect("temp state root");
        let first = FileStateStore::open(dir.path().to_path_buf()).expect("open first registry");
        let second = FileStateStore::open(dir.path().to_path_buf())
            .expect("open second registry")
            .with_lock_timeout(Duration::ZERO);

        let _held = first
            .acquire_lock()
            .expect("first instance acquires the lock");

        let blocked = second.acquire_lock();

        let err = blocked.expect_err(
            "a second FileStateStore on the same state_root must fail to lock while the first holds it",
        );
        let msg = err.to_string();
        assert!(
            msg.contains("phora") && (msg.contains("state.lock") || msg.contains("lock held")),
            "lock-held error must mention another phora process / state.lock, got: {msg}"
        );
    }

    #[test]
    fn lock_is_released_after_guard_dropped() {
        let _serial = STATE_LOCK_SERIAL
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let dir = TempDir::new().expect("temp state root");
        let first = FileStateStore::open(dir.path().to_path_buf()).expect("open first registry");
        let second = FileStateStore::open(dir.path().to_path_buf()).expect("open second registry");

        {
            let _held = first
                .acquire_lock()
                .expect("first instance acquires the lock");
        }

        let reacquired = second.acquire_lock();

        assert!(
            reacquired.is_ok(),
            "dropping the guard must release the OS lock so another instance can acquire it, got: {:?}",
            reacquired.err()
        );
    }

    #[test]
    fn contended_lock_is_acquired_once_the_holder_releases_it() {
        let _serial = STATE_LOCK_SERIAL
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let dir = TempDir::new().expect("temp state root");
        let first = FileStateStore::open(dir.path().to_path_buf()).expect("open first registry");
        let second = FileStateStore::open(dir.path().to_path_buf())
            .expect("open second registry")
            .with_lock_timeout(Duration::from_secs(5));
        let (held_tx, held_rx) = std::sync::mpsc::channel();

        let holder = std::thread::spawn(move || {
            let guard = first.acquire_lock().expect("holder acquires the lock");
            held_tx.send(()).expect("signal held");
            std::thread::sleep(Duration::from_millis(200));
            drop(guard);
        });
        held_rx.recv().expect("holder holds the lock");
        let started = Instant::now();
        let acquired = second.acquire_lock();
        let waited = started.elapsed();
        holder.join().expect("holder thread");

        assert!(
            acquired.is_ok(),
            "a waiting acquisition must succeed once the holder releases, got: {:?}",
            acquired.err()
        );
        assert!(
            waited >= Duration::from_millis(100) && waited < Duration::from_secs(5),
            "acquisition must wait for the release, not the deadline; waited {waited:?}"
        );
    }

    #[test]
    fn contended_lock_gives_up_at_the_deadline() {
        let dir = TempDir::new().expect("temp state root");
        let first = FileStateStore::open(dir.path().to_path_buf()).expect("open first registry");
        let second = FileStateStore::open(dir.path().to_path_buf())
            .expect("open second registry")
            .with_lock_timeout(Duration::from_millis(300));
        let _held = first
            .acquire_lock()
            .expect("first instance acquires the lock");

        let started = Instant::now();
        let err = second
            .acquire_lock()
            .expect_err("a lock held past the deadline must not be acquired");
        let waited = started.elapsed();

        assert!(
            matches!(&err, StateError::Lock(msg) if msg.contains("state.lock held")),
            "deadline expiry must be the contended-lock error, got: {err:?}"
        );
        assert!(
            waited >= Duration::from_millis(300) && waited < Duration::from_secs(2),
            "acquisition must give up at roughly the deadline; waited {waited:?}"
        );
    }

    #[test]
    fn zero_lock_timeout_fails_without_waiting() {
        let dir = TempDir::new().expect("temp state root");
        let first = FileStateStore::open(dir.path().to_path_buf()).expect("open first registry");
        let second = FileStateStore::open(dir.path().to_path_buf())
            .expect("open second registry")
            .with_lock_timeout(Duration::ZERO);
        let _held = first
            .acquire_lock()
            .expect("first instance acquires the lock");

        let started = Instant::now();
        let err = second
            .acquire_lock()
            .expect_err("a zero timeout must not acquire a held lock");
        let waited = started.elapsed();

        assert_eq!(
            err.to_string(),
            StateError::Lock(
                "another phora process is running for this project (state.lock held)".to_owned()
            )
            .to_string(),
            "a zero timeout keeps the fail-fast message"
        );
        assert!(
            waited < Duration::from_millis(50),
            "a zero timeout must fail before the first backoff; waited {waited:?}"
        );
    }

    // ── per-hook last-success digest-set (TPH-002) ─────────────────

    fn digest_set(digests: &[&str]) -> std::collections::BTreeSet<String> {
        digests.iter().map(|d| (*d).to_owned()).collect()
    }

    /// A hook's last-success record is the set of artifact digests the target
    /// carried when that hook last exited 0; saving then loading must return it
    /// field-for-field (INV-4 state shape).
    #[test]
    fn save_then_load_hook_state_round_trips() {
        let (_dir, reg) = registry();
        let states = vec![HookState {
            hook_id: "vscode#0".to_owned(),
            last_success: digest_set(&["blake3:aaa", "blake3:bbb"]),
        }];

        reg.save_hook_state("vscode", &states)
            .expect("save hook state");
        let loaded = reg.hook_state("vscode").expect("load hook state");

        assert_eq!(
            loaded, states,
            "load_hook_state must return every saved hook record, field-for-field"
        );
    }

    /// A target that never ran a hook has no hook state; loading must not error
    /// and must yield an empty list (INV-8 absence, not a synthesized record).
    #[test]
    fn load_hook_state_on_missing_target_is_empty() {
        let (_dir, reg) = registry();

        let states = reg
            .hook_state("never-synced")
            .expect("missing hook state must not error");

        assert!(
            states.is_empty(),
            "a target with no recorded hook run yields an empty hook-state list"
        );
    }

    /// INV-4 success-only: an unrecorded sibling hook keeps its prior set and re-fires.
    #[test]
    fn record_hook_success_merges_and_leaves_other_hooks_untouched() {
        let (_dir, reg) = registry();
        reg.save_hook_state(
            "vscode",
            &[
                HookState {
                    hook_id: "vscode#0".to_owned(),
                    last_success: digest_set(&["blake3:aaa"]),
                },
                HookState {
                    hook_id: "vscode#1".to_owned(),
                    last_success: digest_set(&["blake3:bbb"]),
                },
            ],
        )
        .expect("seed two hook records");

        reg.record_hook_success("vscode", "vscode#0", &digest_set(&["blake3:ccc"]))
            .expect("record success only for the hook that exited 0");

        let loaded = reg.hook_state("vscode").expect("load hook state");
        let succeeded = loaded
            .iter()
            .find(|s| s.hook_id == "vscode#0")
            .expect("succeeded hook present");
        let untouched = loaded
            .iter()
            .find(|s| s.hook_id == "vscode#1")
            .expect("the hook that never succeeded must still be present");

        assert_eq!(
            succeeded.last_success,
            digest_set(&["blake3:ccc"]),
            "the succeeded hook's last-success set advances to the current digest-set"
        );
        assert_eq!(
            untouched.last_success,
            digest_set(&["blake3:bbb"]),
            "a hook not recorded keeps its prior set, so it re-fires next sync (INV-4)"
        );
    }

    #[test]
    fn record_hook_success_creates_record_for_first_success() {
        let (_dir, reg) = registry();

        reg.record_hook_success("vscode", "vscode#0", &digest_set(&["blake3:aaa"]))
            .expect("record first-ever success");

        let loaded = reg.hook_state("vscode").expect("load hook state");
        assert_eq!(
            loaded,
            vec![HookState {
                hook_id: "vscode#0".to_owned(),
                last_success: digest_set(&["blake3:aaa"]),
            }],
            "first success for a hook with no prior record creates exactly that record"
        );
    }

    /// INV-8: a target that records hook state and ejected entries side by side
    /// must round-trip both — hook state does not clobber the existing ejected
    /// meta, and vice versa.
    #[test]
    fn hook_state_and_ejected_meta_coexist_for_same_target() {
        let (_dir, reg) = registry();
        let ejected = vec![Ejection {
            source: "company-configs".to_owned(),
            artifact: "snippets".to_owned(),
            ejected_at: "2026-06-13T10:00:00Z".to_owned(),
        }];
        let hooks = vec![HookState {
            hook_id: "vscode#0".to_owned(),
            last_success: digest_set(&["blake3:aaa"]),
        }];

        reg.save_ejections("vscode", &ejected)
            .expect("save ejected");
        reg.save_hook_state("vscode", &hooks)
            .expect("save hook state");

        assert_eq!(
            reg.ejections("vscode").expect("load ejected"),
            ejected,
            "saving hook state must not clobber existing ejected entries"
        );
        assert_eq!(
            reg.hook_state("vscode").expect("load hook state"),
            hooks,
            "hook state must persist alongside ejected entries"
        );
    }

    /// INV-8 (byte-stability): a hook-free target writes meta identical to the
    /// pre-feature format — the new hook-state field is `skip_serializing_if`
    /// absent, so an ejected-only meta serializes byte-for-byte as today.
    #[test]
    fn hook_free_target_meta_serializes_byte_identical_to_pre_feature() {
        let (dir, reg) = registry();
        let ejected = vec![Ejection {
            source: "company-configs".to_owned(),
            artifact: "snippets".to_owned(),
            ejected_at: "2026-01-31T14:00:00Z".to_owned(),
        }];

        reg.save_ejections("vscode", &ejected)
            .expect("save ejected");

        let meta_path = dir.path().join("targets").join("vscode").join("meta.toml");
        let written = std::fs::read_to_string(&meta_path).expect("read meta.toml");
        let expected = "\
version = 1

[[ejected]]
source = \"company-configs\"
artifact = \"snippets\"
ejected_at = \"2026-01-31T14:00:00Z\"
";
        assert_eq!(
            written, expected,
            "a hook-free target's meta.toml must serialize byte-identically to the pre-feature format (INV-8)"
        );
    }
}