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 reference: Vec<String>,
130 pub notes: Vec<String>,
132}
133
134pub fn resolve_root(
144 target: &Utf8Path,
145 output: Option<&Utf8Path>,
146 env: Option<&str>,
147 state_root: &Utf8Path,
148) -> Result<(Utf8PathBuf, RootSource), AppError> {
149 let (root, source) = match (output, env) {
150 (Some(named), _) => (named.to_owned(), RootSource::Flag),
151 (None, Some(base)) if !base.is_empty() => (
152 Utf8Path::new(base).join(stage_name(target)),
153 RootSource::Environment,
154 ),
155 _ => (
156 state_root.join("stages").join(stage_name(target)),
157 RootSource::Default,
158 ),
159 };
160 if !root.is_absolute() {
161 return Err(AppError::Usage(format!(
162 "the stage root must be absolute: {root}"
163 )));
164 }
165 if root
169 .components()
170 .any(|part| part.as_str() == ".." || part.as_str() == ".")
171 {
172 return Err(AppError::Usage(format!(
173 "the stage root names a relative step: {root}; give the path it resolves to"
174 )));
175 }
176 Ok((root, source))
177}
178
179fn resolved_ancestor(path: &Utf8Path) -> Utf8PathBuf {
184 let mut walked = path.to_owned();
185 loop {
186 if let Ok(canonical) = std::fs::canonicalize(walked.as_std_path())
187 && let Ok(canonical) = Utf8PathBuf::from_path_buf(canonical)
188 {
189 let rest = path
190 .strip_prefix(&walked)
191 .unwrap_or_else(|_| Utf8Path::new(""));
192 return canonical.join(rest);
193 }
194 let Some(parent) = walked.parent() else {
195 return path.to_owned();
196 };
197 walked = parent.to_owned();
198 }
199}
200
201fn writing_style_of(declaration: &crate::domain::instance_config::InstanceConfig) -> String {
203 use crate::domain::instance_config::WritingSource;
204
205 match declaration.writing_style.source {
206 WritingSource::Builtin => "builtin".to_string(),
207 WritingSource::None => "none".to_string(),
208 WritingSource::Project => declaration
209 .writing_style
210 .path
211 .as_ref()
212 .map_or_else(|| "project".to_string(), |path| format!("project:{path}")),
213 }
214}
215
216fn scratch_beside(root: &Utf8Path) -> Result<Utf8PathBuf, AppError> {
222 let stamp = jiff::Timestamp::now().as_nanosecond();
223 let partial = Utf8PathBuf::from(format!("{root}.partial-{}-{stamp}", std::process::id()));
224 if let Some(parent) = partial.parent() {
225 std::fs::create_dir_all(parent)?;
226 }
227 std::fs::create_dir(&partial).map_err(|source| {
228 AppError::Refused(format!(
229 "{partial} could not be created for this run: {source}"
230 ))
231 })?;
232 Ok(partial)
233}
234
235pub(crate) fn stage_name(target: &Utf8Path) -> String {
240 let digest = crate::domain::ownership::Sha256::of(target.as_str().as_bytes()).to_string();
241 let leaf = target.file_name().unwrap_or("target");
242 format!("{leaf}-{}", &digest[..12])
243}
244
245pub fn create(request: &Request, state_root: &Utf8Path) -> Result<Receipt, AppError> {
253 let target = crate::services::installer::resolved_target(&request.target)?;
254 let env = std::env::var(STAGE_ROOT_VAR).ok();
255 let (root, root_source) = resolve_root(
256 &target,
257 request.output.as_deref(),
258 env.as_deref(),
259 state_root,
260 )?;
261
262 let resolved = resolved_ancestor(&root);
268 if resolved == target || resolved.starts_with(&target) {
269 return Err(AppError::Refused(format!(
270 "{root} is inside {target}, and a stage is written outside the target it describes"
271 )));
272 }
273 if root.exists() && root.read_dir_utf8().is_ok_and(|mut it| it.next().is_some()) {
274 return Err(AppError::Refused(format!(
275 "{root} already holds a stage; read it, or remove it with 'sdd stage clean {root}'"
276 )));
277 }
278
279 let profile = staged_profile(&target, request.profile)?;
280 let options = crate::services::installer::InitOptions {
281 target: target.clone(),
282 profile,
283 apply: false,
284 dry_run: true,
285 docs_scratch: request.docs_scratch.clone(),
286 reserve: request.reserve.clone(),
287 writing_style: request.writing_style.clone(),
288 acquisition: request.acquisition.clone(),
289 replace: Vec::new(),
290 };
291 let candidate = crate::services::installer::candidate_for(&target, &options)?;
292
293 let partial = scratch_beside(&root)?;
298 let render = render(&partial, &target, &root, root_source, &candidate, profile);
299 match render {
300 Ok(receipt) => finish(&partial, &root, receipt),
301 Err(error) => {
302 let _ = std::fs::remove_dir_all(&partial);
306 Err(error)
307 }
308 }
309}
310
311fn finish(partial: &Utf8Path, root: &Utf8Path, receipt: Receipt) -> Result<Receipt, AppError> {
313 if let Some(parent) = root.parent() {
314 std::fs::create_dir_all(parent)?;
315 }
316 let _ = std::fs::remove_dir(root);
319 if let Err(source) = std::fs::rename(partial, root) {
320 let _ = std::fs::remove_dir_all(partial);
321 return Err(AppError::Io(source));
322 }
323 Ok(receipt)
324}
325
326fn served_reference(partial: &Utf8Path, reference: &mut Vec<String>) -> Result<(), AppError> {
330 for (name, file) in crate::embedded::spec_files() {
331 crate::adapters::fs::write_file(
332 &partial.join(REFERENCE_DIR).join("_docs/specs").join(name),
333 file.contents(),
334 )?;
335 }
336 reference.push(format!("{REFERENCE_DIR}/_docs/specs"));
337 let lint = "_docs/.markdownlint-cli2.jsonc";
338 if let Some(bytes) = crate::embedded::asset(&format!("{}/{lint}", crate::embedded::PAYLOAD_DIR))
339 {
340 crate::adapters::fs::write_file(&partial.join(REFERENCE_DIR).join(lint), bytes)?;
341 reference.push(format!("{REFERENCE_DIR}/{lint}"));
342 }
343 Ok(())
344}
345
346fn render(
348 partial: &Utf8Path,
349 target: &Utf8Path,
350 root: &Utf8Path,
351 root_source: RootSource,
352 candidate: &crate::candidate::Candidate,
353 profile: ProfileId,
354) -> Result<Receipt, AppError> {
355 let mut artifacts = Vec::new();
356 for destination in &candidate.destinations {
357 let path = partial.join(ARTIFACTS_DIR).join(&destination.path);
358 crate::adapters::fs::write_file(&path, &destination.bytes)?;
359 artifacts.push(Artifact {
360 path: destination.path.to_string(),
361 ownership: match destination.ownership {
362 crate::candidate::Ownership::Managed => "managed",
363 crate::candidate::Ownership::Adopted => "adopted",
364 crate::candidate::Ownership::Integration => "integration",
365 }
366 .to_string(),
367 placement: match destination.placement {
368 crate::candidate::Placement::WholeFile => "whole-file",
369 crate::candidate::Placement::MarkedRegion => "marked-region",
370 }
371 .to_string(),
372 });
373 }
374 crate::adapters::fs::write_file(
375 &partial.join(ARTIFACTS_DIR).join(MANIFEST_PATH),
376 candidate.manifest.to_json().as_bytes(),
377 )?;
378 artifacts.push(Artifact {
379 path: MANIFEST_PATH.to_string(),
380 ownership: "record".to_string(),
381 placement: "whole-file".to_string(),
382 });
383
384 let mut reference = Vec::new();
385
386 for name in crate::embedded::skill_names() {
390 let package = crate::embedded::skill_package(name).map_err(anyhow::Error::from)?;
391 for (relative, bytes) in package {
392 crate::adapters::fs::write_file(
393 &partial
394 .join(REFERENCE_DIR)
395 .join("skills")
396 .join(name)
397 .join(&relative),
398 bytes,
399 )?;
400 }
401 }
402 reference.push(format!("{REFERENCE_DIR}/skills"));
403
404 crate::adapters::fs::write_file(
407 &partial.join(REFERENCE_DIR).join("CHANGELOG.md"),
408 crate::embedded::CHANGELOG.as_bytes(),
409 )?;
410 reference.push(format!("{REFERENCE_DIR}/CHANGELOG.md"));
411
412 for root_name in REFERENCE_ROOTS {
413 let mut carried = false;
414 for (path, bytes) in crate::embedded::assets_under(root_name) {
415 crate::adapters::fs::write_file(&partial.join(REFERENCE_DIR).join(&path), bytes)?;
416 carried = true;
417 }
418 if carried {
419 reference.push(format!("{REFERENCE_DIR}/{root_name}"));
420 }
421 }
422 served_reference(partial, &mut reference)?;
423 if let Some(bytes) = crate::embedded::asset("instance/docs-catalog.toml") {
424 crate::adapters::fs::write_file(
425 &partial
426 .join(REFERENCE_DIR)
427 .join("instance/docs-catalog.toml"),
428 bytes,
429 )?;
430 reference.push(format!("{REFERENCE_DIR}/instance/docs-catalog.toml"));
431 }
432
433 let receipt = Receipt {
434 schema: STAGE_SCHEMA,
435 version: crate::domain::version::CanonVersion::current().to_string(),
436 target: target.to_owned(),
437 profile,
438 root: root.to_owned(),
439 root_source,
440 recorded_version: crate::services::installer::recorded_field(target, "canon_version")
441 .and_then(|value| value.as_str().map(String::from)),
442 docs_root: candidate.manifest.docs_root.to_string(),
443 docs_scratch: candidate.manifest.docs_scratch.clone(),
444 reserve: candidate.declaration.reserved.clone(),
445 writing_style: writing_style_of(&candidate.declaration),
446 acquisition: candidate.declaration.acquisition.clone(),
447 artifacts,
448 reference,
449 notes: candidate.notes.clone(),
450 };
451 let json = serde_json::to_string_pretty(&receipt)
452 .map_err(|error| anyhow::anyhow!("the stage receipt does not serialize: {error}"))?;
453 crate::adapters::fs::write_file(&partial.join(RECEIPT_FILE), json.as_bytes())?;
454
455 Ok(receipt)
456}
457
458fn staged_profile(target: &Utf8Path, flag: Option<ProfileId>) -> Result<ProfileId, AppError> {
472 let recorded =
473 crate::services::installer::recorded_field(target, "profile").and_then(|value| {
474 ProfileId::every().find(|profile| Some(profile.as_str()) == value.as_str())
475 });
476 match (recorded, flag) {
477 (Some(recorded), Some(asked)) if recorded != asked => Err(AppError::Refused(format!(
478 "{target} records the {recorded} profile and this stage asks for {asked}; \
479 moving a profile moves the documentation root, which is a migration to ask for deliberately"
480 ))),
481 (Some(recorded), _) => Ok(recorded),
482 (None, Some(asked)) => Ok(asked),
483 (None, None) => Ok(ProfileId::Codebase),
484 }
485}
486
487#[derive(Debug, Clone)]
489pub struct StagedChoices {
490 pub target: Utf8PathBuf,
492 pub profile: ProfileId,
494 pub docs_scratch: Option<Utf8PathBuf>,
496 pub reserve: Vec<String>,
498 pub writing_style: crate::domain::instance_config::WritingStyle,
500 pub acquisition: Option<crate::domain::instance_config::Acquisition>,
502 pub artifacts: Vec<HeldArtifact>,
504}
505
506#[derive(Debug, Clone, Deserialize)]
508pub struct HeldArtifact {
509 pub path: String,
511 pub ownership: String,
513}
514
515#[derive(Debug, Deserialize)]
517struct HeldReceipt {
518 schema: String,
519 version: String,
520 target: Utf8PathBuf,
521 profile: ProfileId,
522 root: Utf8PathBuf,
523 docs_scratch: Option<Utf8PathBuf>,
524 #[serde(default)]
525 reserve: Vec<String>,
526 writing_style: String,
527 #[serde(default)]
528 acquisition: Option<crate::domain::instance_config::Acquisition>,
529 #[serde(default)]
530 artifacts: Vec<HeldArtifact>,
531}
532
533pub fn read_choices(root: &Utf8Path, target: &Utf8Path) -> Result<StagedChoices, AppError> {
549 if !root.is_absolute() {
550 return Err(AppError::Usage(format!(
551 "the stage path must be absolute: {root}"
552 )));
553 }
554 let path = root.join(RECEIPT_FILE);
555 let text = std::fs::read_to_string(&path).map_err(|source| {
556 AppError::Refused(format!(
557 "{path} is not readable, so {root} is not a stage this tool wrote: {source}"
558 ))
559 })?;
560 let held: HeldReceipt = serde_json::from_str(&text).map_err(|source| {
561 AppError::Refused(format!(
562 "{path} is not a receipt this release reads: {source}"
563 ))
564 })?;
565 if held.schema != STAGE_SCHEMA {
566 return Err(AppError::Refused(format!(
567 "{path} does not declare {STAGE_SCHEMA}, so this is not a stage"
568 )));
569 }
570 if held.root != root {
571 return Err(AppError::Refused(format!(
572 "{path} declares the root {}, and this path is {root}",
573 held.root
574 )));
575 }
576 let current = crate::domain::version::CanonVersion::current().to_string();
577 if held.version != current {
578 return Err(AppError::Refused(format!(
579 "the stage at {root} was rendered by sdd {}, and this is sdd {current}; stage again with this binary",
580 held.version
581 )));
582 }
583 let target = crate::services::installer::resolved_target(target)?;
584 if held.target != target {
585 return Err(AppError::Refused(format!(
586 "the stage at {root} was rendered for {}, and this landing targets {target}",
587 held.target
588 )));
589 }
590 let writing_style = crate::domain::instance_config::WritingStyle::parse_flag(
591 &held.writing_style,
592 )
593 .map_err(|error| {
594 AppError::Refused(format!(
595 "{path} records a writing style this release refuses: {error}"
596 ))
597 })?;
598 Ok(StagedChoices {
599 target,
600 profile: held.profile,
601 docs_scratch: held.docs_scratch,
602 reserve: held.reserve,
603 writing_style,
604 acquisition: held.acquisition,
605 artifacts: held.artifacts,
606 })
607}
608
609pub fn clean(path: &Utf8Path) -> Result<Vec<String>, AppError> {
617 if !path.is_absolute() {
618 return Err(AppError::Usage(format!(
619 "the stage path must be absolute: {path}"
620 )));
621 }
622 let held = std::fs::symlink_metadata(path)
625 .map_err(|source| AppError::Refused(format!("{path}: {source}")))?;
626 if held.file_type().is_symlink() {
627 return Err(AppError::Refused(format!(
628 "{path} is a symlink; a stage is a directory this tool wrote"
629 )));
630 }
631 if !held.is_dir() {
632 return Err(AppError::Refused(format!("{path} is not a directory")));
633 }
634 if path.parent().is_none() || path.as_str().matches('/').count() < 2 {
635 return Err(AppError::Refused(format!(
636 "{path} is too close to the filesystem root to remove"
637 )));
638 }
639 if path.join(MANIFEST_PATH).exists() || path.join(".git").exists() {
640 return Err(AppError::Refused(format!(
641 "{path} looks like a project rather than a stage"
642 )));
643 }
644 if let Some(home) = crate::domain::paths::UserEnv::from_process().home
648 && path == home
649 {
650 return Err(AppError::Refused(format!(
651 "{path} is the home directory, which is never a stage"
652 )));
653 }
654 if let Ok(cwd) = std::env::current_dir()
655 && let Ok(cwd) = Utf8PathBuf::from_path_buf(cwd)
656 && cwd.starts_with(path)
657 {
658 return Err(AppError::Refused(format!(
659 "{path} holds the working directory, so it is not a stage this tool wrote"
660 )));
661 }
662 if !path.join(ARTIFACTS_DIR).is_dir() {
666 return Err(AppError::Refused(format!(
667 "{path} carries no {ARTIFACTS_DIR}/ directory, so it is not a stage this tool wrote"
668 )));
669 }
670
671 let receipt_path = path.join(RECEIPT_FILE);
672 let text = std::fs::read_to_string(&receipt_path).map_err(|source| {
673 AppError::Refused(format!(
674 "{receipt_path} is not readable, so this is not a stage this tool wrote: {source}"
675 ))
676 })?;
677 let receipt: serde_json::Value = serde_json::from_str(&text)
678 .map_err(|source| AppError::Refused(format!("{receipt_path} does not parse: {source}")))?;
679 if receipt.get("schema").and_then(serde_json::Value::as_str) != Some(STAGE_SCHEMA) {
680 return Err(AppError::Refused(format!(
681 "{receipt_path} does not declare {STAGE_SCHEMA}, so this is not a stage"
682 )));
683 }
684 let declared = receipt
685 .get("root")
686 .and_then(serde_json::Value::as_str)
687 .ok_or_else(|| AppError::Refused(format!("{receipt_path} declares no root")))?;
688 if declared != path.as_str() {
689 return Err(AppError::Refused(format!(
690 "{receipt_path} declares the root {declared}, and this path is {path}"
691 )));
692 }
693
694 let aside = scratch_beside(path)?;
698 let _ = std::fs::remove_dir(&aside);
699 std::fs::rename(path, &aside)?;
700 if let Err(source) = std::fs::remove_dir_all(&aside) {
701 if std::fs::rename(&aside, path).is_err() {
705 return Err(AppError::Refused(format!(
706 "{path} could not be removed and is now at {aside}: {source}"
707 )));
708 }
709 return Err(AppError::Io(source));
710 }
711 Ok(vec![format!("removed {path}")])
712}
713
714#[cfg(test)]
715mod tests {
716 #![allow(
717 clippy::unwrap_used,
718 reason = "a test panics as its failure signal, not as control flow"
719 )]
720
721 use super::*;
722
723 fn root(dir: &tempfile::TempDir) -> Utf8PathBuf {
724 Utf8PathBuf::from(dir.path().to_str().unwrap())
725 }
726
727 #[test]
728 fn the_flag_wins_then_the_base_then_the_state_root() {
729 let target = Utf8Path::new("/work/project");
730 let state = Utf8Path::new("/state/spec-driven-docs");
731
732 let (path, source) = resolve_root(
733 target,
734 Some(Utf8Path::new("/tmp/here")),
735 Some("/base"),
736 state,
737 )
738 .unwrap();
739 assert_eq!(path, "/tmp/here");
740 assert_eq!(source, RootSource::Flag);
741
742 let (path, source) = resolve_root(target, None, Some("/base"), state).unwrap();
743 assert!(path.as_str().starts_with("/base/project-"), "{path}");
744 assert_eq!(source, RootSource::Environment);
745
746 let (path, source) = resolve_root(target, None, None, state).unwrap();
747 assert!(
748 path.as_str().starts_with(state.join("stages").as_str()),
749 "{path}"
750 );
751 assert_eq!(source, RootSource::Default);
752 }
753
754 #[test]
755 fn a_relative_stage_root_is_a_usage_error() {
756 let error = resolve_root(
757 Utf8Path::new("/work/project"),
758 Some(Utf8Path::new("stage")),
759 None,
760 Utf8Path::new("/state"),
761 )
762 .unwrap_err();
763 assert_eq!(error.kind(), "Usage");
764 }
765
766 #[test]
767 fn a_relative_step_in_the_stage_root_is_a_usage_error() {
768 for (output, env) in [
771 (Some(Utf8Path::new("/work/project/absent/../inside")), None),
772 (None, Some("/tmp/absent/../../work")),
773 ] {
774 let error = resolve_root(
775 Utf8Path::new("/work/project"),
776 output,
777 env,
778 Utf8Path::new("/state"),
779 )
780 .unwrap_err();
781 assert_eq!(error.kind(), "Usage");
782 assert!(error.to_string().contains("relative step"), "{error}");
783 }
784 }
785
786 #[test]
787 fn two_targets_stage_under_different_names() {
788 assert_ne!(
789 stage_name(Utf8Path::new("/one/project")),
790 stage_name(Utf8Path::new("/two/project"))
791 );
792 }
793
794 #[test]
795 fn clean_refuses_a_directory_that_is_not_a_stage() {
796 let dir = tempfile::tempdir().unwrap();
797 let path = root(&dir).join("not-a-stage");
798 std::fs::create_dir_all(&path).unwrap();
799 let error = clean(&path).unwrap_err();
800 assert_eq!(error.kind(), "Refused");
801 assert!(path.exists(), "the directory was removed anyway");
802 }
803
804 #[test]
805 fn clean_refuses_a_receipt_that_names_another_root() {
806 let dir = tempfile::tempdir().unwrap();
807 let path = root(&dir).join("stage");
808 std::fs::create_dir_all(path.join(ARTIFACTS_DIR)).unwrap();
809 crate::adapters::fs::write_file(
810 &path.join(RECEIPT_FILE),
811 format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"/elsewhere"}}"#).as_bytes(),
812 )
813 .unwrap();
814 let error = clean(&path).unwrap_err();
815 assert!(error.to_string().contains("/elsewhere"), "{error}");
816 assert!(path.exists());
817 }
818
819 #[test]
820 fn clean_refuses_a_link_standing_where_a_stage_stood() {
821 let dir = tempfile::tempdir().unwrap();
822 let real = root(&dir).join("stage");
823 std::fs::create_dir_all(real.join(ARTIFACTS_DIR)).unwrap();
824 crate::adapters::fs::write_file(
825 &real.join(RECEIPT_FILE),
826 format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"{real}"}}"#).as_bytes(),
827 )
828 .unwrap();
829 let link = root(&dir).join("link");
830 std::os::unix::fs::symlink(real.as_std_path(), link.as_std_path()).unwrap();
831
832 let error = clean(&link).unwrap_err();
833 assert!(error.to_string().contains("symlink"), "{error}");
834 assert!(real.exists(), "the link's target was removed");
835 }
836
837 #[test]
838 fn clean_refuses_a_project_root() {
839 let dir = tempfile::tempdir().unwrap();
840 let path = root(&dir).join("project");
841 crate::adapters::fs::write_file(&path.join(MANIFEST_PATH), b"{}").unwrap();
842 crate::adapters::fs::write_file(
843 &path.join(RECEIPT_FILE),
844 format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"{path}"}}"#).as_bytes(),
845 )
846 .unwrap();
847 let error = clean(&path).unwrap_err();
848 assert!(error.to_string().contains("project"), "{error}");
849 assert!(path.exists());
850 }
851
852 #[test]
853 fn clean_refuses_a_forged_receipt_over_a_directory_that_is_not_a_stage() {
854 let dir = tempfile::tempdir().unwrap();
855 let path = root(&dir).join("someones-files");
858 crate::adapters::fs::write_file(&path.join("notes.md"), b"mine").unwrap();
859 crate::adapters::fs::write_file(
860 &path.join(RECEIPT_FILE),
861 format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"{path}"}}"#).as_bytes(),
862 )
863 .unwrap();
864
865 let error = clean(&path).unwrap_err();
866 assert!(error.to_string().contains(ARTIFACTS_DIR), "{error}");
867 assert!(path.join("notes.md").exists(), "the directory was removed");
868 }
869
870 #[test]
871 fn clean_refuses_a_directory_holding_the_working_directory() {
872 let dir = tempfile::tempdir().unwrap();
873 let path = Utf8PathBuf::from_path_buf(std::env::current_dir().unwrap())
874 .unwrap()
875 .parent()
876 .unwrap()
877 .to_owned();
878 let _ = dir;
879 let error = clean(&path).unwrap_err();
880 assert_eq!(error.kind(), "Refused");
881 assert!(path.exists());
882 }
883
884 #[test]
885 fn clean_removes_one_valid_stage() {
886 let dir = tempfile::tempdir().unwrap();
887 let path = root(&dir).join("stage");
888 crate::adapters::fs::write_file(&path.join(ARTIFACTS_DIR).join("AGENTS.md"), b"x").unwrap();
889 crate::adapters::fs::write_file(
890 &path.join(RECEIPT_FILE),
891 format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"{path}"}}"#).as_bytes(),
892 )
893 .unwrap();
894 assert_eq!(clean(&path).unwrap().len(), 1);
895 assert!(!path.exists());
896 }
897}