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