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(target, candidate, recorded)?;
70 let retired = retired(target, candidate, recorded)?;
71 let mut outcome = Outcome::default();
72
73 for destination in &candidate.destinations {
74 let path = target.join(&destination.path);
75 if std::fs::read(&path).is_ok_and(|held| held == destination.bytes) {
76 continue;
77 }
78 if let Err(error) = write_one(target, &destination.path, &destination.bytes) {
79 if std::fs::read(&path).is_ok_and(|held| held == destination.bytes) {
85 outcome.written.push(destination.path.clone());
86 }
87 return Err(stopped(&error, &outcome));
88 }
89 outcome.written.push(destination.path.clone());
90 }
91
92 for (destination, vouched) in retired {
93 let path = target.join(&destination);
94 if let Some((_, kind)) = escapes(target, Utf8Path::new(&destination)) {
99 return Err(stopped(
100 &AppError::Refused(format!("destination {kind}: {destination}")),
101 &outcome,
102 ));
103 }
104 match std::fs::read(&path) {
105 Ok(held) if Sha256::of(&held) == vouched => {}
106 Ok(_) if recorded.replace.contains(&destination) => {}
108 _ => continue,
110 }
111 match std::fs::remove_file(&path) {
112 Ok(()) => {
113 prune_empty(target, &destination);
114 outcome.removed.push(destination);
115 }
116 Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}
117 Err(source) => return Err(stopped(&AppError::Io(source), &outcome)),
118 }
119 }
120
121 let record = candidate.manifest.to_json().into_bytes();
124 if let Err(error) = write_one(target, Utf8Path::new(MANIFEST_PATH), &record) {
125 if std::fs::read(target.join(MANIFEST_PATH)).is_ok_and(|held| held == record) {
126 outcome.written.push(Utf8PathBuf::from(MANIFEST_PATH));
127 }
128 return Err(stopped(&error, &outcome));
129 }
130 outcome.written.push(Utf8PathBuf::from(MANIFEST_PATH));
131 Ok(outcome)
132}
133
134fn write_one(target: &Utf8Path, destination: &Utf8Path, bytes: &[u8]) -> Result<(), AppError> {
140 let refuse = || {
141 escapes(target, destination)
142 .map(|(component, kind)| AppError::Refused(format!("{component} {kind}")))
143 };
144 if let Some(refusal) = refuse() {
147 return Err(refusal);
148 }
149 let path = target.join(destination);
150 let scratch = Stage::write(&path, bytes)?;
151 if let Some(refusal) = refuse() {
154 Stage::discard(&scratch);
155 return Err(refusal);
156 }
157 Stage::replace(&scratch, &path)
158}
159
160fn stopped(cause: &AppError, outcome: &Outcome) -> AppError {
162 let mut finished: Vec<String> = Vec::new();
163 if !outcome.written.is_empty() {
164 let done: Vec<String> = outcome.written.iter().map(ToString::to_string).collect();
165 finished.push(format!(
166 "these destinations hold candidate bytes: {}",
167 done.join(", ")
168 ));
169 }
170 if !outcome.removed.is_empty() {
171 finished.push(format!(
172 "these destinations were removed: {}",
173 outcome.removed.join(", ")
174 ));
175 }
176 if finished.is_empty() {
177 finished.push("nothing was written or removed".to_string());
178 }
179 AppError::Refused(format!(
180 "the landing stopped: {cause}; {}, the previous record still stands, and running this again finishes the rest",
181 finished.join("; ")
182 ))
183}
184
185fn contained(target: &Utf8Path, candidate: &Candidate) -> Result<(), AppError> {
190 let mut escaping: Vec<String> = Vec::new();
191 let mut note = |found: Option<(Utf8PathBuf, &'static str)>| {
192 if let Some((component, kind)) = found {
193 let reason = format!("{component} {kind}");
194 if !escaping.contains(&reason) {
197 escaping.push(reason);
198 }
199 }
200 };
201 for destination in &candidate.destinations {
202 note(escapes(target, &destination.path));
203 }
204 note(escapes(target, Utf8Path::new(MANIFEST_PATH)));
205 if escaping.is_empty() {
206 return Ok(());
207 }
208 Err(AppError::Refused(format!(
209 "the landing writes nothing: {}",
210 escaping.join("; ")
211 )))
212}
213
214fn escapes(target: &Utf8Path, destination: &Utf8Path) -> Option<(Utf8PathBuf, &'static str)> {
216 if destination.is_absolute() {
217 return Some((destination.to_owned(), "is absolute"));
218 }
219 if destination
220 .components()
221 .any(|part| part.as_str() == ".." || part.as_str() == ".")
222 {
223 return Some((destination.to_owned(), "climbs out of the target"));
224 }
225 let mut current = target.to_owned();
226 let components: Vec<&str> = destination.as_str().split('/').collect();
227 let last = components.len().saturating_sub(1);
228 for (index, part) in components.iter().enumerate() {
229 current = current.join(part);
230 let Ok(held) = std::fs::symlink_metadata(¤t) else {
231 return None;
233 };
234 if held.file_type().is_symlink() {
235 return Some((current, "escapes the target through a symlink"));
236 }
237 if index < last && !held.is_dir() {
238 return Some((current, "is not a directory"));
239 }
240 if index == last && !held.is_file() {
241 return Some((current, "is not a regular file"));
242 }
243 }
244 None
245}
246
247#[must_use]
255pub(crate) fn refuses_named(
256 target: &Utf8Path,
257 candidate: &Candidate,
258 destination: &str,
259) -> Option<(Utf8PathBuf, &'static str)> {
260 let written = candidate
261 .destinations
262 .iter()
263 .any(|landed| landed.path.as_str() == destination);
264 let removed = PRUNABLE_ROOTS
265 .iter()
266 .any(|prefix| destination.starts_with(prefix));
267 (written || removed)
268 .then(|| escapes(target, Utf8Path::new(destination)))
269 .flatten()
270}
271
272fn unattributed(
281 target: &Utf8Path,
282 candidate: &Candidate,
283 recorded: &Recorded,
284) -> Result<(), AppError> {
285 let mut collisions: Vec<String> = Vec::new();
286 for destination in &candidate.destinations {
287 let path = target.join(&destination.path);
288 let Ok(held) = std::fs::read(&path) else {
289 continue;
290 };
291 if held == destination.bytes {
292 continue;
293 }
294 if vouches(recorded, &destination.path, destination.ownership, &held)
295 || recorded
296 .replace
297 .iter()
298 .any(|named| named == destination.path.as_str())
299 {
300 continue;
301 }
302 collisions.push(destination.path.to_string());
303 }
304 if collisions.is_empty() {
305 return Ok(());
306 }
307 Err(AppError::Refused(format!(
308 "destinations hold bytes no record vouches for: {}; move them aside, or let the setup skill reconcile them",
309 collisions.join(", ")
310 )))
311}
312
313#[must_use]
319pub fn vouches(recorded: &Recorded, path: &Utf8Path, ownership: Ownership, held: &[u8]) -> bool {
320 match ownership {
321 Ownership::Managed => recorded
322 .managed
323 .iter()
324 .find(|(name, _)| name == path.as_str())
325 .is_some_and(|(_, digest)| digest == &Sha256::of(held)),
326 Ownership::Integration => region_vouched(path, held, recorded),
330 Ownership::Adopted => true,
333 }
334}
335
336#[must_use]
340pub fn vouches_retired(recorded: &Recorded, path: &str, held: &[u8]) -> bool {
341 recorded
342 .managed
343 .iter()
344 .find(|(name, _)| name == path)
345 .is_some_and(|(_, digest)| digest == &Sha256::of(held))
346}
347
348fn region_vouched(path: &Utf8Path, held: &[u8], recorded: &Recorded) -> bool {
354 use crate::domain::marker;
355
356 let Ok(text) = std::str::from_utf8(held) else {
357 return false;
358 };
359 let hash = if path == crate::domain::paths::HOOKS_CONFIG_PATH {
360 marker::block_hash(text)
361 } else {
362 marker::block_hash_with(text, marker::AGENTS_BEGIN, marker::AGENTS_END)
363 };
364 let Some(hash) = hash else {
365 return true;
366 };
367 recorded
368 .integration
369 .iter()
370 .find(|(name, _)| name == path.as_str())
371 .is_some_and(|(_, recorded)| recorded == &hash)
372}
373
374fn prune_empty(target: &Utf8Path, destination: &str) {
381 let mut parent = Utf8Path::new(destination).parent();
382 while let Some(directory) = parent {
383 if !PRUNABLE_ROOTS
384 .iter()
385 .any(|prefix| format!("{directory}/").starts_with(prefix))
386 {
387 return;
388 }
389 if std::fs::remove_dir(target.join(directory)).is_err() {
390 return;
391 }
392 parent = directory.parent();
393 }
394}
395
396fn retired(
405 target: &Utf8Path,
406 candidate: &Candidate,
407 recorded: &Recorded,
408) -> Result<Vec<(String, Sha256)>, AppError> {
409 let recorded_managed = &recorded.managed;
410 let landing: Vec<&str> = candidate
411 .destinations
412 .iter()
413 .map(|destination| destination.path.as_str())
414 .collect();
415 let mut retired = Vec::new();
416 for (destination, digest) in recorded_managed {
417 if landing.contains(&destination.as_str()) {
418 continue;
419 }
420 if !PRUNABLE_ROOTS
421 .iter()
422 .any(|prefix| destination.starts_with(prefix))
423 {
424 continue;
425 }
426 if let Some((_, kind)) = escapes(target, Utf8Path::new(destination)) {
429 return Err(AppError::Refused(format!(
430 "destination {kind}: {destination}"
431 )));
432 }
433 let Ok(held) = std::fs::read(target.join(destination)) else {
434 continue;
435 };
436 let named = recorded.replace.contains(destination);
437 if &Sha256::of(&held) != digest && !named {
438 continue;
439 }
440 retired.push((destination.clone(), digest.clone()));
441 }
442 Ok(retired)
443}
444
445#[cfg(test)]
446mod tests {
447 #![allow(
448 clippy::unwrap_used,
449 reason = "a test panics as its failure signal, not as control flow"
450 )]
451
452 use super::*;
453 use crate::candidate::{Destination, Input, Placement, project};
454 use crate::domain::profile::ProfileId;
455 use crate::domain::version::CanonVersion;
456
457 fn target(dir: &tempfile::TempDir) -> Utf8PathBuf {
458 Utf8PathBuf::from(dir.path().to_str().unwrap())
459 }
460
461 fn candidate() -> Candidate {
462 project(&Input {
463 profile: ProfileId::Codebase,
464 version: CanonVersion::current(),
465 installed_at: "2026-01-01T00:00:00Z".to_string(),
466 docs_scratch: None,
467 reserve: Vec::new(),
468 writing_style: None,
469 acquisition: None,
470 evidence: crate::candidate::Evidence::default(),
471 })
472 .unwrap()
473 }
474
475 #[test]
476 fn a_landing_writes_every_destination_and_the_record_last() {
477 let dir = tempfile::tempdir().unwrap();
478 let target = target(&dir);
479 let candidate = candidate();
480
481 let outcome = land(&target, &candidate, &Recorded::default()).unwrap();
482
483 assert_eq!(
484 outcome.written.last().unwrap(),
485 &Utf8PathBuf::from(MANIFEST_PATH)
486 );
487 for destination in &candidate.destinations {
488 assert_eq!(
489 std::fs::read(target.join(&destination.path)).unwrap(),
490 destination.bytes,
491 "{}",
492 destination.path
493 );
494 }
495 }
496
497 #[test]
498 fn a_second_landing_writes_nothing_and_still_records() {
499 let dir = tempfile::tempdir().unwrap();
500 let target = target(&dir);
501 let candidate = candidate();
502 land(&target, &candidate, &Recorded::default()).unwrap();
503
504 let outcome = land(&target, &candidate, &Recorded::default()).unwrap();
505 assert_eq!(outcome.written, vec![Utf8PathBuf::from(MANIFEST_PATH)]);
506 }
507
508 #[test]
509 fn a_managed_destination_no_record_accounts_for_refuses_before_any_write() {
510 let dir = tempfile::tempdir().unwrap();
511 let target = target(&dir);
512 let candidate = candidate();
513 let managed = candidate
514 .destinations
515 .iter()
516 .find(|destination| destination.ownership == Ownership::Managed)
517 .unwrap();
518 crate::adapters::fs::write_file(&target.join(&managed.path), b"somebody else wrote this")
519 .unwrap();
520
521 let error = land(&target, &candidate, &Recorded::default()).unwrap_err();
522 assert!(error.to_string().contains(managed.path.as_str()), "{error}");
523 assert_eq!(
525 std::fs::read(target.join(&managed.path)).unwrap(),
526 b"somebody else wrote this"
527 );
528 assert!(!target.join(MANIFEST_PATH).exists());
529 }
530
531 #[test]
532 fn a_managed_destination_edited_since_the_record_refuses() {
533 let dir = tempfile::tempdir().unwrap();
534 let target = target(&dir);
535 let candidate = candidate();
536 let managed = candidate
537 .destinations
538 .iter()
539 .find(|destination| destination.ownership == Ownership::Managed)
540 .unwrap()
541 .clone();
542 crate::adapters::fs::write_file(&target.join(&managed.path), b"edited since").unwrap();
545 let recorded = Recorded {
546 managed: vec![(
547 managed.path.to_string(),
548 Sha256::of(b"what the record holds"),
549 )],
550 integration: Vec::new(),
551 replace: Vec::new(),
552 };
553
554 let error = land(&target, &candidate, &recorded).unwrap_err();
555 assert!(error.to_string().contains(managed.path.as_str()), "{error}");
556 assert_eq!(
557 std::fs::read(target.join(&managed.path)).unwrap(),
558 b"edited since"
559 );
560 assert!(!target.join(MANIFEST_PATH).exists());
561 }
562
563 #[test]
564 fn a_recorded_managed_destination_is_refreshed() {
565 let dir = tempfile::tempdir().unwrap();
566 let target = target(&dir);
567 let candidate = candidate();
568 let managed = candidate
569 .destinations
570 .iter()
571 .find(|destination| destination.ownership == Ownership::Managed)
572 .unwrap()
573 .clone();
574 crate::adapters::fs::write_file(&target.join(&managed.path), b"older").unwrap();
575 let recorded = Recorded {
578 managed: vec![(managed.path.to_string(), Sha256::of(b"older"))],
579 integration: Vec::new(),
580 replace: Vec::new(),
581 };
582
583 land(&target, &candidate, &recorded).unwrap();
584 assert_eq!(
585 std::fs::read(target.join(&managed.path)).unwrap(),
586 managed.bytes
587 );
588 }
589
590 #[test]
591 fn a_managed_file_this_release_dropped_is_taken_back() {
592 let dir = tempfile::tempdir().unwrap();
593 let target = target(&dir);
594 let dropped = ".spec-driven-docs/markdownlint/retired.jsonc";
595 crate::adapters::fs::write_file(&target.join(dropped), b"old").unwrap();
596 let recorded = Recorded {
597 managed: vec![(dropped.to_string(), Sha256::of(b"old"))],
598 integration: Vec::new(),
599 replace: Vec::new(),
600 };
601
602 let outcome = land(&target, &candidate(), &recorded).unwrap();
603 assert_eq!(outcome.removed, vec![dropped.to_string()]);
604 assert!(!target.join(dropped).exists());
605 }
606
607 #[test]
608 fn an_edited_file_this_release_dropped_stays() {
609 let dir = tempfile::tempdir().unwrap();
610 let target = target(&dir);
611 let dropped = ".spec-driven-docs/markdownlint/retired.jsonc";
612 crate::adapters::fs::write_file(&target.join(dropped), b"edited since").unwrap();
613 let recorded = Recorded {
614 managed: vec![(dropped.to_string(), Sha256::of(b"old"))],
615 integration: Vec::new(),
616 replace: Vec::new(),
617 };
618
619 let outcome = land(&target, &candidate(), &recorded).unwrap();
620 assert!(outcome.removed.is_empty());
621 assert!(target.join(dropped).exists());
622 }
623
624 #[test]
625 fn a_named_destination_is_overwritten_and_a_named_retired_file_taken_back() {
626 let dir = tempfile::tempdir().unwrap();
627 let target = target(&dir);
628 let candidate = candidate();
629 let managed = candidate
630 .destinations
631 .iter()
632 .find(|destination| destination.ownership == Ownership::Managed)
633 .unwrap()
634 .clone();
635 crate::adapters::fs::write_file(&target.join(&managed.path), b"edited since").unwrap();
636 let dropped = ".spec-driven-docs/markdownlint/retired.jsonc";
637 crate::adapters::fs::write_file(&target.join(dropped), b"edited since").unwrap();
638 let recorded = Recorded {
639 managed: vec![
640 (managed.path.to_string(), Sha256::of(b"older")),
641 (dropped.to_string(), Sha256::of(b"old")),
642 ],
643 integration: Vec::new(),
644 replace: vec![managed.path.to_string(), dropped.to_string()],
645 };
646 assert!(!vouches(
647 &recorded,
648 &managed.path,
649 Ownership::Managed,
650 b"edited since"
651 ));
652
653 let outcome = land(&target, &candidate, &recorded).unwrap();
654 assert_eq!(
655 std::fs::read(target.join(&managed.path)).unwrap(),
656 managed.bytes
657 );
658 assert_eq!(outcome.removed, vec![dropped.to_string()]);
659 }
660
661 #[test]
662 fn a_destination_reached_through_a_link_refuses() {
663 let dir = tempfile::tempdir().unwrap();
664 let target = target(&dir);
665 let outside = target.join("outside");
666 std::fs::create_dir_all(&outside).unwrap();
667 std::os::unix::fs::symlink(outside.as_std_path(), target.join("docs").as_std_path())
668 .unwrap();
669
670 let error = land(&target, &candidate(), &Recorded::default()).unwrap_err();
671 assert!(error.to_string().contains("symlink"), "{error}");
672 assert!(!target.join(MANIFEST_PATH).exists());
673 }
674
675 #[test]
676 fn a_destination_that_climbs_out_refuses() {
677 let dir = tempfile::tempdir().unwrap();
678 let target = target(&dir);
679 let mut candidate = candidate();
680 candidate.destinations.push(Destination {
681 path: Utf8PathBuf::from("../escaped.md"),
682 bytes: b"x".to_vec(),
683 ownership: Ownership::Managed,
684 placement: Placement::WholeFile,
685 source: None,
686 });
687
688 let error = land(&target, &candidate, &Recorded::default()).unwrap_err();
689 assert!(error.to_string().contains("climbs out"), "{error}");
690 }
691}