use camino::{Utf8Path, Utf8PathBuf};
use crate::candidate::{Candidate, Ownership};
use crate::domain::manifest::MANIFEST_PATH;
use crate::domain::ownership::Sha256;
use crate::domain::paths::PRUNABLE_ROOTS;
use crate::error::AppError;
use crate::transaction::stage::Stage;
#[derive(Debug, Default)]
pub struct Outcome {
pub written: Vec<Utf8PathBuf>,
pub removed: Vec<String>,
pub dropped: Vec<String>,
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Departures {
pub retired: Vec<(String, Sha256)>,
pub dropped: Vec<String>,
}
impl Departures {
#[must_use]
pub fn into_paths(self) -> (Vec<String>, Vec<String>) {
let retired = self.retired.into_iter().map(|(path, _)| path).collect();
(retired, self.dropped)
}
}
#[derive(Debug, Default, Clone)]
pub struct Recorded {
pub managed: Vec<(String, Sha256)>,
pub integration: Vec<(String, Sha256)>,
pub replace: Vec<String>,
}
pub fn land(
target: &Utf8Path,
candidate: &Candidate,
recorded: &Recorded,
) -> Result<Outcome, AppError> {
contained(target, candidate)?;
unattributed_packages(target, recorded)?;
unattributed(target, candidate, recorded)?;
let departures = departures(target, candidate, recorded);
let mut outcome = Outcome {
dropped: departures.dropped,
..Outcome::default()
};
for destination in &candidate.destinations {
let path = target.join(&destination.path);
if std::fs::read(&path).is_ok_and(|held| held == destination.bytes) {
continue;
}
if let Err(error) = write_one(target, &destination.path, &destination.bytes) {
if std::fs::read(&path).is_ok_and(|held| held == destination.bytes) {
outcome.written.push(destination.path.clone());
}
return Err(stopped(&error, &outcome));
}
outcome.written.push(destination.path.clone());
}
for (destination, vouched) in departures.retired {
let path = target.join(&destination);
if let Some((_, kind)) = escapes(target, Utf8Path::new(&destination)) {
return Err(stopped(
&AppError::Refused(format!("destination {kind}: {destination}")),
&outcome,
));
}
match std::fs::read(&path) {
Ok(held) if Sha256::of(&held) == vouched => {}
Ok(_) => {
outcome.dropped.push(destination);
continue;
}
Err(_) => continue,
}
match std::fs::remove_file(&path) {
Ok(()) => {
prune_empty(target, &destination);
outcome.removed.push(destination);
}
Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}
Err(source) => return Err(stopped(&AppError::Io(source), &outcome)),
}
}
let record = candidate.manifest.to_json().into_bytes();
if let Err(error) = write_one(target, Utf8Path::new(MANIFEST_PATH), &record) {
if std::fs::read(target.join(MANIFEST_PATH)).is_ok_and(|held| held == record) {
outcome.written.push(Utf8PathBuf::from(MANIFEST_PATH));
}
return Err(stopped(&error, &outcome));
}
outcome.written.push(Utf8PathBuf::from(MANIFEST_PATH));
Ok(outcome)
}
fn write_one(target: &Utf8Path, destination: &Utf8Path, bytes: &[u8]) -> Result<(), AppError> {
let refuse = || {
escapes(target, destination)
.map(|(component, kind)| AppError::Refused(format!("{component} {kind}")))
};
if let Some(refusal) = refuse() {
return Err(refusal);
}
let path = target.join(destination);
let scratch = Stage::write(&path, bytes)?;
if let Some(refusal) = refuse() {
Stage::discard(&scratch);
return Err(refusal);
}
Stage::replace(&scratch, &path)
}
fn stopped(cause: &AppError, outcome: &Outcome) -> AppError {
let mut finished: Vec<String> = Vec::new();
if !outcome.written.is_empty() {
let done: Vec<String> = outcome.written.iter().map(ToString::to_string).collect();
finished.push(format!(
"these destinations hold candidate bytes: {}",
done.join(", ")
));
}
if !outcome.removed.is_empty() {
finished.push(format!(
"these destinations were removed: {}",
outcome.removed.join(", ")
));
}
if finished.is_empty() {
finished.push("nothing was written or removed".to_string());
}
AppError::Refused(format!(
"the landing stopped: {cause}; {}, the previous record still stands, and running this again finishes the rest",
finished.join("; ")
))
}
fn contained(target: &Utf8Path, candidate: &Candidate) -> Result<(), AppError> {
let mut escaping: Vec<String> = Vec::new();
let mut note = |found: Option<(Utf8PathBuf, &'static str)>| {
if let Some((component, kind)) = found {
let reason = format!("{component} {kind}");
if !escaping.contains(&reason) {
escaping.push(reason);
}
}
};
for destination in &candidate.destinations {
note(escapes(target, &destination.path));
}
note(escapes(target, Utf8Path::new(MANIFEST_PATH)));
if escaping.is_empty() {
return Ok(());
}
Err(AppError::Refused(format!(
"the landing writes nothing: {}",
escaping.join("; ")
)))
}
fn escapes(target: &Utf8Path, destination: &Utf8Path) -> Option<(Utf8PathBuf, &'static str)> {
if destination.is_absolute() {
return Some((destination.to_owned(), "is absolute"));
}
if destination
.components()
.any(|part| part.as_str() == ".." || part.as_str() == ".")
{
return Some((destination.to_owned(), "climbs out of the target"));
}
let mut current = target.to_owned();
let components: Vec<&str> = destination.as_str().split('/').collect();
let last = components.len().saturating_sub(1);
for (index, part) in components.iter().enumerate() {
current = current.join(part);
let Ok(held) = std::fs::symlink_metadata(¤t) else {
return None;
};
if held.file_type().is_symlink() {
return Some((current, "escapes the target through a symlink"));
}
if index < last && !held.is_dir() {
return Some((current, "is not a directory"));
}
if index == last && !held.is_file() {
return Some((current, "is not a regular file"));
}
}
None
}
#[must_use]
pub(crate) fn refuses_named(
target: &Utf8Path,
candidate: &Candidate,
destination: &str,
) -> Option<(Utf8PathBuf, &'static str)> {
candidate
.destinations
.iter()
.any(|landed| landed.path.as_str() == destination)
.then(|| escapes(target, Utf8Path::new(destination)))
.flatten()
}
fn unattributed(
target: &Utf8Path,
candidate: &Candidate,
recorded: &Recorded,
) -> Result<(), AppError> {
let mut collisions: Vec<String> = Vec::new();
for destination in &candidate.destinations {
let path = target.join(&destination.path);
let Ok(held) = std::fs::read(&path) else {
continue;
};
if held == destination.bytes {
continue;
}
if vouches(recorded, &destination.path, destination.ownership, &held)
|| recorded
.replace
.iter()
.any(|named| named == destination.path.as_str())
{
continue;
}
collisions.push(destination.path.to_string());
}
if collisions.is_empty() {
return Ok(());
}
Err(AppError::Refused(format!(
"destinations hold bytes no record vouches for: {}; move them aside, or let the setup skill reconcile them",
collisions.join(", ")
)))
}
#[must_use]
pub fn refused_skill_packages(target: &Utf8Path, recorded: &Recorded) -> Vec<String> {
crate::embedded::skill_package_folders()
.into_iter()
.filter_map(|folder| {
let prefix = format!("{folder}/");
let holds = std::fs::read_dir(target.join(&folder))
.is_ok_and(|mut entries| entries.next().is_some());
let attributed = recorded
.managed
.iter()
.any(|(destination, _)| destination.starts_with(&prefix));
(holds && !attributed).then_some(prefix)
})
.collect()
}
#[must_use]
pub fn refused_package_line(folder: &str) -> String {
format!(
"{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)"
)
}
fn unattributed_packages(target: &Utf8Path, recorded: &Recorded) -> Result<(), AppError> {
let refused = refused_skill_packages(target, recorded);
if refused.is_empty() {
return Ok(());
}
Err(AppError::Refused(
refused
.iter()
.map(|folder| refused_package_line(folder))
.collect::<Vec<_>>()
.join("\n"),
))
}
#[must_use]
pub fn vouches(recorded: &Recorded, path: &Utf8Path, ownership: Ownership, held: &[u8]) -> bool {
match ownership {
Ownership::Managed => recorded
.managed
.iter()
.find(|(name, _)| name == path.as_str())
.is_some_and(|(_, digest)| digest == &Sha256::of(held)),
Ownership::Integration => region_vouched(path, held, recorded),
Ownership::Adopted => true,
}
}
fn region_vouched(path: &Utf8Path, held: &[u8], recorded: &Recorded) -> bool {
use crate::domain::marker;
let Ok(text) = std::str::from_utf8(held) else {
return false;
};
let hash = if path == crate::domain::paths::HOOKS_CONFIG_PATH {
marker::block_hash(text)
} else {
marker::block_hash_with(text, marker::AGENTS_BEGIN, marker::AGENTS_END)
};
let Some(hash) = hash else {
return true;
};
recorded
.integration
.iter()
.find(|(name, _)| name == path.as_str())
.is_some_and(|(_, recorded)| recorded == &hash)
}
fn prune_empty(target: &Utf8Path, destination: &str) {
let mut parent = Utf8Path::new(destination).parent();
while let Some(directory) = parent {
if !PRUNABLE_ROOTS
.iter()
.any(|prefix| format!("{directory}/").starts_with(prefix))
{
return;
}
if std::fs::remove_dir(target.join(directory)).is_err() {
return;
}
parent = directory.parent();
}
}
#[must_use]
pub fn departures(target: &Utf8Path, candidate: &Candidate, recorded: &Recorded) -> Departures {
let landing: Vec<&str> = candidate
.destinations
.iter()
.map(|destination| destination.path.as_str())
.collect();
departures_from(target, &landing, recorded)
}
#[must_use]
pub fn departures_from(target: &Utf8Path, landing: &[&str], recorded: &Recorded) -> Departures {
let mut departures = Departures::default();
for (destination, digest) in &recorded.managed {
if landing.contains(&destination.as_str()) {
continue;
}
if escapes(target, Utf8Path::new(destination)).is_some() {
departures.dropped.push(destination.clone());
continue;
}
match std::fs::read(target.join(destination)) {
Ok(held) if &Sha256::of(&held) == digest => {
departures
.retired
.push((destination.clone(), digest.clone()));
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
_ => departures.dropped.push(destination.clone()),
}
}
departures
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
reason = "a test panics as its failure signal, not as control flow"
)]
use super::*;
use crate::candidate::{Destination, Input, Placement, project};
use crate::domain::profile::ProfileId;
use crate::domain::version::CanonVersion;
fn target(dir: &tempfile::TempDir) -> Utf8PathBuf {
Utf8PathBuf::from(dir.path().to_str().unwrap())
}
fn candidate() -> Candidate {
project(&Input {
profile: ProfileId::Codebase,
version: CanonVersion::current(),
installed_at: "2026-01-01T00:00:00Z".to_string(),
docs_scratch: None,
reserve: Vec::new(),
writing_style: None,
acquisition: None,
evidence: crate::candidate::Evidence::default(),
})
.unwrap()
}
#[test]
fn a_landing_writes_every_destination_and_the_record_last() {
let dir = tempfile::tempdir().unwrap();
let target = target(&dir);
let candidate = candidate();
let outcome = land(&target, &candidate, &Recorded::default()).unwrap();
assert_eq!(
outcome.written.last().unwrap(),
&Utf8PathBuf::from(MANIFEST_PATH)
);
for destination in &candidate.destinations {
assert_eq!(
std::fs::read(target.join(&destination.path)).unwrap(),
destination.bytes,
"{}",
destination.path
);
}
}
#[test]
fn the_landing_names_every_unattributed_package_folder() {
let candidate = candidate();
let landed: Vec<&Destination> = candidate
.destinations
.iter()
.filter(|destination| destination.path.starts_with(".claude/skills/sdd-setup"))
.collect();
let cases: [(&str, &str); 3] = [
(".claude/skills/sdd-setup/SKILL.md", "full"),
(".claude/skills/sdd-setup/extra.txt", "extra"),
("", "identical"),
];
for (path, case) in cases {
let dir = tempfile::tempdir().unwrap();
let target = target(&dir);
if path.is_empty() {
for destination in &landed {
crate::adapters::fs::write_file(
&target.join(&destination.path),
&destination.bytes,
)
.unwrap();
}
} else {
crate::adapters::fs::write_file(&target.join(path), b"somebody else's\n").unwrap();
}
let error = land(&target, &candidate, &Recorded::default()).unwrap_err();
assert!(
error
.to_string()
.contains(".claude/skills/sdd-setup/ holds a skill package"),
"{case}: {error}"
);
assert!(
!target.join(crate::domain::manifest::MANIFEST_PATH).exists(),
"{case}: the refusal wrote the record"
);
}
}
#[test]
fn a_second_landing_writes_nothing_and_still_records() {
let dir = tempfile::tempdir().unwrap();
let target = target(&dir);
let candidate = candidate();
land(&target, &candidate, &Recorded::default()).unwrap();
let recorded = crate::services::installer::recorded(&target);
let outcome = land(&target, &candidate, &recorded).unwrap();
assert_eq!(outcome.written, vec![Utf8PathBuf::from(MANIFEST_PATH)]);
}
#[test]
fn a_managed_destination_no_record_accounts_for_refuses_before_any_write() {
let dir = tempfile::tempdir().unwrap();
let target = target(&dir);
let candidate = candidate();
let managed = candidate
.destinations
.iter()
.find(|destination| destination.ownership == Ownership::Managed)
.unwrap();
crate::adapters::fs::write_file(&target.join(&managed.path), b"somebody else wrote this")
.unwrap();
let error = land(&target, &candidate, &Recorded::default()).unwrap_err();
assert!(error.to_string().contains(managed.path.as_str()), "{error}");
assert_eq!(
std::fs::read(target.join(&managed.path)).unwrap(),
b"somebody else wrote this"
);
assert!(!target.join(MANIFEST_PATH).exists());
}
#[test]
fn a_managed_destination_edited_since_the_record_refuses() {
let dir = tempfile::tempdir().unwrap();
let target = target(&dir);
let candidate = candidate();
let managed = candidate
.destinations
.iter()
.find(|destination| destination.ownership == Ownership::Managed)
.unwrap()
.clone();
crate::adapters::fs::write_file(&target.join(&managed.path), b"edited since").unwrap();
let recorded = Recorded {
managed: vec![(
managed.path.to_string(),
Sha256::of(b"what the record holds"),
)],
integration: Vec::new(),
replace: Vec::new(),
};
let error = land(&target, &candidate, &recorded).unwrap_err();
assert!(error.to_string().contains(managed.path.as_str()), "{error}");
assert_eq!(
std::fs::read(target.join(&managed.path)).unwrap(),
b"edited since"
);
assert!(!target.join(MANIFEST_PATH).exists());
}
#[test]
fn a_recorded_managed_destination_is_refreshed() {
let dir = tempfile::tempdir().unwrap();
let target = target(&dir);
let candidate = candidate();
let managed = candidate
.destinations
.iter()
.find(|destination| destination.ownership == Ownership::Managed)
.unwrap()
.clone();
crate::adapters::fs::write_file(&target.join(&managed.path), b"older").unwrap();
let recorded = Recorded {
managed: vec![(managed.path.to_string(), Sha256::of(b"older"))],
integration: Vec::new(),
replace: Vec::new(),
};
land(&target, &candidate, &recorded).unwrap();
assert_eq!(
std::fs::read(target.join(&managed.path)).unwrap(),
managed.bytes
);
}
#[test]
fn an_unedited_managed_file_this_release_stops_landing_is_retired() {
let dir = tempfile::tempdir().unwrap();
let target = target(&dir);
let retired = ".spec-driven-docs/markdownlint/retired.jsonc";
crate::adapters::fs::write_file(&target.join(retired), b"old").unwrap();
let recorded = Recorded {
managed: vec![(retired.to_string(), Sha256::of(b"old"))],
integration: Vec::new(),
replace: Vec::new(),
};
let outcome = land(&target, &candidate(), &recorded).unwrap();
assert_eq!(outcome.removed, vec![retired.to_string()]);
assert!(outcome.dropped.is_empty());
assert!(!target.join(retired).exists());
assert!(
!target.join(".spec-driven-docs/markdownlint").exists(),
"the emptied directory inside the instance stayed"
);
}
#[test]
fn an_unedited_retired_file_outside_the_owned_roots_is_deleted() {
let dir = tempfile::tempdir().unwrap();
let target = target(&dir);
let retired = "docs/lint/retired.jsonc";
crate::adapters::fs::write_file(&target.join(retired), b"old").unwrap();
let recorded = Recorded {
managed: vec![(retired.to_string(), Sha256::of(b"old"))],
integration: Vec::new(),
replace: Vec::new(),
};
let outcome = land(&target, &candidate(), &recorded).unwrap();
assert_eq!(outcome.removed, vec![retired.to_string()]);
assert!(!target.join(retired).exists());
assert!(
target.join("docs/lint").is_dir(),
"a project directory went"
);
}
#[test]
fn an_edited_file_this_release_stops_landing_is_dropped() {
let dir = tempfile::tempdir().unwrap();
let target = target(&dir);
let inside = ".spec-driven-docs/markdownlint/retired.jsonc";
let outside = "docs/lint/retired.jsonc";
let gone = ".claude/skills/old/SKILL.md";
for path in [inside, outside] {
crate::adapters::fs::write_file(&target.join(path), b"edited since").unwrap();
}
let recorded = Recorded {
managed: vec![
(inside.to_string(), Sha256::of(b"old")),
(outside.to_string(), Sha256::of(b"old")),
(gone.to_string(), Sha256::of(b"old")),
],
integration: Vec::new(),
replace: Vec::new(),
};
let outcome = land(&target, &candidate(), &recorded).unwrap();
assert!(outcome.removed.is_empty());
assert_eq!(
outcome.dropped,
vec![inside.to_string(), outside.to_string()]
);
for path in [inside, outside] {
assert_eq!(std::fs::read(target.join(path)).unwrap(), b"edited since");
}
let record = std::fs::read_to_string(target.join(MANIFEST_PATH)).unwrap();
for path in [inside, outside, gone] {
assert!(!record.contains(path), "{path} stayed in the record");
}
}
#[test]
fn a_named_destination_is_overwritten() {
let dir = tempfile::tempdir().unwrap();
let target = target(&dir);
let candidate = candidate();
let managed = candidate
.destinations
.iter()
.find(|destination| destination.ownership == Ownership::Managed)
.unwrap()
.clone();
crate::adapters::fs::write_file(&target.join(&managed.path), b"edited since").unwrap();
let recorded = Recorded {
managed: vec![(managed.path.to_string(), Sha256::of(b"older"))],
integration: Vec::new(),
replace: vec![managed.path.to_string()],
};
assert!(!vouches(
&recorded,
&managed.path,
Ownership::Managed,
b"edited since"
));
land(&target, &candidate, &recorded).unwrap();
assert_eq!(
std::fs::read(target.join(&managed.path)).unwrap(),
managed.bytes
);
}
#[test]
fn a_destination_reached_through_a_link_refuses() {
let dir = tempfile::tempdir().unwrap();
let target = target(&dir);
let outside = target.join("outside");
std::fs::create_dir_all(&outside).unwrap();
std::os::unix::fs::symlink(outside.as_std_path(), target.join("docs").as_std_path())
.unwrap();
let error = land(&target, &candidate(), &Recorded::default()).unwrap_err();
assert!(error.to_string().contains("symlink"), "{error}");
assert!(!target.join(MANIFEST_PATH).exists());
}
#[test]
fn a_destination_that_climbs_out_refuses() {
let dir = tempfile::tempdir().unwrap();
let target = target(&dir);
let mut candidate = candidate();
candidate.destinations.push(Destination {
path: Utf8PathBuf::from("../escaped.md"),
bytes: b"x".to_vec(),
ownership: Ownership::Managed,
placement: Placement::WholeFile,
source: None,
});
let error = land(&target, &candidate, &Recorded::default()).unwrap_err();
assert!(error.to_string().contains("climbs out"), "{error}");
}
}