1use camino::{Utf8Path, Utf8PathBuf};
14use serde::{Deserialize, Serialize};
15
16use crate::domain::manifest::MANIFEST_PATH;
17use crate::domain::profile::ProfileId;
18use crate::error::AppError;
19
20pub mod compare;
21
22pub const STAGE_SCHEMA: &str = "sdd.stage/1";
24
25pub const STAGE_ROOT_VAR: &str = "SDD_STAGE_ROOT";
27
28pub const RECEIPT_FILE: &str = "stage.json";
30
31pub const ARTIFACTS_DIR: &str = "artifacts";
33
34pub const REFERENCE_DIR: &str = "reference";
36
37const REFERENCE_ROOTS: [&str; 6] = [
44 "method",
45 "templates",
46 "instance",
47 "comparison-docs",
48 "reference/prior-art",
49 "reference/tracker-markup",
50];
51
52#[derive(Debug, Clone)]
58pub struct Request {
59 pub target: Utf8PathBuf,
61 pub profile: Option<ProfileId>,
64 pub output: Option<Utf8PathBuf>,
66 pub docs_scratch: Option<Option<Utf8PathBuf>>,
68 pub reserve: Vec<String>,
70 pub writing_style: Option<crate::domain::instance_config::WritingStyle>,
72 pub acquisition: Option<crate::domain::instance_config::Acquisition>,
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
78#[serde(rename_all = "kebab-case")]
79pub enum RootSource {
80 Flag,
82 Environment,
84 Default,
86}
87
88#[derive(Debug, Clone, Serialize)]
90pub struct Artifact {
91 pub path: String,
93 pub ownership: String,
95 pub placement: String,
97}
98
99#[derive(Debug, Clone, Serialize)]
101pub struct Receipt {
102 pub schema: &'static str,
104 pub version: String,
106 pub target: Utf8PathBuf,
108 pub profile: ProfileId,
110 pub root: Utf8PathBuf,
112 pub root_source: RootSource,
114 pub recorded_version: Option<String>,
116 pub docs_root: String,
118 pub docs_scratch: Option<Utf8PathBuf>,
120 pub reserve: Vec<String>,
122 pub writing_style: String,
124 pub acquisition: Option<crate::domain::instance_config::Acquisition>,
126 pub artifacts: Vec<Artifact>,
128 pub retired: Vec<String>,
131 pub dropped: Vec<String>,
134 pub reference: Vec<String>,
136 pub notes: Vec<String>,
138}
139
140pub fn resolve_root(
150 target: &Utf8Path,
151 output: Option<&Utf8Path>,
152 env: Option<&str>,
153 state_root: &Utf8Path,
154) -> Result<(Utf8PathBuf, RootSource), AppError> {
155 let (root, source) = match (output, env) {
156 (Some(named), _) => (named.to_owned(), RootSource::Flag),
157 (None, Some(base)) if !base.is_empty() => (
158 Utf8Path::new(base).join(stage_name(target)),
159 RootSource::Environment,
160 ),
161 _ => (
162 state_root.join("stages").join(stage_name(target)),
163 RootSource::Default,
164 ),
165 };
166 if !root.is_absolute() {
167 return Err(AppError::Usage(format!(
168 "the stage root must be absolute: {root}"
169 )));
170 }
171 if root
175 .components()
176 .any(|part| part.as_str() == ".." || part.as_str() == ".")
177 {
178 return Err(AppError::Usage(format!(
179 "the stage root names a relative step: {root}; give the path it resolves to"
180 )));
181 }
182 Ok((root, source))
183}
184
185fn resolved_ancestor(path: &Utf8Path) -> Utf8PathBuf {
190 let mut walked = path.to_owned();
191 loop {
192 if let Ok(canonical) = std::fs::canonicalize(walked.as_std_path())
193 && let Ok(canonical) = Utf8PathBuf::from_path_buf(canonical)
194 {
195 let rest = path
196 .strip_prefix(&walked)
197 .unwrap_or_else(|_| Utf8Path::new(""));
198 return canonical.join(rest);
199 }
200 let Some(parent) = walked.parent() else {
201 return path.to_owned();
202 };
203 walked = parent.to_owned();
204 }
205}
206
207fn writing_style_of(declaration: &crate::domain::instance_config::InstanceConfig) -> String {
209 use crate::domain::instance_config::WritingSource;
210
211 match declaration.writing_style.source {
212 WritingSource::Builtin => "builtin".to_string(),
213 WritingSource::None => "none".to_string(),
214 WritingSource::Project => declaration
215 .writing_style
216 .path
217 .as_ref()
218 .map_or_else(|| "project".to_string(), |path| format!("project:{path}")),
219 }
220}
221
222fn scratch_beside(root: &Utf8Path) -> Result<Utf8PathBuf, AppError> {
228 let stamp = jiff::Timestamp::now().as_nanosecond();
229 let partial = Utf8PathBuf::from(format!("{root}.partial-{}-{stamp}", std::process::id()));
230 if let Some(parent) = partial.parent() {
231 std::fs::create_dir_all(parent)?;
232 }
233 std::fs::create_dir(&partial).map_err(|source| {
234 AppError::Refused(format!(
235 "{partial} could not be created for this run: {source}"
236 ))
237 })?;
238 Ok(partial)
239}
240
241pub(crate) fn stage_name(target: &Utf8Path) -> String {
246 let digest = crate::domain::ownership::Sha256::of(target.as_str().as_bytes()).to_string();
247 let leaf = target.file_name().unwrap_or("target");
248 format!("{leaf}-{}", &digest[..12])
249}
250
251pub fn create(request: &Request, state_root: &Utf8Path) -> Result<Receipt, AppError> {
259 let target = crate::services::installer::resolved_target(&request.target)?;
260 let env = std::env::var(STAGE_ROOT_VAR).ok();
261 let (root, root_source) = resolve_root(
262 &target,
263 request.output.as_deref(),
264 env.as_deref(),
265 state_root,
266 )?;
267
268 let resolved = resolved_ancestor(&root);
274 if resolved == target || resolved.starts_with(&target) {
275 return Err(AppError::Refused(format!(
276 "{root} is inside {target}, and a stage is written outside the target it describes"
277 )));
278 }
279 if root.exists() && root.read_dir_utf8().is_ok_and(|mut it| it.next().is_some()) {
280 return Err(AppError::Refused(format!(
281 "{root} already holds a stage; read it, or remove it with 'sdd stage clean {root}'"
282 )));
283 }
284
285 let profile = staged_profile(&target, request.profile)?;
286 let options = crate::services::installer::InitOptions {
287 target: target.clone(),
288 profile,
289 apply: false,
290 dry_run: true,
291 docs_scratch: request.docs_scratch.clone(),
292 reserve: request.reserve.clone(),
293 writing_style: request.writing_style.clone(),
294 acquisition: request.acquisition.clone(),
295 replace: Vec::new(),
296 };
297 let candidate = crate::services::installer::candidate_for(&target, &options)?;
298
299 let partial = scratch_beside(&root)?;
304 let render = render(&partial, &target, &root, root_source, &candidate, profile);
305 match render {
306 Ok(receipt) => finish(&partial, &root, receipt),
307 Err(error) => {
308 let _ = std::fs::remove_dir_all(&partial);
312 Err(error)
313 }
314 }
315}
316
317fn finish(partial: &Utf8Path, root: &Utf8Path, receipt: Receipt) -> Result<Receipt, AppError> {
319 if let Some(parent) = root.parent() {
320 std::fs::create_dir_all(parent)?;
321 }
322 let _ = std::fs::remove_dir(root);
325 if let Err(source) = std::fs::rename(partial, root) {
326 let _ = std::fs::remove_dir_all(partial);
327 return Err(AppError::Io(source));
328 }
329 Ok(receipt)
330}
331
332fn served_reference(partial: &Utf8Path, reference: &mut Vec<String>) -> Result<(), AppError> {
336 for (name, file) in crate::embedded::spec_files() {
337 crate::adapters::fs::write_file(
338 &partial.join(REFERENCE_DIR).join("_docs/specs").join(name),
339 file.contents(),
340 )?;
341 }
342 reference.push(format!("{REFERENCE_DIR}/_docs/specs"));
343 let lint = "_docs/.markdownlint-cli2.jsonc";
344 if let Some(bytes) = crate::embedded::asset(&format!("{}/{lint}", crate::embedded::PAYLOAD_DIR))
345 {
346 crate::adapters::fs::write_file(&partial.join(REFERENCE_DIR).join(lint), bytes)?;
347 reference.push(format!("{REFERENCE_DIR}/{lint}"));
348 }
349 Ok(())
350}
351
352fn render(
354 partial: &Utf8Path,
355 target: &Utf8Path,
356 root: &Utf8Path,
357 root_source: RootSource,
358 candidate: &crate::candidate::Candidate,
359 profile: ProfileId,
360) -> Result<Receipt, AppError> {
361 let mut artifacts = Vec::new();
362 for destination in &candidate.destinations {
363 let path = partial.join(ARTIFACTS_DIR).join(&destination.path);
364 crate::adapters::fs::write_file(&path, &destination.bytes)?;
365 artifacts.push(Artifact {
366 path: destination.path.to_string(),
367 ownership: match destination.ownership {
368 crate::candidate::Ownership::Managed => "managed",
369 crate::candidate::Ownership::Adopted => "adopted",
370 crate::candidate::Ownership::Integration => "integration",
371 }
372 .to_string(),
373 placement: match destination.placement {
374 crate::candidate::Placement::WholeFile => "whole-file",
375 crate::candidate::Placement::MarkedRegion => "marked-region",
376 }
377 .to_string(),
378 });
379 }
380 crate::adapters::fs::write_file(
381 &partial.join(ARTIFACTS_DIR).join(MANIFEST_PATH),
382 candidate.manifest.to_json().as_bytes(),
383 )?;
384 artifacts.push(Artifact {
385 path: MANIFEST_PATH.to_string(),
386 ownership: "record".to_string(),
387 placement: "whole-file".to_string(),
388 });
389
390 let mut reference = Vec::new();
391
392 for name in crate::embedded::skill_names() {
396 let package = crate::embedded::skill_package(name).map_err(anyhow::Error::from)?;
397 for (relative, bytes) in package {
398 crate::adapters::fs::write_file(
399 &partial
400 .join(REFERENCE_DIR)
401 .join("skills")
402 .join(name)
403 .join(&relative),
404 bytes,
405 )?;
406 }
407 }
408 reference.push(format!("{REFERENCE_DIR}/skills"));
409
410 crate::adapters::fs::write_file(
413 &partial.join(REFERENCE_DIR).join("CHANGELOG.md"),
414 crate::embedded::CHANGELOG.as_bytes(),
415 )?;
416 reference.push(format!("{REFERENCE_DIR}/CHANGELOG.md"));
417
418 for root_name in REFERENCE_ROOTS {
419 let mut carried = false;
420 for (path, bytes) in crate::embedded::assets_under(root_name) {
421 crate::adapters::fs::write_file(&partial.join(REFERENCE_DIR).join(&path), bytes)?;
422 carried = true;
423 }
424 if carried {
425 reference.push(format!("{REFERENCE_DIR}/{root_name}"));
426 }
427 }
428 served_reference(partial, &mut reference)?;
429 if let Some(bytes) = crate::embedded::asset("instance/docs-catalog.toml") {
430 crate::adapters::fs::write_file(
431 &partial
432 .join(REFERENCE_DIR)
433 .join("instance/docs-catalog.toml"),
434 bytes,
435 )?;
436 reference.push(format!("{REFERENCE_DIR}/instance/docs-catalog.toml"));
437 }
438
439 let (retired, dropped) = crate::landing::apply::departures(
442 target,
443 candidate,
444 &crate::services::installer::recorded(target),
445 )
446 .into_paths();
447 let receipt = Receipt {
448 schema: STAGE_SCHEMA,
449 version: crate::domain::version::CanonVersion::current().to_string(),
450 target: target.to_owned(),
451 profile,
452 root: root.to_owned(),
453 root_source,
454 recorded_version: crate::services::installer::recorded_field(target, "canon_version")
455 .and_then(|value| value.as_str().map(String::from)),
456 docs_root: candidate.manifest.docs_root.to_string(),
457 docs_scratch: candidate.manifest.docs_scratch.clone(),
458 reserve: candidate.declaration.reserved.clone(),
459 writing_style: writing_style_of(&candidate.declaration),
460 acquisition: candidate.declaration.acquisition.clone(),
461 artifacts,
462 retired,
463 dropped,
464 reference,
465 notes: candidate.notes.clone(),
466 };
467 let json = serde_json::to_string_pretty(&receipt)
468 .map_err(|error| anyhow::anyhow!("the stage receipt does not serialize: {error}"))?;
469 crate::adapters::fs::write_file(&partial.join(RECEIPT_FILE), json.as_bytes())?;
470
471 Ok(receipt)
472}
473
474fn staged_profile(target: &Utf8Path, flag: Option<ProfileId>) -> Result<ProfileId, AppError> {
488 let recorded =
489 crate::services::installer::recorded_field(target, "profile").and_then(|value| {
490 ProfileId::every().find(|profile| Some(profile.as_str()) == value.as_str())
491 });
492 match (recorded, flag) {
493 (Some(recorded), Some(asked)) if recorded != asked => Err(AppError::Refused(format!(
494 "{target} records the {recorded} profile and this stage asks for {asked}; \
495 moving a profile moves the documentation root, which is a migration to ask for deliberately"
496 ))),
497 (Some(recorded), _) => Ok(recorded),
498 (None, Some(asked)) => Ok(asked),
499 (None, None) => Ok(ProfileId::Codebase),
500 }
501}
502
503#[derive(Debug, Clone)]
505pub struct StagedChoices {
506 pub target: Utf8PathBuf,
508 pub profile: ProfileId,
510 pub docs_scratch: Option<Utf8PathBuf>,
512 pub reserve: Vec<String>,
514 pub writing_style: crate::domain::instance_config::WritingStyle,
516 pub acquisition: Option<crate::domain::instance_config::Acquisition>,
518 pub artifacts: Vec<HeldArtifact>,
520}
521
522#[derive(Debug, Clone, Deserialize)]
524pub struct HeldArtifact {
525 pub path: String,
527 pub ownership: String,
529}
530
531#[derive(Debug, Deserialize)]
533struct HeldReceipt {
534 schema: String,
535 version: String,
536 target: Utf8PathBuf,
537 profile: ProfileId,
538 root: Utf8PathBuf,
539 docs_scratch: Option<Utf8PathBuf>,
540 #[serde(default)]
541 reserve: Vec<String>,
542 writing_style: String,
543 #[serde(default)]
544 acquisition: Option<crate::domain::instance_config::Acquisition>,
545 #[serde(default)]
546 artifacts: Vec<HeldArtifact>,
547}
548
549pub fn read_choices(root: &Utf8Path, target: &Utf8Path) -> Result<StagedChoices, AppError> {
565 if !root.is_absolute() {
566 return Err(AppError::Usage(format!(
567 "the stage path must be absolute: {root}"
568 )));
569 }
570 let path = root.join(RECEIPT_FILE);
571 let text = std::fs::read_to_string(&path).map_err(|source| {
572 AppError::Refused(format!(
573 "{path} is not readable, so {root} is not a stage this tool wrote: {source}"
574 ))
575 })?;
576 let held: HeldReceipt = serde_json::from_str(&text).map_err(|source| {
577 AppError::Refused(format!(
578 "{path} is not a receipt this release reads: {source}"
579 ))
580 })?;
581 if held.schema != STAGE_SCHEMA {
582 return Err(AppError::Refused(format!(
583 "{path} does not declare {STAGE_SCHEMA}, so this is not a stage"
584 )));
585 }
586 if held.root != root {
587 return Err(AppError::Refused(format!(
588 "{path} declares the root {}, and this path is {root}",
589 held.root
590 )));
591 }
592 let current = crate::domain::version::CanonVersion::current().to_string();
593 if held.version != current {
594 return Err(AppError::Refused(format!(
595 "the stage at {root} was rendered by sdd {}, and this is sdd {current}; stage again with this binary",
596 held.version
597 )));
598 }
599 let target = crate::services::installer::resolved_target(target)?;
600 if held.target != target {
601 return Err(AppError::Refused(format!(
602 "the stage at {root} was rendered for {}, and this landing targets {target}",
603 held.target
604 )));
605 }
606 let writing_style = crate::domain::instance_config::WritingStyle::parse_flag(
607 &held.writing_style,
608 )
609 .map_err(|error| {
610 AppError::Refused(format!(
611 "{path} records a writing style this release refuses: {error}"
612 ))
613 })?;
614 Ok(StagedChoices {
615 target,
616 profile: held.profile,
617 docs_scratch: held.docs_scratch,
618 reserve: held.reserve,
619 writing_style,
620 acquisition: held.acquisition,
621 artifacts: held.artifacts,
622 })
623}
624
625pub fn clean(path: &Utf8Path) -> Result<Vec<String>, AppError> {
633 if !path.is_absolute() {
634 return Err(AppError::Usage(format!(
635 "the stage path must be absolute: {path}"
636 )));
637 }
638 let held = std::fs::symlink_metadata(path)
641 .map_err(|source| AppError::Refused(format!("{path}: {source}")))?;
642 if held.file_type().is_symlink() {
643 return Err(AppError::Refused(format!(
644 "{path} is a symlink; a stage is a directory this tool wrote"
645 )));
646 }
647 if !held.is_dir() {
648 return Err(AppError::Refused(format!("{path} is not a directory")));
649 }
650 if path.parent().is_none() || path.as_str().matches('/').count() < 2 {
651 return Err(AppError::Refused(format!(
652 "{path} is too close to the filesystem root to remove"
653 )));
654 }
655 if path.join(MANIFEST_PATH).exists() || path.join(".git").exists() {
656 return Err(AppError::Refused(format!(
657 "{path} looks like a project rather than a stage"
658 )));
659 }
660 if let Some(home) = crate::domain::paths::UserEnv::from_process().home
664 && path == home
665 {
666 return Err(AppError::Refused(format!(
667 "{path} is the home directory, which is never a stage"
668 )));
669 }
670 if let Ok(cwd) = std::env::current_dir()
671 && let Ok(cwd) = Utf8PathBuf::from_path_buf(cwd)
672 && cwd.starts_with(path)
673 {
674 return Err(AppError::Refused(format!(
675 "{path} holds the working directory, so it is not a stage this tool wrote"
676 )));
677 }
678 if !path.join(ARTIFACTS_DIR).is_dir() {
682 return Err(AppError::Refused(format!(
683 "{path} carries no {ARTIFACTS_DIR}/ directory, so it is not a stage this tool wrote"
684 )));
685 }
686
687 let receipt_path = path.join(RECEIPT_FILE);
688 let text = std::fs::read_to_string(&receipt_path).map_err(|source| {
689 AppError::Refused(format!(
690 "{receipt_path} is not readable, so this is not a stage this tool wrote: {source}"
691 ))
692 })?;
693 let receipt: serde_json::Value = serde_json::from_str(&text)
694 .map_err(|source| AppError::Refused(format!("{receipt_path} does not parse: {source}")))?;
695 if receipt.get("schema").and_then(serde_json::Value::as_str) != Some(STAGE_SCHEMA) {
696 return Err(AppError::Refused(format!(
697 "{receipt_path} does not declare {STAGE_SCHEMA}, so this is not a stage"
698 )));
699 }
700 let declared = receipt
701 .get("root")
702 .and_then(serde_json::Value::as_str)
703 .ok_or_else(|| AppError::Refused(format!("{receipt_path} declares no root")))?;
704 if declared != path.as_str() {
705 return Err(AppError::Refused(format!(
706 "{receipt_path} declares the root {declared}, and this path is {path}"
707 )));
708 }
709
710 let aside = scratch_beside(path)?;
714 let _ = std::fs::remove_dir(&aside);
715 std::fs::rename(path, &aside)?;
716 if let Err(source) = std::fs::remove_dir_all(&aside) {
717 if std::fs::rename(&aside, path).is_err() {
721 return Err(AppError::Refused(format!(
722 "{path} could not be removed and is now at {aside}: {source}"
723 )));
724 }
725 return Err(AppError::Io(source));
726 }
727 Ok(vec![format!("removed {path}")])
728}
729
730#[cfg(test)]
731mod tests {
732 #![allow(
733 clippy::unwrap_used,
734 reason = "a test panics as its failure signal, not as control flow"
735 )]
736
737 use super::*;
738
739 fn root(dir: &tempfile::TempDir) -> Utf8PathBuf {
740 Utf8PathBuf::from(dir.path().to_str().unwrap())
741 }
742
743 #[test]
744 fn the_flag_wins_then_the_base_then_the_state_root() {
745 let target = Utf8Path::new("/work/project");
746 let state = Utf8Path::new("/state/spec-driven-docs");
747
748 let (path, source) = resolve_root(
749 target,
750 Some(Utf8Path::new("/tmp/here")),
751 Some("/base"),
752 state,
753 )
754 .unwrap();
755 assert_eq!(path, "/tmp/here");
756 assert_eq!(source, RootSource::Flag);
757
758 let (path, source) = resolve_root(target, None, Some("/base"), state).unwrap();
759 assert!(path.as_str().starts_with("/base/project-"), "{path}");
760 assert_eq!(source, RootSource::Environment);
761
762 let (path, source) = resolve_root(target, None, None, state).unwrap();
763 assert!(
764 path.as_str().starts_with(state.join("stages").as_str()),
765 "{path}"
766 );
767 assert_eq!(source, RootSource::Default);
768 }
769
770 #[test]
771 fn a_relative_stage_root_is_a_usage_error() {
772 let error = resolve_root(
773 Utf8Path::new("/work/project"),
774 Some(Utf8Path::new("stage")),
775 None,
776 Utf8Path::new("/state"),
777 )
778 .unwrap_err();
779 assert_eq!(error.kind(), "Usage");
780 }
781
782 #[test]
783 fn a_relative_step_in_the_stage_root_is_a_usage_error() {
784 for (output, env) in [
787 (Some(Utf8Path::new("/work/project/absent/../inside")), None),
788 (None, Some("/tmp/absent/../../work")),
789 ] {
790 let error = resolve_root(
791 Utf8Path::new("/work/project"),
792 output,
793 env,
794 Utf8Path::new("/state"),
795 )
796 .unwrap_err();
797 assert_eq!(error.kind(), "Usage");
798 assert!(error.to_string().contains("relative step"), "{error}");
799 }
800 }
801
802 #[test]
803 fn two_targets_stage_under_different_names() {
804 assert_ne!(
805 stage_name(Utf8Path::new("/one/project")),
806 stage_name(Utf8Path::new("/two/project"))
807 );
808 }
809
810 #[test]
811 fn clean_refuses_a_directory_that_is_not_a_stage() {
812 let dir = tempfile::tempdir().unwrap();
813 let path = root(&dir).join("not-a-stage");
814 std::fs::create_dir_all(&path).unwrap();
815 let error = clean(&path).unwrap_err();
816 assert_eq!(error.kind(), "Refused");
817 assert!(path.exists(), "the directory was removed anyway");
818 }
819
820 #[test]
821 fn clean_refuses_a_receipt_that_names_another_root() {
822 let dir = tempfile::tempdir().unwrap();
823 let path = root(&dir).join("stage");
824 std::fs::create_dir_all(path.join(ARTIFACTS_DIR)).unwrap();
825 crate::adapters::fs::write_file(
826 &path.join(RECEIPT_FILE),
827 format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"/elsewhere"}}"#).as_bytes(),
828 )
829 .unwrap();
830 let error = clean(&path).unwrap_err();
831 assert!(error.to_string().contains("/elsewhere"), "{error}");
832 assert!(path.exists());
833 }
834
835 #[test]
836 fn clean_refuses_a_link_standing_where_a_stage_stood() {
837 let dir = tempfile::tempdir().unwrap();
838 let real = root(&dir).join("stage");
839 std::fs::create_dir_all(real.join(ARTIFACTS_DIR)).unwrap();
840 crate::adapters::fs::write_file(
841 &real.join(RECEIPT_FILE),
842 format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"{real}"}}"#).as_bytes(),
843 )
844 .unwrap();
845 let link = root(&dir).join("link");
846 std::os::unix::fs::symlink(real.as_std_path(), link.as_std_path()).unwrap();
847
848 let error = clean(&link).unwrap_err();
849 assert!(error.to_string().contains("symlink"), "{error}");
850 assert!(real.exists(), "the link's target was removed");
851 }
852
853 #[test]
854 fn clean_refuses_a_project_root() {
855 let dir = tempfile::tempdir().unwrap();
856 let path = root(&dir).join("project");
857 crate::adapters::fs::write_file(&path.join(MANIFEST_PATH), b"{}").unwrap();
858 crate::adapters::fs::write_file(
859 &path.join(RECEIPT_FILE),
860 format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"{path}"}}"#).as_bytes(),
861 )
862 .unwrap();
863 let error = clean(&path).unwrap_err();
864 assert!(error.to_string().contains("project"), "{error}");
865 assert!(path.exists());
866 }
867
868 #[test]
869 fn clean_refuses_a_forged_receipt_over_a_directory_that_is_not_a_stage() {
870 let dir = tempfile::tempdir().unwrap();
871 let path = root(&dir).join("someones-files");
874 crate::adapters::fs::write_file(&path.join("notes.md"), b"mine").unwrap();
875 crate::adapters::fs::write_file(
876 &path.join(RECEIPT_FILE),
877 format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"{path}"}}"#).as_bytes(),
878 )
879 .unwrap();
880
881 let error = clean(&path).unwrap_err();
882 assert!(error.to_string().contains(ARTIFACTS_DIR), "{error}");
883 assert!(path.join("notes.md").exists(), "the directory was removed");
884 }
885
886 #[test]
887 fn clean_refuses_a_directory_holding_the_working_directory() {
888 let dir = tempfile::tempdir().unwrap();
889 let path = Utf8PathBuf::from_path_buf(std::env::current_dir().unwrap())
890 .unwrap()
891 .parent()
892 .unwrap()
893 .to_owned();
894 let _ = dir;
895 let error = clean(&path).unwrap_err();
896 assert_eq!(error.kind(), "Refused");
897 assert!(path.exists());
898 }
899
900 #[test]
901 fn clean_removes_one_valid_stage() {
902 let dir = tempfile::tempdir().unwrap();
903 let path = root(&dir).join("stage");
904 crate::adapters::fs::write_file(&path.join(ARTIFACTS_DIR).join("AGENTS.md"), b"x").unwrap();
905 crate::adapters::fs::write_file(
906 &path.join(RECEIPT_FILE),
907 format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"{path}"}}"#).as_bytes(),
908 )
909 .unwrap();
910 assert_eq!(clean(&path).unwrap().len(), 1);
911 assert!(!path.exists());
912 }
913}