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
//! Target-side artifact copy, link, and atomic swap operations.

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

use crate::error::{Error, Result};
use crate::sync::scan::scan_dir_strict;
use crate::sync::state::{ArtifactRecord, StateStore};

use super::SyncWarning;
use super::journal::{Journal, JournalEntry};
use super::recovery::{backup_path, remove_path, rollback_swap};
use super::request::SyncEvents;

#[cfg(test)]
use super::recovery::recovery_sweep;

/// Copy a file from staging to target, preferring reflink, preserving mtime.
pub fn copy_file(src: &Path, dst: &Path) -> Result<()> {
    if reflink_copy::reflink(src, dst).is_err() {
        std::fs::copy(src, dst).map_err(|e| {
            Error::Projection(format!("copy {} -> {}: {e}", src.display(), dst.display()))
        })?;
    }
    copy_mtime(src, dst)
}

fn copy_mtime(src: &Path, dst: &Path) -> Result<()> {
    let meta = std::fs::metadata(src)
        .map_err(|e| Error::Projection(format!("stat {}: {e}", src.display())))?;
    let mtime = filetime::FileTime::from_last_modification_time(&meta);
    filetime::set_file_mtime(dst, mtime)
        .map_err(|e| Error::Projection(format!("set mtime {}: {e}", dst.display())))
}

/// Cross-device fallback for the atomic-rename swap: recursively copy `src` into `dst`.
pub fn copy_tree(src: &Path, dst: &Path, allow_symlinks: bool) -> Result<()> {
    let scan = scan_dir_strict(src, allow_symlinks)?;
    std::fs::create_dir_all(dst)
        .map_err(|e| Error::Projection(format!("create dir {}: {e}", dst.display())))?;
    for file in &scan.files {
        let from = src.join(&file.path);
        let to = dst.join(&file.path);
        if let Some(parent) = to.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| Error::Projection(format!("create dir {}: {e}", parent.display())))?;
        }
        copy_file(&from, &to)?;
    }
    for link in &scan.symlinks {
        let to = dst.join(link);
        let target = std::fs::read_link(src.join(link))
            .map_err(|e| Error::Projection(format!("read link {}: {e}", link.display())))?;
        if let Some(parent) = to.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| Error::Projection(format!("create dir {}: {e}", parent.display())))?;
        }
        std::os::unix::fs::symlink(&target, &to)
            .map_err(|e| Error::Projection(format!("symlink {}: {e}", to.display())))?;
    }
    Ok(())
}

/// Atomic swap of `staging` into `dst`, then persist `record`.
///
/// `staging_base` is `<target_parent>/.phora-stage/`; `staging` is the exported dir
/// inside it. The intent is journaled before the swap and cleared after the put.
/// Removes its tracked paths on drop; `base` is the shared `staging_base`, pruned only
/// when empty so a sibling artifact's pending staging is never wiped.
struct CleanupGuard {
    paths: Vec<PathBuf>,
    base: Option<PathBuf>,
}

impl CleanupGuard {
    fn new() -> Self {
        Self {
            paths: Vec::new(),
            base: None,
        }
    }

    fn track(&mut self, path: PathBuf) {
        self.paths.push(path);
    }

    fn prune_base_if_empty(&mut self, base: PathBuf) {
        self.base = Some(base);
    }
}

impl Drop for CleanupGuard {
    fn drop(&mut self) {
        for path in &self.paths {
            let _ = remove_path(path);
        }
        if let Some(base) = &self.base {
            let _ = std::fs::remove_dir(base);
        }
    }
}

pub fn apply_artifact(
    staging_base: &Path,
    staging: &Path,
    dst: &Path,
    record: ArtifactRecord,
    journal: &Journal,
    registry: &dyn StateStore,
) -> Result<()> {
    let mut events = SyncEvents::discarding();
    apply_artifact_report(
        ApplyPaths {
            staging_base,
            staging,
            dst,
        },
        record,
        journal,
        registry,
        &mut events,
        || Ok(()),
    )
}

#[derive(Clone, Copy)]
pub(super) struct ApplyPaths<'a> {
    pub(super) staging_base: &'a Path,
    pub(super) staging: &'a Path,
    pub(super) dst: &'a Path,
}

pub(super) fn apply_artifact_report(
    paths: ApplyPaths<'_>,
    mut record: ArtifactRecord,
    journal: &Journal,
    registry: &dyn StateStore,
    events: &mut SyncEvents,
    pre_swap: impl FnOnce() -> Result<()>,
) -> Result<()> {
    let mut cleanup = CleanupGuard::new();
    cleanup.track(paths.staging.to_path_buf());
    cleanup.track(backup_path(paths.staging_base, paths.dst));
    cleanup.prune_base_if_empty(paths.staging_base.to_path_buf());

    if record.kind == crate::sync::state::RecordKind::Dir {
        record.directories = super::directories::snapshot(paths.staging, &record)?;
    }

    journal.append(&JournalEntry {
        staging_base: paths.staging_base.to_path_buf(),
        staging: paths.staging.to_path_buf(),
        dst: paths.dst.to_path_buf(),
        record: record.clone(),
        swap_completed: false,
    })?;

    if let Err(error) = pre_swap() {
        journal.remove(paths.dst)?;
        return Err(error);
    }

    let backup = match std::fs::symlink_metadata(paths.dst) {
        Ok(_) => {
            let backup = backup_path(paths.staging_base, paths.dst);
            std::fs::rename(paths.dst, &backup).map_err(|e| {
                Error::Projection(format!(
                    "rename {} -> {}: {e}",
                    paths.dst.display(),
                    backup.display()
                ))
            })?;
            Some(backup)
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => {
            return Err(Error::Projection(format!(
                "stat {}: {e}",
                paths.dst.display()
            )));
        }
    };

    swap_into(paths.staging, paths.dst, record.allow_symlinks, events)?;
    journal.mark_swap_completed(paths.dst)?;

    if let Err(put_err) = registry.put_artifact_journaled(&record, journal.directory()) {
        rollback_swap(paths.dst, backup.as_deref())?;
        journal.remove(paths.dst)?;
        return Err(put_err.into());
    }

    journal.remove(paths.dst)?;
    Ok(())
}

#[cfg(unix)]
use std::os::unix::fs::symlink as symlink_unix;
#[cfg(windows)]
use std::os::windows::fs::{symlink_dir, symlink_file};

#[cfg(unix)]
fn create_symlink(target: &Path, link: &Path, _is_file: bool) -> std::io::Result<()> {
    symlink_unix(target, link)
}

#[cfg(windows)]
fn create_symlink(target: &Path, link: &Path, is_file: bool) -> std::io::Result<()> {
    if is_file {
        symlink_file(target, link)
    } else {
        symlink_dir(target, link)
    }
}

/// Crash-safe symlink deploy: stage a fresh symlink beside `dst`, journal the
/// intent, then atomically `rename` it over `dst`. No copy/swap is involved —
/// the link points at the absolute working-tree `target`.
#[expect(
    clippy::needless_pass_by_value,
    reason = "caller hands off ownership of the record being deployed"
)]
pub fn link_artifact(
    staging_base: &Path,
    dst: &Path,
    target: &Path,
    record: ArtifactRecord,
    journal: &Journal,
    registry: &dyn StateStore,
) -> Result<()> {
    let parent = dst
        .parent()
        .ok_or_else(|| Error::Projection(format!("link dst {} has no parent", dst.display())))?;
    std::fs::create_dir_all(parent)
        .map_err(|e| Error::Projection(format!("create link dir {}: {e}", parent.display())))?;
    std::fs::create_dir_all(staging_base).map_err(|e| {
        Error::Projection(format!(
            "create staging dir {}: {e}",
            staging_base.display()
        ))
    })?;

    let leaf = dst.file_name().map_or_else(
        || "artifact".to_owned(),
        |n| n.to_string_lossy().into_owned(),
    );
    let staging = staging_base.join(format!("link-{leaf}-{}", link_nonce()));
    let mut cleanup = CleanupGuard::new();
    cleanup.track(staging.clone());
    cleanup.track(backup_path(staging_base, dst));
    cleanup.prune_base_if_empty(staging_base.to_path_buf());

    let is_file = matches!(record.kind, crate::sync::state::RecordKind::File);
    create_symlink(target, &staging, is_file).map_err(|e| {
        Error::Projection(format!(
            "symlink {} -> {}: {e}",
            staging.display(),
            target.display()
        ))
    })?;

    journal.append(&JournalEntry {
        staging_base: staging_base.to_path_buf(),
        staging: staging.clone(),
        dst: dst.to_path_buf(),
        record: record.clone(),
        swap_completed: false,
    })?;

    let backup = match dst.try_exists() {
        Ok(true) => {
            let backup = backup_path(staging_base, dst);
            std::fs::rename(dst, &backup).map_err(|e| {
                Error::Projection(format!(
                    "rename {} -> {}: {e}",
                    dst.display(),
                    backup.display()
                ))
            })?;
            Some(backup)
        }
        Ok(false) => None,
        Err(e) => return Err(Error::Projection(format!("stat {}: {e}", dst.display()))),
    };

    std::fs::rename(&staging, dst).map_err(|e| {
        Error::Projection(format!(
            "rename {} -> {}: {e}",
            staging.display(),
            dst.display()
        ))
    })?;
    journal.mark_swap_completed(dst)?;

    if let Err(put_err) = registry.put_artifact_journaled(&record, journal.directory()) {
        rollback_swap(dst, backup.as_deref())?;
        journal.remove(dst)?;
        return Err(put_err.into());
    }

    journal.remove(dst)?;
    Ok(())
}

fn link_nonce() -> u64 {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    COUNTER.fetch_add(1, Ordering::Relaxed)
}

/// Same-mount `rename` is atomic; a cross-device error falls back to copy+fsync.
fn swap_into(
    staging: &Path,
    dst: &Path,
    allow_symlinks: bool,
    events: &mut SyncEvents,
) -> Result<()> {
    match std::fs::rename(staging, dst) {
        Ok(()) => Ok(()),
        Err(e) if is_cross_device(&e) => {
            events.push_warning(SyncWarning::CrossDeviceFallback {
                destination: dst.to_path_buf(),
            });
            if staging.is_file() {
                copy_file(staging, dst)
            } else {
                copy_tree(staging, dst, allow_symlinks)
            }
        }
        Err(e) => Err(Error::Projection(format!(
            "rename {} -> {}: {e}",
            staging.display(),
            dst.display()
        ))),
    }
}

fn is_cross_device(e: &std::io::Error) -> bool {
    e.kind() == std::io::ErrorKind::CrossesDevices
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sync::state::{
        ArtifactKey, Ejection, FileStateStore, HookState, ManifestFile, StateError,
    };

    type StoreResult<T> = std::result::Result<T, StateError>;
    use std::collections::BTreeSet;
    use std::os::unix::fs::symlink;
    use tempfile::TempDir;

    fn read_mtime_secs(path: &Path) -> u64 {
        std::fs::metadata(path)
            .expect("metadata")
            .modified()
            .expect("modified time")
            .duration_since(std::time::UNIX_EPOCH)
            .expect("after epoch")
            .as_secs()
    }

    fn set_mtime(path: &Path, secs: u64) {
        filetime::set_file_mtime(
            path,
            filetime::FileTime::from_unix_time(secs.cast_signed(), 0),
        )
        .expect("set mtime");
    }

    // copy_file

    #[test]
    fn copy_file_reproduces_source_content() {
        let dir = TempDir::new().expect("tempdir");
        let src = dir.path().join("src.txt");
        let dst = dir.path().join("dst.txt");
        std::fs::write(&src, b"reflink-or-copy payload").expect("write src");

        copy_file(&src, &dst).expect("copy_file");

        assert_eq!(
            std::fs::read(&dst).expect("read dst"),
            b"reflink-or-copy payload",
            "dst content must be byte-identical to src regardless of reflink vs plain copy"
        );
    }

    #[test]
    fn copy_file_preserves_source_mtime() {
        let dir = TempDir::new().expect("tempdir");
        let src = dir.path().join("src.txt");
        let dst = dir.path().join("dst.txt");
        std::fs::write(&src, b"payload").expect("write src");
        let known = 1_700_000_000u64;
        set_mtime(&src, known);

        copy_file(&src, &dst).expect("copy_file");

        assert_eq!(
            read_mtime_secs(&dst),
            known,
            "copy_file must explicitly carry the src mtime onto dst (reflink does not copy mtime)"
        );
    }

    // copy_tree

    #[test]
    fn copy_tree_recreates_symlinks_not_just_regular_files() {
        let root = TempDir::new().expect("tempdir");
        let src = root.path().join("src");
        let dst = root.path().join("dst");
        std::fs::create_dir(&src).expect("mkdir src");
        std::fs::write(src.join("real.txt"), b"payload").expect("write real");
        symlink("real.txt", src.join("link.txt")).expect("create symlink");

        copy_tree(&src, &dst, true).expect("copy_tree with symlinks allowed");

        assert_eq!(
            std::fs::read(dst.join("real.txt")).expect("read copied file"),
            b"payload",
            "the regular file must be copied"
        );
        let link = dst.join("link.txt");
        assert!(
            std::fs::symlink_metadata(&link)
                .expect("stat copied link")
                .file_type()
                .is_symlink(),
            "copy_tree must recreate the symlink AS a symlink, not drop it or dereference it"
        );
        assert_eq!(
            std::fs::read_link(&link).expect("read copied link"),
            PathBuf::from("real.txt"),
            "the recreated symlink must preserve its original target"
        );
    }

    const SOURCE: &str = "company-configs";
    const COMMIT: &str = "abc123def456";
    const ARTIFACT: &str = "snippets";
    const TARGET: &str = "vscode";

    fn key() -> ArtifactKey {
        ArtifactKey {
            target: TARGET.to_owned(),
            source: SOURCE.to_owned(),
            artifact: ARTIFACT.to_owned(),
        }
    }

    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)
    }

    // apply_artifact / recovery_sweep

    /// `<target_parent>/.phora-stage/`: deploy stages here and cleans it up afterward.
    fn staging_base(target_parent: &Path) -> PathBuf {
        target_parent.join(".phora-stage")
    }

    /// Create the already-staged dir with the given files, mirroring what
    /// `stage_artifact` leaves before the swap.
    fn make_staging(staging_base: &Path, files: &[(&str, &[u8])]) -> PathBuf {
        let staging = staging_base.join("snippets-deadbeef");
        for (rel, contents) in files {
            let path = staging.join(rel);
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent).expect("mkdir staging parent");
            }
            std::fs::write(&path, contents).expect("write staged file");
        }
        staging
    }

    /// Record describing what `apply_artifact` should persist; file metadata is filled
    /// from the staging dir so a post-deploy `check_artifact_state` reads as Clean.
    fn record_for(staging: &Path, files: &[(&str, &[u8])]) -> ArtifactRecord {
        let mut manifest = Vec::new();
        for (rel, contents) in files {
            manifest.push(ManifestFile {
                path: PathBuf::from(rel),
                kind: crate::sync::state::ManifestEntryKind::File,
                size: contents.len() as u64,
                mtime: read_mtime_secs(&staging.join(rel)),
                blake3: blake3::hash(contents).to_hex().to_string(),
            });
        }
        ArtifactRecord {
            version: 1,
            key: key(),
            source: SOURCE.to_owned(),
            commit: COMMIT.to_owned(),
            digest: "blake3:d4e5f6".to_owned(),
            projected_at: "2026-01-31T12:34:56Z".to_owned(),
            layout: "flat".to_owned(),
            kind: crate::sync::state::RecordKind::Dir,
            allow_symlinks: false,
            preserve_executable: true,
            files: manifest,
            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,
        }
    }

    /// True when `target_parent` holds any `.phora-stage*` entry (staging or backup leftover).
    fn has_phora_stage_leftover(target_parent: &Path) -> bool {
        std::fs::read_dir(target_parent)
            .expect("read target parent")
            .any(|e| {
                e.expect("dir entry")
                    .file_name()
                    .to_string_lossy()
                    .starts_with(".phora-stage")
            })
    }

    fn read_dir_names(dir: &Path) -> Vec<String> {
        std::fs::read_dir(dir)
            .expect("read dir")
            .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
            .collect()
    }

    fn journal_for(reg: &FileStateStore) -> Journal {
        Journal::open(&reg.state_root().join("locks")).expect("open journal")
    }

    fn entry(
        base: &Path,
        staging: &Path,
        dst: &Path,
        record: &ArtifactRecord,
        swap_completed: bool,
    ) -> JournalEntry {
        JournalEntry {
            staging_base: base.to_path_buf(),
            staging: staging.to_path_buf(),
            dst: dst.to_path_buf(),
            record: record.clone(),
            swap_completed,
        }
    }

    #[test]
    fn deploy_makes_dst_contain_exactly_the_staged_files() {
        let (_state_dir, reg) = registry();
        let parent = TempDir::new().expect("target parent");
        let dst = parent.path().join("vscode");
        let files: &[(&str, &[u8])] = &[("a.json", b"{}"), ("nested/b.txt", b"hello")];
        let base = staging_base(parent.path());
        let staging = make_staging(&base, files);
        let record = record_for(&staging, files);
        let jrnl = journal_for(&reg);

        apply_artifact(&base, &staging, &dst, record, &jrnl, &reg).expect("deploy must succeed");

        assert_eq!(
            std::fs::read(dst.join("a.json")).expect("read a.json"),
            b"{}",
            "dst must contain the staged a.json byte-for-byte"
        );
        assert_eq!(
            std::fs::read(dst.join("nested/b.txt")).expect("read nested/b.txt"),
            b"hello",
            "dst must contain the staged nested/b.txt byte-for-byte"
        );
    }

    #[test]
    fn pre_swap_writes_arrive_with_the_swap() {
        let (_state_dir, reg) = registry();
        let parent = TempDir::new().expect("target parent");
        let dst = parent.path().join("vscode");
        std::fs::create_dir_all(&dst).expect("create prior deployment");
        std::fs::write(dst.join("old.txt"), b"old").expect("write prior file");
        let files: &[(&str, &[u8])] = &[("a.json", b"{}")];
        let base = staging_base(parent.path());
        let staging = make_staging(&base, files);
        let record = record_for(&staging, files);
        let jrnl = journal_for(&reg);
        let mut events = SyncEvents::discarding();

        apply_artifact_report(
            ApplyPaths {
                staging_base: &base,
                staging: &staging,
                dst: &dst,
            },
            record,
            &jrnl,
            &reg,
            &mut events,
            || {
                assert!(
                    dst.join("old.txt").is_file(),
                    "pre_swap runs while the prior deployment is still in place"
                );
                std::fs::write(staging.join(".git"), b"gitdir: /admin\n").expect("stage gitlink");
                Ok(())
            },
        )
        .expect("deploy must succeed");

        assert_eq!(
            std::fs::read(dst.join(".git")).expect("read gitlink"),
            b"gitdir: /admin\n",
            "a file written by pre_swap is in place the moment the deployment is"
        );
    }

    #[test]
    fn failed_pre_swap_keeps_the_prior_deployment_and_clears_the_journal() {
        let (_state_dir, reg) = registry();
        let parent = TempDir::new().expect("target parent");
        let dst = parent.path().join("vscode");
        std::fs::create_dir_all(&dst).expect("create prior deployment");
        std::fs::write(dst.join("old.txt"), b"old").expect("write prior file");
        let files: &[(&str, &[u8])] = &[("a.json", b"{}")];
        let base = staging_base(parent.path());
        let staging = make_staging(&base, files);
        let record = record_for(&staging, files);
        let jrnl = journal_for(&reg);
        let mut events = SyncEvents::discarding();

        let result = apply_artifact_report(
            ApplyPaths {
                staging_base: &base,
                staging: &staging,
                dst: &dst,
            },
            record,
            &jrnl,
            &reg,
            &mut events,
            || Err(Error::Projection("publish failed".to_owned())),
        );

        assert!(result.is_err(), "a pre_swap failure fails the deploy");
        assert_eq!(
            std::fs::read(dst.join("old.txt")).expect("read prior file"),
            b"old",
            "the prior deployment stays in place"
        );
        assert!(
            jrnl.entries().expect("read journal").is_empty(),
            "the journal entry is removed"
        );
    }

    #[test]
    fn deploy_leaves_no_staging_or_backup_in_target_parent() {
        let (_state_dir, reg) = registry();
        let parent = TempDir::new().expect("target parent");
        let dst = parent.path().join("vscode");
        let files: &[(&str, &[u8])] = &[("a.json", b"{}")];
        let base = staging_base(parent.path());
        let staging = make_staging(&base, files);
        let record = record_for(&staging, files);
        let jrnl = journal_for(&reg);

        apply_artifact(&base, &staging, &dst, record, &jrnl, &reg).expect("deploy must succeed");

        assert!(
            !has_phora_stage_leftover(parent.path()),
            "after a successful deploy the target parent must hold no .phora-stage* leftover, found {:?}",
            read_dir_names(parent.path())
        );
    }

    #[test]
    fn deploy_persists_the_registry_record() {
        let (_state_dir, reg) = registry();
        let parent = TempDir::new().expect("target parent");
        let dst = parent.path().join("vscode");
        let files: &[(&str, &[u8])] = &[("a.json", b"{}")];
        let base = staging_base(parent.path());
        let staging = make_staging(&base, files);
        let mut record = record_for(&staging, files);
        record.directories =
            super::super::directories::snapshot(&staging, &record).expect("snapshot");
        let jrnl = journal_for(&reg);

        apply_artifact(&base, &staging, &dst, record.clone(), &jrnl, &reg)
            .expect("deploy must succeed");

        let got = reg
            .artifact(&key())
            .expect("get after deploy")
            .expect("record persisted after deploy");
        assert_eq!(
            got, record,
            "deploy must persist the record so a later get returns it field-for-field"
        );
        assert!(
            journal_for(&reg)
                .entries()
                .expect("read journal after deploy")
                .is_empty(),
            "a successful deploy must clear its journal intent so recovery never replays it"
        );
    }

    #[test]
    fn deploy_swaps_out_old_dst_content_for_new_staged_content() {
        let (_state_dir, reg) = registry();
        let parent = TempDir::new().expect("target parent");
        let dst = parent.path().join("vscode");
        std::fs::create_dir_all(&dst).expect("mkdir old dst");
        std::fs::write(dst.join("old.json"), b"OLD").expect("write old content");

        let files: &[(&str, &[u8])] = &[("a.json", b"NEW")];
        let base = staging_base(parent.path());
        let staging = make_staging(&base, files);
        let record = record_for(&staging, files);
        let jrnl = journal_for(&reg);

        apply_artifact(&base, &staging, &dst, record, &jrnl, &reg).expect("deploy must succeed");

        assert_eq!(
            std::fs::read(dst.join("a.json")).expect("read new a.json"),
            b"NEW",
            "dst must hold the new staged content after the swap"
        );
        assert!(
            !dst.join("old.json").exists(),
            "the old dst content must be swapped out, old.json must be gone"
        );
        assert!(
            !has_phora_stage_leftover(parent.path()),
            "the swapped-out old version (backup) must be cleaned up, found {:?}",
            read_dir_names(parent.path())
        );
    }

    /// `StateStore` double that, at `put` time, records whether the write-ahead invariants already
    /// hold: the journal carries the intent and `dst` already holds the staged content. Reads
    /// delegate to an inner `FileStateStore`; `put` succeeds.
    struct OrderingProbeRegistry {
        inner: FileStateStore,
        journal_dir: PathBuf,
        dst: PathBuf,
        staged_content: Vec<u8>,
        journal_nonempty_at_put: std::cell::Cell<bool>,
        dst_held_staged_content_at_put: std::cell::Cell<bool>,
    }

    impl StateStore for OrderingProbeRegistry {
        fn artifact(&self, key: &ArtifactKey) -> StoreResult<Option<ArtifactRecord>> {
            self.inner.artifact(key)
        }
        fn put_artifact(&self, _record: &ArtifactRecord) -> StoreResult<()> {
            panic!("deployment must use the journaled record write");
        }
        fn put_artifact_journaled(
            &self,
            record: &ArtifactRecord,
            journal_dir: &Path,
        ) -> StoreResult<()> {
            assert_eq!(journal_dir, self.journal_dir);
            let journal = Journal::open(&self.journal_dir).expect("open journal at put time");
            let entries = journal.entries().expect("read journal at put time");
            self.journal_nonempty_at_put.set(
                entries
                    .iter()
                    .any(|entry| entry.swap_completed && entry.record == *record),
            );
            let on_disk = std::fs::read(self.dst.join("a.json")).unwrap_or_default();
            self.dst_held_staged_content_at_put
                .set(on_disk == self.staged_content);
            self.inner.put_artifact_journaled(record, journal_dir)
        }
        fn remove_artifact(&self, key: &ArtifactKey) -> StoreResult<()> {
            self.inner.remove_artifact(key)
        }
        fn target_artifacts(&self, target: &str) -> StoreResult<Vec<ArtifactRecord>> {
            self.inner.target_artifacts(target)
        }
        fn all_artifacts(&self) -> StoreResult<Vec<ArtifactRecord>> {
            self.inner.all_artifacts()
        }
        fn ejections(&self, target: &str) -> StoreResult<Vec<Ejection>> {
            self.inner.ejections(target)
        }
        fn save_ejections(&self, target: &str, ejected: &[Ejection]) -> StoreResult<()> {
            self.inner.save_ejections(target, ejected)
        }
        fn hook_state(&self, target: &str) -> StoreResult<Vec<HookState>> {
            self.inner.hook_state(target)
        }
        fn record_hook_success(
            &self,
            target: &str,
            hook_id: &str,
            digest_set: &BTreeSet<String>,
        ) -> StoreResult<()> {
            self.inner.record_hook_success(target, hook_id, digest_set)
        }
        fn acquire_lock(&self) -> StoreResult<crate::sync::state::StateLock> {
            self.inner.acquire_lock()
        }
        fn journal_root(&self) -> PathBuf {
            self.inner.journal_root()
        }
    }

    #[test]
    fn deploy_journals_intent_before_put_and_swaps_before_put() {
        let dir = TempDir::new().expect("temp state root");
        let inner = FileStateStore::open(dir.path().to_path_buf()).expect("open inner registry");
        let journal_dir = inner.state_root().join("locks");
        let parent = TempDir::new().expect("target parent");
        let dst = parent.path().join("vscode");
        let files: &[(&str, &[u8])] = &[("a.json", b"NEW")];
        let base = staging_base(parent.path());
        let staging = make_staging(&base, files);
        let record = record_for(&staging, files);
        let reg = OrderingProbeRegistry {
            inner,
            journal_dir: journal_dir.clone(),
            dst: dst.clone(),
            staged_content: b"NEW".to_vec(),
            journal_nonempty_at_put: std::cell::Cell::new(false),
            dst_held_staged_content_at_put: std::cell::Cell::new(false),
        };
        let jrnl = Journal::open(&journal_dir).expect("open journal");

        apply_artifact(&base, &staging, &dst, record, &jrnl, &reg).expect("deploy must succeed");

        assert!(
            reg.journal_nonempty_at_put.get(),
            "deploy must append the intent to the journal BEFORE calling registry put (write-ahead): \
             the journal was empty at put time"
        );
        assert!(
            reg.dst_held_staged_content_at_put.get(),
            "deploy must complete the stage->dst swap BEFORE calling registry put: \
             dst did not hold the staged content at put time"
        );
    }

    /// `StateStore` double whose `put` always fails; all reads delegate to an inner `FileStateStore`.
    struct FailingPutRegistry {
        inner: FileStateStore,
    }

    impl StateStore for FailingPutRegistry {
        fn artifact(&self, key: &ArtifactKey) -> StoreResult<Option<ArtifactRecord>> {
            self.inner.artifact(key)
        }
        fn put_artifact(&self, _record: &ArtifactRecord) -> StoreResult<()> {
            Err(StateError::StateStore("injected put failure".to_owned()))
        }
        fn remove_artifact(&self, key: &ArtifactKey) -> StoreResult<()> {
            self.inner.remove_artifact(key)
        }
        fn target_artifacts(&self, target: &str) -> StoreResult<Vec<ArtifactRecord>> {
            self.inner.target_artifacts(target)
        }
        fn all_artifacts(&self) -> StoreResult<Vec<ArtifactRecord>> {
            self.inner.all_artifacts()
        }
        fn ejections(&self, target: &str) -> StoreResult<Vec<Ejection>> {
            self.inner.ejections(target)
        }
        fn save_ejections(&self, target: &str, ejected: &[Ejection]) -> StoreResult<()> {
            self.inner.save_ejections(target, ejected)
        }
        fn hook_state(&self, target: &str) -> StoreResult<Vec<HookState>> {
            self.inner.hook_state(target)
        }
        fn record_hook_success(
            &self,
            target: &str,
            hook_id: &str,
            digest_set: &BTreeSet<String>,
        ) -> StoreResult<()> {
            self.inner.record_hook_success(target, hook_id, digest_set)
        }
        fn acquire_lock(&self) -> StoreResult<crate::sync::state::StateLock> {
            self.inner.acquire_lock()
        }
        fn journal_root(&self) -> PathBuf {
            self.inner.journal_root()
        }
    }

    #[test]
    fn deploy_rolls_back_to_original_content_when_put_fails() {
        let dir = TempDir::new().expect("temp state root");
        let reg = FailingPutRegistry {
            inner: FileStateStore::open(dir.path().to_path_buf()).expect("open inner registry"),
        };
        let parent = TempDir::new().expect("target parent");
        let dst = parent.path().join("vscode");
        std::fs::create_dir_all(&dst).expect("mkdir old dst");
        std::fs::write(dst.join("old.json"), b"ORIGINAL").expect("write original content");

        let files: &[(&str, &[u8])] = &[("a.json", b"NEW")];
        let base = staging_base(parent.path());
        let staging = make_staging(&base, files);
        let record = record_for(&staging, files);
        let jrnl = journal_for(&reg.inner);

        let result = apply_artifact(&base, &staging, &dst, record, &jrnl, &reg);

        assert!(
            result.is_err(),
            "a failing registry put must make apply_artifact return Err"
        );
        assert_eq!(
            std::fs::read(dst.join("old.json")).expect("read rolled-back content"),
            b"ORIGINAL",
            "on put failure the destination must be rolled back to its original pre-deploy content"
        );
        assert!(
            !dst.join("a.json").exists(),
            "rollback must remove the new-but-untracked install; a.json must not survive"
        );
        assert!(
            journal_for(&reg.inner)
                .entries()
                .expect("read journal after rollback")
                .is_empty(),
            "after rolling back a failed deploy the journal intent must be cleared so the next \
             recovery sweep does not replay the rolled-back swap"
        );
    }

    #[test]
    fn deploy_rolls_back_to_absent_when_dst_did_not_exist_and_put_fails() {
        let dir = TempDir::new().expect("temp state root");
        let reg = FailingPutRegistry {
            inner: FileStateStore::open(dir.path().to_path_buf()).expect("open inner registry"),
        };
        let parent = TempDir::new().expect("target parent");
        let dst = parent.path().join("vscode");

        let files: &[(&str, &[u8])] = &[("a.json", b"NEW")];
        let base = staging_base(parent.path());
        let staging = make_staging(&base, files);
        let record = record_for(&staging, files);
        let jrnl = journal_for(&reg.inner);

        let result = apply_artifact(&base, &staging, &dst, record, &jrnl, &reg);

        assert!(result.is_err(), "failing put must yield Err");
        assert!(
            !dst.exists(),
            "dst absent before deploy => after a failed put it must be absent again, never a partial install"
        );
        assert!(
            journal_for(&reg.inner)
                .entries()
                .expect("read journal after rollback")
                .is_empty(),
            "after rolling back a failed deploy the journal intent must be cleared so the next \
             recovery sweep does not replay the rolled-back swap"
        );
    }

    #[test]
    fn recovery_finishes_registry_write_when_swap_completed_but_put_did_not() {
        let (_state_dir, reg) = registry();
        let parent = TempDir::new().expect("target parent");
        let dst = parent.path().join("vscode");
        let files: &[(&str, &[u8])] = &[("a.json", b"NEW")];
        let base = staging_base(parent.path());
        let staging = make_staging(&base, files);
        let record = record_for(&staging, files);
        let jrnl = journal_for(&reg);

        // State after a real stage->dst rename: dst holds the new content, the staging dir is
        // gone (renamed away), the journal has swap_completed=true, the registry has no record.
        jrnl.append(&entry(&base, &staging, &dst, &record, true))
            .expect("append swap-completed intent");
        std::fs::rename(&staging, &dst).expect("simulate completed stage->dst rename");
        std::fs::remove_dir_all(&base).expect("staging base removed after the move");
        assert_eq!(
            std::fs::read(dst.join("a.json")).expect("read dst after simulated swap"),
            b"NEW",
            "premise: dst already holds the new staged content (swap completed)"
        );
        assert!(
            !staging.exists(),
            "premise: the staging dir was renamed away, not left behind"
        );
        assert!(
            reg.artifact(&key()).expect("pre-sweep get").is_none(),
            "premise: registry has no record yet (the crash happened before put)"
        );

        recovery_sweep(parent.path(), &jrnl, &reg).expect("recovery sweep must succeed");

        let persisted = reg
            .artifact(&key())
            .expect("post-sweep get")
            .expect("swap-completed-but-put-missing must be reconciled by finishing the put");
        assert_eq!(
            persisted, record,
            "recovery must persist exactly the journal entry's record, field-for-field"
        );
        assert!(
            journal_for(&reg)
                .entries()
                .expect("read journal after sweep")
                .is_empty(),
            "the journal must be cleared once the entry is reconciled"
        );
    }

    #[test]
    fn recovery_discards_staging_and_leaves_dst_unchanged_when_swap_did_not_complete() {
        let (_state_dir, reg) = registry();
        let parent = TempDir::new().expect("target parent");
        let dst = parent.path().join("vscode");
        std::fs::create_dir_all(&dst).expect("mkdir dst");
        std::fs::write(dst.join("untouched.json"), b"BEFORE").expect("write dst content");

        let files: &[(&str, &[u8])] = &[("a.json", b"NEW")];
        let base = staging_base(parent.path());
        let staging = make_staging(&base, files);
        let record = record_for(&staging, files);
        let jrnl = journal_for(&reg);
        jrnl.append(&entry(&base, &staging, &dst, &record, false))
            .expect("append swap-pending intent");

        recovery_sweep(parent.path(), &jrnl, &reg).expect("recovery sweep must succeed");

        assert_eq!(
            std::fs::read(dst.join("untouched.json")).expect("read dst"),
            b"BEFORE",
            "an incomplete swap must leave the destination exactly as it was"
        );
        assert!(
            reg.artifact(&key()).expect("post-sweep get").is_none(),
            "an incomplete swap must not produce a registry record"
        );
        assert!(
            !has_phora_stage_leftover(parent.path()),
            "recovery must discard the staging dir of the incomplete swap, found {:?}",
            read_dir_names(parent.path())
        );
        assert!(
            journal_for(&reg)
                .entries()
                .expect("read journal after sweep")
                .is_empty(),
            "the journal entry for the discarded incomplete swap must be cleared after the sweep"
        );
    }

    #[test]
    fn frozen_recovery_sweep_with_a_pending_entry_refuses_before_discarding_staging() {
        let (_state_dir, reg) = registry();
        let parent = TempDir::new().expect("target parent");
        let dst = parent.path().join("vscode");
        let files: &[(&str, &[u8])] = &[("a.json", b"NEW")];
        let base = staging_base(parent.path());
        let staging = make_staging(&base, files);
        let record = record_for(&staging, files);

        journal_for(&reg)
            .append(&entry(&base, &staging, &dst, &record, false))
            .expect("seed a crashed-swap intent through a writable journal");

        let readonly = Journal::open_readonly(&reg.state_root().join("locks"));
        let err = recovery_sweep(parent.path(), &readonly, &reg).expect_err(
            "a frozen recovery sweep with a pending journal entry must refuse before mutating",
        );

        let msg = err.to_string();
        assert!(
            msg.contains(&reg.state_root().display().to_string())
                && msg.to_lowercase().contains("read-only"),
            "the refusal must name the read-only state root, got: {msg}"
        );
        assert!(
            staging.exists(),
            "the sweep must fail BEFORE discarding the pending swap's staging dir — a read-only \
             frozen sync performs zero mutation when there is pending recovery work"
        );
    }

    /// Mirrors the impl's backup naming: `<staging_base>/.phora-backup-<dst-leaf>`.
    fn backup_for(base: &Path, dst: &Path) -> PathBuf {
        let leaf = dst.file_name().map_or_else(
            || "artifact".to_owned(),
            |n| n.to_string_lossy().into_owned(),
        );
        base.join(format!(".phora-backup-{leaf}"))
    }

    #[test]
    fn recovery_restores_backup_when_swap_was_incomplete() {
        let (_state_dir, reg) = registry();
        let parent = TempDir::new().expect("target parent");
        let dst = parent.path().join("vscode");

        let files: &[(&str, &[u8])] = &[("a.json", b"NEW")];
        let base = staging_base(parent.path());
        let staging = make_staging(&base, files);
        let record = record_for(&staging, files);

        let backup = backup_for(&base, &dst);
        std::fs::create_dir_all(&backup).expect("mkdir backup");
        std::fs::write(backup.join("old.json"), b"OLD").expect("write old backup content");

        let jrnl = journal_for(&reg);
        jrnl.append(&entry(&base, &staging, &dst, &record, false))
            .expect("append swap-incomplete intent");

        assert!(
            !dst.exists(),
            "premise: dst is missing (it was renamed to backup, swap not yet done)"
        );

        recovery_sweep(parent.path(), &jrnl, &reg).expect("recovery sweep must succeed");

        assert!(
            dst.exists(),
            "an incomplete swap with dst already renamed to backup must restore dst, not leave it missing"
        );
        assert_eq!(
            std::fs::read(dst.join("old.json")).expect("read restored dst"),
            b"OLD",
            "recovery must restore the ORIGINAL/backup content to dst, not the new staged content"
        );
        assert!(
            !dst.join("a.json").exists(),
            "the new staged content must NOT be installed for an incomplete swap"
        );
        assert!(
            reg.artifact(&key()).expect("post-sweep get").is_none(),
            "an incomplete swap must not produce a registry record"
        );
        assert!(
            journal_for(&reg)
                .entries()
                .expect("read journal after sweep")
                .is_empty(),
            "the journal entry for the reverted incomplete swap must be cleared after the sweep"
        );
    }

    #[test]
    fn deploy_preserves_unrelated_staging_in_shared_base() {
        let (_state_dir, reg) = registry();
        let parent = TempDir::new().expect("target parent");
        let dst = parent.path().join("vscode");

        let files: &[(&str, &[u8])] = &[("a.json", b"{}")];
        let base = staging_base(parent.path());
        let staging = make_staging(&base, files);
        let record = record_for(&staging, files);

        let sibling = base.join("b-nonce");
        std::fs::create_dir_all(&sibling).expect("mkdir sibling staging");
        let marker = sibling.join("b-marker.txt");
        std::fs::write(&marker, b"B is still pending").expect("write sibling marker");

        let jrnl = journal_for(&reg);

        apply_artifact(&base, &staging, &dst, record, &jrnl, &reg).expect("deploy A must succeed");

        assert_eq!(
            std::fs::read(dst.join("a.json")).expect("read deployed A"),
            b"{}",
            "artifact A must be deployed to its dst"
        );
        assert!(
            sibling.exists(),
            "deploying A must not delete sibling artifact B's staging dir in the shared base"
        );
        assert_eq!(
            std::fs::read(&marker).expect("read sibling marker"),
            b"B is still pending",
            "B's pending staging content must survive A's cleanup"
        );
        assert!(
            !staging.exists(),
            "A's own staging dir must be cleaned up after deploy"
        );
        assert!(
            !backup_for(&base, &dst).exists(),
            "A's own backup must be cleaned up after deploy"
        );
    }

    #[test]
    fn recovery_removes_orphaned_phora_stage_left_by_previous_crash() {
        let (_state_dir, reg) = registry();
        let parent = TempDir::new().expect("target parent");
        let base = staging_base(parent.path());
        std::fs::create_dir_all(base.join("orphan-cafef00d")).expect("mkdir orphan staging");
        std::fs::write(base.join("orphan-cafef00d").join("leftover.txt"), b"x")
            .expect("write orphan file");
        assert!(
            has_phora_stage_leftover(parent.path()),
            "premise: an orphaned .phora-stage exists before the sweep"
        );
        let jrnl = journal_for(&reg);

        recovery_sweep(parent.path(), &jrnl, &reg).expect("recovery sweep must succeed");

        assert!(
            !has_phora_stage_leftover(parent.path()),
            "the startup recovery sweep must remove orphaned .phora-stage* dirs, found {:?}",
            read_dir_names(parent.path())
        );
    }
}