1use 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#[derive(Debug, Default)]
25pub struct Outcome {
26 pub written: Vec<Utf8PathBuf>,
28 pub removed: Vec<String>,
31 pub dropped: Vec<String>,
35}
36
37#[derive(Debug, Default, Clone, PartialEq, Eq)]
42pub struct Departures {
43 pub retired: Vec<(String, Sha256)>,
46 pub dropped: Vec<String>,
48}
49
50impl Departures {
51 #[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#[derive(Debug, Default, Clone)]
65pub struct Recorded {
66 pub managed: Vec<(String, Sha256)>,
68 pub integration: Vec<(String, Sha256)>,
70 pub replace: Vec<String>,
76}
77
78pub 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 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 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 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 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
167fn 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 if let Some(refusal) = refuse() {
180 return Err(refusal);
181 }
182 let path = target.join(destination);
183 let scratch = Stage::write(&path, bytes)?;
184 if let Some(refusal) = refuse() {
187 Stage::discard(&scratch);
188 return Err(refusal);
189 }
190 Stage::replace(&scratch, &path)
191}
192
193fn 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
218fn 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 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
247fn 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(¤t) else {
264 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#[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
299fn 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#[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#[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
376fn 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#[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 Ownership::Integration => region_vouched(path, held, recorded),
408 Ownership::Adopted => true,
411 }
412}
413
414fn 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
440fn 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#[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#[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 #[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 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 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 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 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 #[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 #[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 #[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}