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>,
30}
31
32#[derive(Debug, Default, Clone)]
38pub struct Recorded {
39 pub managed: Vec<(String, Sha256)>,
41 pub integration: Vec<(String, Sha256)>,
43 pub replace: Vec<String>,
50}
51
52pub 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 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 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 Ok(_) if recorded.replace.contains(&destination) => {}
109 _ => 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 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
135fn 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 if let Some(refusal) = refuse() {
148 return Err(refusal);
149 }
150 let path = target.join(destination);
151 let scratch = Stage::write(&path, bytes)?;
152 if let Some(refusal) = refuse() {
155 Stage::discard(&scratch);
156 return Err(refusal);
157 }
158 Stage::replace(&scratch, &path)
159}
160
161fn 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
186fn 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 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
215fn 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(¤t) else {
232 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#[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
273fn 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#[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#[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
350fn 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#[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 Ownership::Integration => region_vouched(path, held, recorded),
382 Ownership::Adopted => true,
385 }
386}
387
388#[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
400fn 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
426fn 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
448fn 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 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 #[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 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 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 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 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}