Skip to main content

spec_driven_docs/landing/
apply.rs

1//! Write one rendered candidate into a target, directly.
2//!
3//! Everything is decided before the first byte moves: every destination is
4//! checked for containment, every whole file this tool would own is checked
5//! for attribution, and the target lock is taken for the whole run. Then
6//! each destination is replaced in its own directory, and the record is
7//! written last.
8//!
9//! There is no journal and no rollback. A run that stops leaves whole
10//! files, the previous record, a visible Git diff, and a command that runs
11//! again. What it finished is reported, because that is what the operator
12//! needs and what the next run reconciles against.
13
14use camino::{Utf8Path, Utf8PathBuf};
15
16use crate::candidate::{Candidate, Ownership};
17use crate::domain::manifest::MANIFEST_PATH;
18use crate::domain::ownership::Sha256;
19use crate::domain::paths::PRUNABLE_ROOTS;
20use crate::error::AppError;
21use crate::transaction::stage::Stage;
22
23/// What one landing did.
24#[derive(Debug, Default)]
25pub struct Outcome {
26    /// Every destination this run wrote, in the order it wrote them.
27    pub written: Vec<Utf8PathBuf>,
28    /// Every managed destination this release no longer owns, taken back.
29    pub removed: Vec<String>,
30}
31
32/// What the target's own record says this tool owns today.
33///
34/// It decides three things: which whole files may be refreshed, which
35/// marked regions may be re-spliced, and which files a release that
36/// stopped landing them may take back.
37#[derive(Debug, Default, Clone)]
38pub struct Recorded {
39    /// Each managed destination and the digest the record vouches for.
40    pub managed: Vec<(String, Sha256)>,
41    /// Each integration host and the hash of the region this tool owns.
42    pub integration: Vec<(String, Sha256)>,
43    /// Destinations the operator named for replacement, whatever they hold.
44    ///
45    /// The one authority beside the record. The caller saved each one's
46    /// bytes before the landing, so a named destination is overwritten,
47    /// or taken back where the release no longer lands it, rather than
48    /// refused.
49    pub replace: Vec<String>,
50}
51
52/// Write the candidate into the target, and record it last.
53///
54/// The caller holds the target lock for the whole of this, including the
55/// observation it passes in: a candidate rendered before the lock would
56/// describe a target somebody else could still be changing.
57///
58/// # Errors
59///
60/// [`AppError::Refused`] where a destination escapes the target or holds
61/// bytes no record accounts for, [`AppError::Busy`] where another process
62/// holds the target, and I/O errors of the writes themselves.
63pub fn land(
64    target: &Utf8Path,
65    candidate: &Candidate,
66    recorded: &Recorded,
67) -> Result<Outcome, AppError> {
68    contained(target, candidate)?;
69    unattributed_packages(target, recorded)?;
70    unattributed(target, candidate, recorded)?;
71    let retired = retired(target, candidate, recorded)?;
72    let mut outcome = Outcome::default();
73
74    for destination in &candidate.destinations {
75        let path = target.join(&destination.path);
76        if std::fs::read(&path).is_ok_and(|held| held == destination.bytes) {
77            continue;
78        }
79        if let Err(error) = write_one(target, &destination.path, &destination.bytes) {
80            // A reported rename failure is re-observed before it is
81            // believed. A remote filesystem may have completed the rename
82            // it reported as failed, and a report that called that
83            // destination unwritten would send the operator looking for
84            // bytes that are already there.
85            if std::fs::read(&path).is_ok_and(|held| held == destination.bytes) {
86                outcome.written.push(destination.path.clone());
87            }
88            return Err(stopped(&error, &outcome));
89        }
90        outcome.written.push(destination.path.clone());
91    }
92
93    for (destination, vouched) in retired {
94        let path = target.join(&destination);
95        // Re-checked here, not only when the list was built: a component
96        // swapped since then is refused rather than followed, and bytes
97        // that changed since then are left alone. A removal is authorized
98        // by the bytes the record holds, never by the path alone.
99        if let Some((_, kind)) = escapes(target, Utf8Path::new(&destination)) {
100            return Err(stopped(
101                &AppError::Refused(format!("destination {kind}: {destination}")),
102                &outcome,
103            ));
104        }
105        match std::fs::read(&path) {
106            Ok(held) if Sha256::of(&held) == vouched => {}
107            // The operator named it, and the caller saved its bytes first.
108            Ok(_) if recorded.replace.contains(&destination) => {}
109            // Gone already, or no longer the bytes the record vouches for.
110            _ => continue,
111        }
112        match std::fs::remove_file(&path) {
113            Ok(()) => {
114                prune_empty(target, &destination);
115                outcome.removed.push(destination);
116            }
117            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}
118            Err(source) => return Err(stopped(&AppError::Io(source), &outcome)),
119        }
120    }
121
122    // The record is last. Until it lands, the previous one describes the
123    // target, which is what the next run reads.
124    let record = candidate.manifest.to_json().into_bytes();
125    if let Err(error) = write_one(target, Utf8Path::new(MANIFEST_PATH), &record) {
126        if std::fs::read(target.join(MANIFEST_PATH)).is_ok_and(|held| held == record) {
127            outcome.written.push(Utf8PathBuf::from(MANIFEST_PATH));
128        }
129        return Err(stopped(&error, &outcome));
130    }
131    outcome.written.push(Utf8PathBuf::from(MANIFEST_PATH));
132    Ok(outcome)
133}
134
135/// Replace one destination in its own directory.
136///
137/// The chain is inspected again immediately before the rename, so a
138/// component swapped between the check and the write is refused rather
139/// than followed.
140fn write_one(target: &Utf8Path, destination: &Utf8Path, bytes: &[u8]) -> Result<(), AppError> {
141    let refuse = || {
142        escapes(target, destination)
143            .map(|(component, kind)| AppError::Refused(format!("{component} {kind}")))
144    };
145    // Before the scratch file is created, so nothing is written through a
146    // component that already escapes.
147    if let Some(refusal) = refuse() {
148        return Err(refusal);
149    }
150    let path = target.join(destination);
151    let scratch = Stage::write(&path, bytes)?;
152    // And again before the rename, so a component swapped in between is
153    // refused rather than followed.
154    if let Some(refusal) = refuse() {
155        Stage::discard(&scratch);
156        return Err(refusal);
157    }
158    Stage::replace(&scratch, &path)
159}
160
161/// The refusal a run that stopped partway carries.
162fn stopped(cause: &AppError, outcome: &Outcome) -> AppError {
163    let mut finished: Vec<String> = Vec::new();
164    if !outcome.written.is_empty() {
165        let done: Vec<String> = outcome.written.iter().map(ToString::to_string).collect();
166        finished.push(format!(
167            "these destinations hold candidate bytes: {}",
168            done.join(", ")
169        ));
170    }
171    if !outcome.removed.is_empty() {
172        finished.push(format!(
173            "these destinations were removed: {}",
174            outcome.removed.join(", ")
175        ));
176    }
177    if finished.is_empty() {
178        finished.push("nothing was written or removed".to_string());
179    }
180    AppError::Refused(format!(
181        "the landing stopped: {cause}; {}, the previous record still stands, and running this again finishes the rest",
182        finished.join("; ")
183    ))
184}
185
186/// Refuse any destination that does not resolve beneath the target.
187///
188/// Each component is inspected without being followed, so a link standing
189/// in the path cannot redirect a write outside the tree the operator named.
190fn contained(target: &Utf8Path, candidate: &Candidate) -> Result<(), AppError> {
191    let mut escaping: Vec<String> = Vec::new();
192    let mut note = |found: Option<(Utf8PathBuf, &'static str)>| {
193        if let Some((component, kind)) = found {
194            let reason = format!("{component} {kind}");
195            // One blocked directory holds many destinations, and naming it
196            // once is what an operator can act on.
197            if !escaping.contains(&reason) {
198                escaping.push(reason);
199            }
200        }
201    };
202    for destination in &candidate.destinations {
203        note(escapes(target, &destination.path));
204    }
205    note(escapes(target, Utf8Path::new(MANIFEST_PATH)));
206    if escaping.is_empty() {
207        return Ok(());
208    }
209    Err(AppError::Refused(format!(
210        "the landing writes nothing: {}",
211        escaping.join("; ")
212    )))
213}
214
215/// Why one destination does not resolve beneath the target, if it does not.
216fn escapes(target: &Utf8Path, destination: &Utf8Path) -> Option<(Utf8PathBuf, &'static str)> {
217    if destination.is_absolute() {
218        return Some((destination.to_owned(), "is absolute"));
219    }
220    if destination
221        .components()
222        .any(|part| part.as_str() == ".." || part.as_str() == ".")
223    {
224        return Some((destination.to_owned(), "climbs out of the target"));
225    }
226    let mut current = target.to_owned();
227    let components: Vec<&str> = destination.as_str().split('/').collect();
228    let last = components.len().saturating_sub(1);
229    for (index, part) in components.iter().enumerate() {
230        current = current.join(part);
231        let Ok(held) = std::fs::symlink_metadata(&current) else {
232            // Absent, so nothing below it exists to be redirected through.
233            return None;
234        };
235        if held.file_type().is_symlink() {
236            return Some((current, "escapes the target through a symlink"));
237        }
238        if index < last && !held.is_dir() {
239            return Some((current, "is not a directory"));
240        }
241        if index == last && !held.is_file() {
242            return Some((current, "is not a regular file"));
243        }
244    }
245    None
246}
247
248/// Why the landing would refuse one destination the operator names, where
249/// it would.
250///
251/// A destination the candidate writes, and a retired one the landing
252/// removes, must resolve beneath the target. A retired destination outside
253/// the prunable roots is one the landing leaves alone, so nothing about its
254/// path stops the landing.
255#[must_use]
256pub(crate) fn refuses_named(
257    target: &Utf8Path,
258    candidate: &Candidate,
259    destination: &str,
260) -> Option<(Utf8PathBuf, &'static str)> {
261    let written = candidate
262        .destinations
263        .iter()
264        .any(|landed| landed.path.as_str() == destination);
265    let removed = PRUNABLE_ROOTS
266        .iter()
267        .any(|prefix| destination.starts_with(prefix));
268    (written || removed)
269        .then(|| escapes(target, Utf8Path::new(destination)))
270        .flatten()
271}
272
273/// Refuse a whole file this tool would own whose bytes no record vouches
274/// for.
275///
276/// The record authorizes exact bytes, never a path. A destination whose
277/// contents are not the ones the record holds is one somebody edited or
278/// one somebody else wrote, and neither is this tool's to replace.
279/// Missing provenance routes to the agent, never to an automatic
280/// overwrite.
281fn unattributed(
282    target: &Utf8Path,
283    candidate: &Candidate,
284    recorded: &Recorded,
285) -> Result<(), AppError> {
286    let mut collisions: Vec<String> = Vec::new();
287    for destination in &candidate.destinations {
288        let path = target.join(&destination.path);
289        let Ok(held) = std::fs::read(&path) else {
290            continue;
291        };
292        if held == destination.bytes {
293            continue;
294        }
295        if vouches(recorded, &destination.path, destination.ownership, &held)
296            || recorded
297                .replace
298                .iter()
299                .any(|named| named == destination.path.as_str())
300        {
301            continue;
302        }
303        collisions.push(destination.path.to_string());
304    }
305    if collisions.is_empty() {
306        return Ok(());
307    }
308    Err(AppError::Refused(format!(
309        "destinations hold bytes no record vouches for: {}; move them aside, or let the setup skill reconcile them",
310        collisions.join(", ")
311    )))
312}
313
314/// Every skill package folder the landing must leave alone, as
315/// `<root>/<name>/`.
316///
317/// The one package-level ownership check. A folder the inventory lands
318/// into is refused whole where it holds anything and the record
319/// attributes none of its files: an extra file, or bytes equal to the
320/// candidate's, still came from somebody else. The landing, the conflict
321/// scan of `sdd upgrade`, and `sdd stage compare` all read this answer, so
322/// a preview and an apply agree.
323///
324/// SATISFIES distribution:an-unattributed-skill-folder-is-never-replaced
325#[must_use]
326pub fn refused_skill_packages(target: &Utf8Path, recorded: &Recorded) -> Vec<String> {
327    crate::embedded::skill_package_folders()
328        .into_iter()
329        .filter_map(|folder| {
330            let prefix = format!("{folder}/");
331            let holds = std::fs::read_dir(target.join(&folder))
332                .is_ok_and(|mut entries| entries.next().is_some());
333            let attributed = recorded
334                .managed
335                .iter()
336                .any(|(destination, _)| destination.starts_with(&prefix));
337            (holds && !attributed).then_some(prefix)
338        })
339        .collect()
340}
341
342/// The line that names one refused package folder.
343#[must_use]
344pub fn refused_package_line(folder: &str) -> String {
345    format!(
346        "{folder} holds a skill package no record attributes; sdd lands its own copy there, so move the folder aside and run this again (distribution:an-unattributed-skill-folder-is-never-replaced)"
347    )
348}
349
350/// Refuse every skill package folder [`refused_skill_packages`] names.
351fn unattributed_packages(target: &Utf8Path, recorded: &Recorded) -> Result<(), AppError> {
352    let refused = refused_skill_packages(target, recorded);
353    if refused.is_empty() {
354        return Ok(());
355    }
356    Err(AppError::Refused(
357        refused
358            .iter()
359            .map(|folder| refused_package_line(folder))
360            .collect::<Vec<_>>()
361            .join("\n"),
362    ))
363}
364
365/// Whether the record vouches for the bytes one destination holds.
366///
367/// The one attribution check. The landing refuses a destination this
368/// answers no for, and `sdd stage compare` reports the same answer as the
369/// record half of a destination's provenance, so the two cannot disagree.
370#[must_use]
371pub fn vouches(recorded: &Recorded, path: &Utf8Path, ownership: Ownership, held: &[u8]) -> bool {
372    match ownership {
373        Ownership::Managed => recorded
374            .managed
375            .iter()
376            .find(|(name, _)| name == path.as_str())
377            .is_some_and(|(_, digest)| digest == &Sha256::of(held)),
378        // A marked region sits in a file the project owns, so what the
379        // record vouches for is the region rather than the file. Every
380        // byte outside it is the project's and survives either way.
381        Ownership::Integration => region_vouched(path, held, recorded),
382        // An adopted destination is the project's from the moment it
383        // lands, and the projection already kept what is there.
384        Ownership::Adopted => true,
385    }
386}
387
388/// Whether the record vouches for a managed file the release retires.
389///
390/// The landing takes such a file back only where this answers yes.
391#[must_use]
392pub fn vouches_retired(recorded: &Recorded, path: &str, held: &[u8]) -> bool {
393    recorded
394        .managed
395        .iter()
396        .find(|(name, _)| name == path)
397        .is_some_and(|(_, digest)| digest == &Sha256::of(held))
398}
399
400/// Whether the record vouches for the marked region a host file holds.
401///
402/// A host with no region yet is a first landing into a file the project
403/// wrote, which the record cannot have an entry for and which the splice
404/// leaves otherwise untouched.
405fn region_vouched(path: &Utf8Path, held: &[u8], recorded: &Recorded) -> bool {
406    use crate::domain::marker;
407
408    let Ok(text) = std::str::from_utf8(held) else {
409        return false;
410    };
411    let hash = if path == crate::domain::paths::HOOKS_CONFIG_PATH {
412        marker::block_hash(text)
413    } else {
414        marker::block_hash_with(text, marker::AGENTS_BEGIN, marker::AGENTS_END)
415    };
416    let Some(hash) = hash else {
417        return true;
418    };
419    recorded
420        .integration
421        .iter()
422        .find(|(name, _)| name == path.as_str())
423        .is_some_and(|(_, recorded)| recorded == &hash)
424}
425
426/// Remove the directories one removal emptied, inside the roots this tool
427/// owns.
428///
429/// A release that stops landing a whole package would otherwise leave its
430/// directory behind, and an empty directory reads as something the tool
431/// still owns.
432fn prune_empty(target: &Utf8Path, destination: &str) {
433    let mut parent = Utf8Path::new(destination).parent();
434    while let Some(directory) = parent {
435        if !PRUNABLE_ROOTS
436            .iter()
437            .any(|prefix| format!("{directory}/").starts_with(prefix))
438        {
439            return;
440        }
441        if std::fs::remove_dir(target.join(directory)).is_err() {
442            return;
443        }
444        parent = directory.parent();
445    }
446}
447
448/// Every managed destination the record holds that this release no longer
449/// lands.
450///
451/// Only managed, and only under a root this tool owns. An adopted file a
452/// release stops seeding stays: the project owns it from the moment it
453/// lands, and a version moving is not permission to take it back. A file
454/// whose bytes are not the ones the record vouches for stays too, because
455/// somebody edited it and a removal would be a silent loss.
456fn retired(
457    target: &Utf8Path,
458    candidate: &Candidate,
459    recorded: &Recorded,
460) -> Result<Vec<(String, Sha256)>, AppError> {
461    let recorded_managed = &recorded.managed;
462    let landing: Vec<&str> = candidate
463        .destinations
464        .iter()
465        .map(|destination| destination.path.as_str())
466        .collect();
467    let mut retired = Vec::new();
468    for (destination, digest) in recorded_managed {
469        if landing.contains(&destination.as_str()) {
470            continue;
471        }
472        if !PRUNABLE_ROOTS
473            .iter()
474            .any(|prefix| destination.starts_with(prefix))
475        {
476            continue;
477        }
478        // A removal reached through a link would delete somebody else's
479        // file, so it refuses rather than following it.
480        if let Some((_, kind)) = escapes(target, Utf8Path::new(destination)) {
481            return Err(AppError::Refused(format!(
482                "destination {kind}: {destination}"
483            )));
484        }
485        let Ok(held) = std::fs::read(target.join(destination)) else {
486            continue;
487        };
488        let named = recorded.replace.contains(destination);
489        if &Sha256::of(&held) != digest && !named {
490            continue;
491        }
492        retired.push((destination.clone(), digest.clone()));
493    }
494    Ok(retired)
495}
496
497#[cfg(test)]
498mod tests {
499    #![allow(
500        clippy::unwrap_used,
501        reason = "a test panics as its failure signal, not as control flow"
502    )]
503
504    use super::*;
505    use crate::candidate::{Destination, Input, Placement, project};
506    use crate::domain::profile::ProfileId;
507    use crate::domain::version::CanonVersion;
508
509    fn target(dir: &tempfile::TempDir) -> Utf8PathBuf {
510        Utf8PathBuf::from(dir.path().to_str().unwrap())
511    }
512
513    fn candidate() -> Candidate {
514        project(&Input {
515            profile: ProfileId::Codebase,
516            version: CanonVersion::current(),
517            installed_at: "2026-01-01T00:00:00Z".to_string(),
518            docs_scratch: None,
519            reserve: Vec::new(),
520            writing_style: None,
521            acquisition: None,
522            evidence: crate::candidate::Evidence::default(),
523        })
524        .unwrap()
525    }
526
527    #[test]
528    fn a_landing_writes_every_destination_and_the_record_last() {
529        let dir = tempfile::tempdir().unwrap();
530        let target = target(&dir);
531        let candidate = candidate();
532
533        let outcome = land(&target, &candidate, &Recorded::default()).unwrap();
534
535        assert_eq!(
536            outcome.written.last().unwrap(),
537            &Utf8PathBuf::from(MANIFEST_PATH)
538        );
539        for destination in &candidate.destinations {
540            assert_eq!(
541                std::fs::read(target.join(&destination.path)).unwrap(),
542                destination.bytes,
543                "{}",
544                destination.path
545            );
546        }
547    }
548
549    /// VERIFIES distribution:an-unattributed-skill-folder-is-never-replaced
550    #[test]
551    fn the_landing_names_every_unattributed_package_folder() {
552        let candidate = candidate();
553        let landed: Vec<&Destination> = candidate
554            .destinations
555            .iter()
556            .filter(|destination| destination.path.starts_with(".claude/skills/sdd-setup"))
557            .collect();
558        let cases: [(&str, &str); 3] = [
559            (".claude/skills/sdd-setup/SKILL.md", "full"),
560            (".claude/skills/sdd-setup/extra.txt", "extra"),
561            ("", "identical"),
562        ];
563        for (path, case) in cases {
564            let dir = tempfile::tempdir().unwrap();
565            let target = target(&dir);
566            if path.is_empty() {
567                for destination in &landed {
568                    crate::adapters::fs::write_file(
569                        &target.join(&destination.path),
570                        &destination.bytes,
571                    )
572                    .unwrap();
573                }
574            } else {
575                crate::adapters::fs::write_file(&target.join(path), b"somebody else's\n").unwrap();
576            }
577            let error = land(&target, &candidate, &Recorded::default()).unwrap_err();
578            assert!(
579                error
580                    .to_string()
581                    .contains(".claude/skills/sdd-setup/ holds a skill package"),
582                "{case}: {error}"
583            );
584            assert!(
585                !target.join(crate::domain::manifest::MANIFEST_PATH).exists(),
586                "{case}: the refusal wrote the record"
587            );
588        }
589    }
590
591    #[test]
592    fn a_second_landing_writes_nothing_and_still_records() {
593        let dir = tempfile::tempdir().unwrap();
594        let target = target(&dir);
595        let candidate = candidate();
596        land(&target, &candidate, &Recorded::default()).unwrap();
597
598        // The second landing reads the record the first one wrote, as every
599        // caller does; that record attributes the landed skill packages.
600        let recorded = crate::services::installer::recorded(&target);
601        let outcome = land(&target, &candidate, &recorded).unwrap();
602        assert_eq!(outcome.written, vec![Utf8PathBuf::from(MANIFEST_PATH)]);
603    }
604
605    #[test]
606    fn a_managed_destination_no_record_accounts_for_refuses_before_any_write() {
607        let dir = tempfile::tempdir().unwrap();
608        let target = target(&dir);
609        let candidate = candidate();
610        let managed = candidate
611            .destinations
612            .iter()
613            .find(|destination| destination.ownership == Ownership::Managed)
614            .unwrap();
615        crate::adapters::fs::write_file(&target.join(&managed.path), b"somebody else wrote this")
616            .unwrap();
617
618        let error = land(&target, &candidate, &Recorded::default()).unwrap_err();
619        assert!(error.to_string().contains(managed.path.as_str()), "{error}");
620        // Nothing else landed: the refusal is before the first write.
621        assert_eq!(
622            std::fs::read(target.join(&managed.path)).unwrap(),
623            b"somebody else wrote this"
624        );
625        assert!(!target.join(MANIFEST_PATH).exists());
626    }
627
628    #[test]
629    fn a_managed_destination_edited_since_the_record_refuses() {
630        let dir = tempfile::tempdir().unwrap();
631        let target = target(&dir);
632        let candidate = candidate();
633        let managed = candidate
634            .destinations
635            .iter()
636            .find(|destination| destination.ownership == Ownership::Managed)
637            .unwrap()
638            .clone();
639        // The record names the path and vouches for other bytes, which is
640        // what a local edit to a managed file looks like.
641        crate::adapters::fs::write_file(&target.join(&managed.path), b"edited since").unwrap();
642        let recorded = Recorded {
643            managed: vec![(
644                managed.path.to_string(),
645                Sha256::of(b"what the record holds"),
646            )],
647            integration: Vec::new(),
648            replace: Vec::new(),
649        };
650
651        let error = land(&target, &candidate, &recorded).unwrap_err();
652        assert!(error.to_string().contains(managed.path.as_str()), "{error}");
653        assert_eq!(
654            std::fs::read(target.join(&managed.path)).unwrap(),
655            b"edited since"
656        );
657        assert!(!target.join(MANIFEST_PATH).exists());
658    }
659
660    #[test]
661    fn a_recorded_managed_destination_is_refreshed() {
662        let dir = tempfile::tempdir().unwrap();
663        let target = target(&dir);
664        let candidate = candidate();
665        let managed = candidate
666            .destinations
667            .iter()
668            .find(|destination| destination.ownership == Ownership::Managed)
669            .unwrap()
670            .clone();
671        crate::adapters::fs::write_file(&target.join(&managed.path), b"older").unwrap();
672        // The record vouches for exactly the bytes that are there, which is
673        // what an older landing of this tool leaves.
674        let recorded = Recorded {
675            managed: vec![(managed.path.to_string(), Sha256::of(b"older"))],
676            integration: Vec::new(),
677            replace: Vec::new(),
678        };
679
680        land(&target, &candidate, &recorded).unwrap();
681        assert_eq!(
682            std::fs::read(target.join(&managed.path)).unwrap(),
683            managed.bytes
684        );
685    }
686
687    #[test]
688    fn a_managed_file_this_release_dropped_is_taken_back() {
689        let dir = tempfile::tempdir().unwrap();
690        let target = target(&dir);
691        let dropped = ".spec-driven-docs/markdownlint/retired.jsonc";
692        crate::adapters::fs::write_file(&target.join(dropped), b"old").unwrap();
693        let recorded = Recorded {
694            managed: vec![(dropped.to_string(), Sha256::of(b"old"))],
695            integration: Vec::new(),
696            replace: Vec::new(),
697        };
698
699        let outcome = land(&target, &candidate(), &recorded).unwrap();
700        assert_eq!(outcome.removed, vec![dropped.to_string()]);
701        assert!(!target.join(dropped).exists());
702    }
703
704    #[test]
705    fn an_edited_file_this_release_dropped_stays() {
706        let dir = tempfile::tempdir().unwrap();
707        let target = target(&dir);
708        let dropped = ".spec-driven-docs/markdownlint/retired.jsonc";
709        crate::adapters::fs::write_file(&target.join(dropped), b"edited since").unwrap();
710        let recorded = Recorded {
711            managed: vec![(dropped.to_string(), Sha256::of(b"old"))],
712            integration: Vec::new(),
713            replace: Vec::new(),
714        };
715
716        let outcome = land(&target, &candidate(), &recorded).unwrap();
717        assert!(outcome.removed.is_empty());
718        assert!(target.join(dropped).exists());
719    }
720
721    #[test]
722    fn a_named_destination_is_overwritten_and_a_named_retired_file_taken_back() {
723        let dir = tempfile::tempdir().unwrap();
724        let target = target(&dir);
725        let candidate = candidate();
726        let managed = candidate
727            .destinations
728            .iter()
729            .find(|destination| destination.ownership == Ownership::Managed)
730            .unwrap()
731            .clone();
732        crate::adapters::fs::write_file(&target.join(&managed.path), b"edited since").unwrap();
733        let dropped = ".spec-driven-docs/markdownlint/retired.jsonc";
734        crate::adapters::fs::write_file(&target.join(dropped), b"edited since").unwrap();
735        let recorded = Recorded {
736            managed: vec![
737                (managed.path.to_string(), Sha256::of(b"older")),
738                (dropped.to_string(), Sha256::of(b"old")),
739            ],
740            integration: Vec::new(),
741            replace: vec![managed.path.to_string(), dropped.to_string()],
742        };
743        assert!(!vouches(
744            &recorded,
745            &managed.path,
746            Ownership::Managed,
747            b"edited since"
748        ));
749
750        let outcome = land(&target, &candidate, &recorded).unwrap();
751        assert_eq!(
752            std::fs::read(target.join(&managed.path)).unwrap(),
753            managed.bytes
754        );
755        assert_eq!(outcome.removed, vec![dropped.to_string()]);
756    }
757
758    #[test]
759    fn a_destination_reached_through_a_link_refuses() {
760        let dir = tempfile::tempdir().unwrap();
761        let target = target(&dir);
762        let outside = target.join("outside");
763        std::fs::create_dir_all(&outside).unwrap();
764        std::os::unix::fs::symlink(outside.as_std_path(), target.join("docs").as_std_path())
765            .unwrap();
766
767        let error = land(&target, &candidate(), &Recorded::default()).unwrap_err();
768        assert!(error.to_string().contains("symlink"), "{error}");
769        assert!(!target.join(MANIFEST_PATH).exists());
770    }
771
772    #[test]
773    fn a_destination_that_climbs_out_refuses() {
774        let dir = tempfile::tempdir().unwrap();
775        let target = target(&dir);
776        let mut candidate = candidate();
777        candidate.destinations.push(Destination {
778            path: Utf8PathBuf::from("../escaped.md"),
779            bytes: b"x".to_vec(),
780            ownership: Ownership::Managed,
781            placement: Placement::WholeFile,
782            source: None,
783        });
784
785        let error = land(&target, &candidate, &Recorded::default()).unwrap_err();
786        assert!(error.to_string().contains("climbs out"), "{error}");
787    }
788}