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; 8] = [
44 "method",
45 "templates",
46 "_docs/specs",
47 "instance",
48 "comparison-docs",
49 "reference/prior-art",
50 "reference/tracker-markup",
51 "_docs/.markdownlint-cli2.jsonc",
52];
53
54#[derive(Debug, Clone)]
60pub struct Request {
61 pub target: Utf8PathBuf,
63 pub profile: Option<ProfileId>,
66 pub output: Option<Utf8PathBuf>,
68 pub docs_scratch: Option<Option<Utf8PathBuf>>,
70 pub reserve: Vec<String>,
72 pub writing_style: Option<crate::domain::instance_config::WritingStyle>,
74 pub acquisition: Option<crate::domain::instance_config::Acquisition>,
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
80#[serde(rename_all = "kebab-case")]
81pub enum RootSource {
82 Flag,
84 Environment,
86 Default,
88}
89
90#[derive(Debug, Clone, Serialize)]
92pub struct Artifact {
93 pub path: String,
95 pub ownership: String,
97 pub placement: String,
99}
100
101#[derive(Debug, Clone, Serialize)]
103pub struct Receipt {
104 pub schema: &'static str,
106 pub version: String,
108 pub target: Utf8PathBuf,
110 pub profile: ProfileId,
112 pub root: Utf8PathBuf,
114 pub root_source: RootSource,
116 pub recorded_version: Option<String>,
118 pub docs_root: String,
120 pub docs_scratch: Option<Utf8PathBuf>,
122 pub reserve: Vec<String>,
124 pub writing_style: String,
126 pub acquisition: Option<crate::domain::instance_config::Acquisition>,
128 pub artifacts: Vec<Artifact>,
130 pub reference: Vec<String>,
132 pub notes: Vec<String>,
134}
135
136pub fn resolve_root(
146 target: &Utf8Path,
147 output: Option<&Utf8Path>,
148 env: Option<&str>,
149 state_root: &Utf8Path,
150) -> Result<(Utf8PathBuf, RootSource), AppError> {
151 let (root, source) = match (output, env) {
152 (Some(named), _) => (named.to_owned(), RootSource::Flag),
153 (None, Some(base)) if !base.is_empty() => (
154 Utf8Path::new(base).join(stage_name(target)),
155 RootSource::Environment,
156 ),
157 _ => (
158 state_root.join("stages").join(stage_name(target)),
159 RootSource::Default,
160 ),
161 };
162 if !root.is_absolute() {
163 return Err(AppError::Usage(format!(
164 "the stage root must be absolute: {root}"
165 )));
166 }
167 if root
171 .components()
172 .any(|part| part.as_str() == ".." || part.as_str() == ".")
173 {
174 return Err(AppError::Usage(format!(
175 "the stage root names a relative step: {root}; give the path it resolves to"
176 )));
177 }
178 Ok((root, source))
179}
180
181fn resolved_ancestor(path: &Utf8Path) -> Utf8PathBuf {
186 let mut walked = path.to_owned();
187 loop {
188 if let Ok(canonical) = std::fs::canonicalize(walked.as_std_path())
189 && let Ok(canonical) = Utf8PathBuf::from_path_buf(canonical)
190 {
191 let rest = path
192 .strip_prefix(&walked)
193 .unwrap_or_else(|_| Utf8Path::new(""));
194 return canonical.join(rest);
195 }
196 let Some(parent) = walked.parent() else {
197 return path.to_owned();
198 };
199 walked = parent.to_owned();
200 }
201}
202
203fn writing_style_of(declaration: &crate::domain::instance_config::InstanceConfig) -> String {
205 use crate::domain::instance_config::WritingSource;
206
207 match declaration.writing_style.source {
208 WritingSource::Builtin => "builtin".to_string(),
209 WritingSource::None => "none".to_string(),
210 WritingSource::Project => declaration
211 .writing_style
212 .path
213 .as_ref()
214 .map_or_else(|| "project".to_string(), |path| format!("project:{path}")),
215 }
216}
217
218fn scratch_beside(root: &Utf8Path) -> Result<Utf8PathBuf, AppError> {
224 let stamp = jiff::Timestamp::now().as_nanosecond();
225 let partial = Utf8PathBuf::from(format!("{root}.partial-{}-{stamp}", std::process::id()));
226 if let Some(parent) = partial.parent() {
227 std::fs::create_dir_all(parent)?;
228 }
229 std::fs::create_dir(&partial).map_err(|source| {
230 AppError::Refused(format!(
231 "{partial} could not be created for this run: {source}"
232 ))
233 })?;
234 Ok(partial)
235}
236
237pub(crate) fn stage_name(target: &Utf8Path) -> String {
242 let digest = crate::domain::ownership::Sha256::of(target.as_str().as_bytes()).to_string();
243 let leaf = target.file_name().unwrap_or("target");
244 format!("{leaf}-{}", &digest[..12])
245}
246
247pub fn create(request: &Request, state_root: &Utf8Path) -> Result<Receipt, AppError> {
255 let target = crate::services::installer::resolved_target(&request.target)?;
256 let env = std::env::var(STAGE_ROOT_VAR).ok();
257 let (root, root_source) = resolve_root(
258 &target,
259 request.output.as_deref(),
260 env.as_deref(),
261 state_root,
262 )?;
263
264 let resolved = resolved_ancestor(&root);
270 if resolved == target || resolved.starts_with(&target) {
271 return Err(AppError::Refused(format!(
272 "{root} is inside {target}, and a stage is written outside the target it describes"
273 )));
274 }
275 if root.exists() && root.read_dir_utf8().is_ok_and(|mut it| it.next().is_some()) {
276 return Err(AppError::Refused(format!(
277 "{root} already holds a stage; read it, or remove it with 'sdd stage clean {root}'"
278 )));
279 }
280
281 let profile = staged_profile(&target, request.profile)?;
282 let options = crate::services::installer::InitOptions {
283 target: target.clone(),
284 profile,
285 apply: false,
286 dry_run: true,
287 docs_scratch: request.docs_scratch.clone(),
288 reserve: request.reserve.clone(),
289 writing_style: request.writing_style.clone(),
290 acquisition: request.acquisition.clone(),
291 replace: Vec::new(),
292 };
293 let candidate = crate::services::installer::candidate_for(&target, &options)?;
294
295 let partial = scratch_beside(&root)?;
300 let render = render(&partial, &target, &root, root_source, &candidate, profile);
301 match render {
302 Ok(receipt) => finish(&partial, &root, receipt),
303 Err(error) => {
304 let _ = std::fs::remove_dir_all(&partial);
308 Err(error)
309 }
310 }
311}
312
313fn finish(partial: &Utf8Path, root: &Utf8Path, receipt: Receipt) -> Result<Receipt, AppError> {
315 if let Some(parent) = root.parent() {
316 std::fs::create_dir_all(parent)?;
317 }
318 let _ = std::fs::remove_dir(root);
321 if let Err(source) = std::fs::rename(partial, root) {
322 let _ = std::fs::remove_dir_all(partial);
323 return Err(AppError::Io(source));
324 }
325 Ok(receipt)
326}
327
328fn render(
330 partial: &Utf8Path,
331 target: &Utf8Path,
332 root: &Utf8Path,
333 root_source: RootSource,
334 candidate: &crate::candidate::Candidate,
335 profile: ProfileId,
336) -> Result<Receipt, AppError> {
337 let mut artifacts = Vec::new();
338 for destination in &candidate.destinations {
339 let path = partial.join(ARTIFACTS_DIR).join(&destination.path);
340 crate::adapters::fs::write_file(&path, &destination.bytes)?;
341 artifacts.push(Artifact {
342 path: destination.path.to_string(),
343 ownership: match destination.ownership {
344 crate::candidate::Ownership::Managed => "managed",
345 crate::candidate::Ownership::Adopted => "adopted",
346 crate::candidate::Ownership::Integration => "integration",
347 }
348 .to_string(),
349 placement: match destination.placement {
350 crate::candidate::Placement::WholeFile => "whole-file",
351 crate::candidate::Placement::MarkedRegion => "marked-region",
352 }
353 .to_string(),
354 });
355 }
356 crate::adapters::fs::write_file(
357 &partial.join(ARTIFACTS_DIR).join(MANIFEST_PATH),
358 candidate.manifest.to_json().as_bytes(),
359 )?;
360 artifacts.push(Artifact {
361 path: MANIFEST_PATH.to_string(),
362 ownership: "record".to_string(),
363 placement: "whole-file".to_string(),
364 });
365
366 let mut reference = Vec::new();
367
368 for name in crate::embedded::skill_names() {
372 let package = crate::embedded::skill_package(name).map_err(anyhow::Error::from)?;
373 for (relative, bytes) in package {
374 crate::adapters::fs::write_file(
375 &partial
376 .join(REFERENCE_DIR)
377 .join("skills")
378 .join(name)
379 .join(&relative),
380 bytes,
381 )?;
382 }
383 }
384 reference.push(format!("{REFERENCE_DIR}/skills"));
385
386 crate::adapters::fs::write_file(
389 &partial.join(REFERENCE_DIR).join("CHANGELOG.md"),
390 crate::embedded::CHANGELOG.as_bytes(),
391 )?;
392 reference.push(format!("{REFERENCE_DIR}/CHANGELOG.md"));
393
394 for root_name in REFERENCE_ROOTS {
395 let mut carried = false;
396 for (path, bytes) in crate::embedded::assets_under(root_name) {
397 crate::adapters::fs::write_file(&partial.join(REFERENCE_DIR).join(&path), bytes)?;
398 carried = true;
399 }
400 if carried {
401 reference.push(format!("{REFERENCE_DIR}/{root_name}"));
402 }
403 }
404 if let Some(bytes) = crate::embedded::asset("instance/docs-catalog.toml") {
405 crate::adapters::fs::write_file(
406 &partial
407 .join(REFERENCE_DIR)
408 .join("instance/docs-catalog.toml"),
409 bytes,
410 )?;
411 reference.push(format!("{REFERENCE_DIR}/instance/docs-catalog.toml"));
412 }
413
414 let receipt = Receipt {
415 schema: STAGE_SCHEMA,
416 version: crate::domain::version::CanonVersion::current().to_string(),
417 target: target.to_owned(),
418 profile,
419 root: root.to_owned(),
420 root_source,
421 recorded_version: crate::services::installer::recorded_field(target, "canon_version")
422 .and_then(|value| value.as_str().map(String::from)),
423 docs_root: candidate.manifest.docs_root.to_string(),
424 docs_scratch: candidate.manifest.docs_scratch.clone(),
425 reserve: candidate.declaration.reserved.clone(),
426 writing_style: writing_style_of(&candidate.declaration),
427 acquisition: candidate.declaration.acquisition.clone(),
428 artifacts,
429 reference,
430 notes: candidate.notes.clone(),
431 };
432 let json = serde_json::to_string_pretty(&receipt)
433 .map_err(|error| anyhow::anyhow!("the stage receipt does not serialize: {error}"))?;
434 crate::adapters::fs::write_file(&partial.join(RECEIPT_FILE), json.as_bytes())?;
435
436 Ok(receipt)
437}
438
439fn staged_profile(target: &Utf8Path, flag: Option<ProfileId>) -> Result<ProfileId, AppError> {
453 let recorded =
454 crate::services::installer::recorded_field(target, "profile").and_then(|value| {
455 ProfileId::every().find(|profile| Some(profile.as_str()) == value.as_str())
456 });
457 match (recorded, flag) {
458 (Some(recorded), Some(asked)) if recorded != asked => Err(AppError::Refused(format!(
459 "{target} records the {recorded} profile and this stage asks for {asked}; \
460 moving a profile moves the documentation root, which is a migration to ask for deliberately"
461 ))),
462 (Some(recorded), _) => Ok(recorded),
463 (None, Some(asked)) => Ok(asked),
464 (None, None) => Ok(ProfileId::Codebase),
465 }
466}
467
468#[derive(Debug, Clone)]
470pub struct StagedChoices {
471 pub target: Utf8PathBuf,
473 pub profile: ProfileId,
475 pub docs_scratch: Option<Utf8PathBuf>,
477 pub reserve: Vec<String>,
479 pub writing_style: crate::domain::instance_config::WritingStyle,
481 pub acquisition: Option<crate::domain::instance_config::Acquisition>,
483 pub artifacts: Vec<HeldArtifact>,
485}
486
487#[derive(Debug, Clone, Deserialize)]
489pub struct HeldArtifact {
490 pub path: String,
492 pub ownership: String,
494}
495
496#[derive(Debug, Deserialize)]
498struct HeldReceipt {
499 schema: String,
500 version: String,
501 target: Utf8PathBuf,
502 profile: ProfileId,
503 root: Utf8PathBuf,
504 docs_scratch: Option<Utf8PathBuf>,
505 #[serde(default)]
506 reserve: Vec<String>,
507 writing_style: String,
508 #[serde(default)]
509 acquisition: Option<crate::domain::instance_config::Acquisition>,
510 #[serde(default)]
511 artifacts: Vec<HeldArtifact>,
512}
513
514pub fn read_choices(root: &Utf8Path, target: &Utf8Path) -> Result<StagedChoices, AppError> {
530 if !root.is_absolute() {
531 return Err(AppError::Usage(format!(
532 "the stage path must be absolute: {root}"
533 )));
534 }
535 let path = root.join(RECEIPT_FILE);
536 let text = std::fs::read_to_string(&path).map_err(|source| {
537 AppError::Refused(format!(
538 "{path} is not readable, so {root} is not a stage this tool wrote: {source}"
539 ))
540 })?;
541 let held: HeldReceipt = serde_json::from_str(&text).map_err(|source| {
542 AppError::Refused(format!(
543 "{path} is not a receipt this release reads: {source}"
544 ))
545 })?;
546 if held.schema != STAGE_SCHEMA {
547 return Err(AppError::Refused(format!(
548 "{path} does not declare {STAGE_SCHEMA}, so this is not a stage"
549 )));
550 }
551 if held.root != root {
552 return Err(AppError::Refused(format!(
553 "{path} declares the root {}, and this path is {root}",
554 held.root
555 )));
556 }
557 let current = crate::domain::version::CanonVersion::current().to_string();
558 if held.version != current {
559 return Err(AppError::Refused(format!(
560 "the stage at {root} was rendered by sdd {}, and this is sdd {current}; stage again with this binary",
561 held.version
562 )));
563 }
564 let target = crate::services::installer::resolved_target(target)?;
565 if held.target != target {
566 return Err(AppError::Refused(format!(
567 "the stage at {root} was rendered for {}, and this landing targets {target}",
568 held.target
569 )));
570 }
571 let writing_style = crate::domain::instance_config::WritingStyle::parse_flag(
572 &held.writing_style,
573 )
574 .map_err(|error| {
575 AppError::Refused(format!(
576 "{path} records a writing style this release refuses: {error}"
577 ))
578 })?;
579 Ok(StagedChoices {
580 target,
581 profile: held.profile,
582 docs_scratch: held.docs_scratch,
583 reserve: held.reserve,
584 writing_style,
585 acquisition: held.acquisition,
586 artifacts: held.artifacts,
587 })
588}
589
590pub fn clean(path: &Utf8Path) -> Result<Vec<String>, AppError> {
598 if !path.is_absolute() {
599 return Err(AppError::Usage(format!(
600 "the stage path must be absolute: {path}"
601 )));
602 }
603 let held = std::fs::symlink_metadata(path)
606 .map_err(|source| AppError::Refused(format!("{path}: {source}")))?;
607 if held.file_type().is_symlink() {
608 return Err(AppError::Refused(format!(
609 "{path} is a symlink; a stage is a directory this tool wrote"
610 )));
611 }
612 if !held.is_dir() {
613 return Err(AppError::Refused(format!("{path} is not a directory")));
614 }
615 if path.parent().is_none() || path.as_str().matches('/').count() < 2 {
616 return Err(AppError::Refused(format!(
617 "{path} is too close to the filesystem root to remove"
618 )));
619 }
620 if path.join(MANIFEST_PATH).exists() || path.join(".git").exists() {
621 return Err(AppError::Refused(format!(
622 "{path} looks like a project rather than a stage"
623 )));
624 }
625 if let Some(home) = crate::domain::paths::UserEnv::from_process().home
629 && path == home
630 {
631 return Err(AppError::Refused(format!(
632 "{path} is the home directory, which is never a stage"
633 )));
634 }
635 if let Ok(cwd) = std::env::current_dir()
636 && let Ok(cwd) = Utf8PathBuf::from_path_buf(cwd)
637 && cwd.starts_with(path)
638 {
639 return Err(AppError::Refused(format!(
640 "{path} holds the working directory, so it is not a stage this tool wrote"
641 )));
642 }
643 if !path.join(ARTIFACTS_DIR).is_dir() {
647 return Err(AppError::Refused(format!(
648 "{path} carries no {ARTIFACTS_DIR}/ directory, so it is not a stage this tool wrote"
649 )));
650 }
651
652 let receipt_path = path.join(RECEIPT_FILE);
653 let text = std::fs::read_to_string(&receipt_path).map_err(|source| {
654 AppError::Refused(format!(
655 "{receipt_path} is not readable, so this is not a stage this tool wrote: {source}"
656 ))
657 })?;
658 let receipt: serde_json::Value = serde_json::from_str(&text)
659 .map_err(|source| AppError::Refused(format!("{receipt_path} does not parse: {source}")))?;
660 if receipt.get("schema").and_then(serde_json::Value::as_str) != Some(STAGE_SCHEMA) {
661 return Err(AppError::Refused(format!(
662 "{receipt_path} does not declare {STAGE_SCHEMA}, so this is not a stage"
663 )));
664 }
665 let declared = receipt
666 .get("root")
667 .and_then(serde_json::Value::as_str)
668 .ok_or_else(|| AppError::Refused(format!("{receipt_path} declares no root")))?;
669 if declared != path.as_str() {
670 return Err(AppError::Refused(format!(
671 "{receipt_path} declares the root {declared}, and this path is {path}"
672 )));
673 }
674
675 let aside = scratch_beside(path)?;
679 let _ = std::fs::remove_dir(&aside);
680 std::fs::rename(path, &aside)?;
681 if let Err(source) = std::fs::remove_dir_all(&aside) {
682 if std::fs::rename(&aside, path).is_err() {
686 return Err(AppError::Refused(format!(
687 "{path} could not be removed and is now at {aside}: {source}"
688 )));
689 }
690 return Err(AppError::Io(source));
691 }
692 Ok(vec![format!("removed {path}")])
693}
694
695#[cfg(test)]
696mod tests {
697 #![allow(
698 clippy::unwrap_used,
699 reason = "a test panics as its failure signal, not as control flow"
700 )]
701
702 use super::*;
703
704 fn root(dir: &tempfile::TempDir) -> Utf8PathBuf {
705 Utf8PathBuf::from(dir.path().to_str().unwrap())
706 }
707
708 #[test]
709 fn the_flag_wins_then_the_base_then_the_state_root() {
710 let target = Utf8Path::new("/work/project");
711 let state = Utf8Path::new("/state/spec-driven-docs");
712
713 let (path, source) = resolve_root(
714 target,
715 Some(Utf8Path::new("/tmp/here")),
716 Some("/base"),
717 state,
718 )
719 .unwrap();
720 assert_eq!(path, "/tmp/here");
721 assert_eq!(source, RootSource::Flag);
722
723 let (path, source) = resolve_root(target, None, Some("/base"), state).unwrap();
724 assert!(path.as_str().starts_with("/base/project-"), "{path}");
725 assert_eq!(source, RootSource::Environment);
726
727 let (path, source) = resolve_root(target, None, None, state).unwrap();
728 assert!(
729 path.as_str().starts_with(state.join("stages").as_str()),
730 "{path}"
731 );
732 assert_eq!(source, RootSource::Default);
733 }
734
735 #[test]
736 fn a_relative_stage_root_is_a_usage_error() {
737 let error = resolve_root(
738 Utf8Path::new("/work/project"),
739 Some(Utf8Path::new("stage")),
740 None,
741 Utf8Path::new("/state"),
742 )
743 .unwrap_err();
744 assert_eq!(error.kind(), "Usage");
745 }
746
747 #[test]
748 fn a_relative_step_in_the_stage_root_is_a_usage_error() {
749 for (output, env) in [
752 (Some(Utf8Path::new("/work/project/absent/../inside")), None),
753 (None, Some("/tmp/absent/../../work")),
754 ] {
755 let error = resolve_root(
756 Utf8Path::new("/work/project"),
757 output,
758 env,
759 Utf8Path::new("/state"),
760 )
761 .unwrap_err();
762 assert_eq!(error.kind(), "Usage");
763 assert!(error.to_string().contains("relative step"), "{error}");
764 }
765 }
766
767 #[test]
768 fn two_targets_stage_under_different_names() {
769 assert_ne!(
770 stage_name(Utf8Path::new("/one/project")),
771 stage_name(Utf8Path::new("/two/project"))
772 );
773 }
774
775 #[test]
776 fn clean_refuses_a_directory_that_is_not_a_stage() {
777 let dir = tempfile::tempdir().unwrap();
778 let path = root(&dir).join("not-a-stage");
779 std::fs::create_dir_all(&path).unwrap();
780 let error = clean(&path).unwrap_err();
781 assert_eq!(error.kind(), "Refused");
782 assert!(path.exists(), "the directory was removed anyway");
783 }
784
785 #[test]
786 fn clean_refuses_a_receipt_that_names_another_root() {
787 let dir = tempfile::tempdir().unwrap();
788 let path = root(&dir).join("stage");
789 std::fs::create_dir_all(path.join(ARTIFACTS_DIR)).unwrap();
790 crate::adapters::fs::write_file(
791 &path.join(RECEIPT_FILE),
792 format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"/elsewhere"}}"#).as_bytes(),
793 )
794 .unwrap();
795 let error = clean(&path).unwrap_err();
796 assert!(error.to_string().contains("/elsewhere"), "{error}");
797 assert!(path.exists());
798 }
799
800 #[test]
801 fn clean_refuses_a_link_standing_where_a_stage_stood() {
802 let dir = tempfile::tempdir().unwrap();
803 let real = root(&dir).join("stage");
804 std::fs::create_dir_all(real.join(ARTIFACTS_DIR)).unwrap();
805 crate::adapters::fs::write_file(
806 &real.join(RECEIPT_FILE),
807 format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"{real}"}}"#).as_bytes(),
808 )
809 .unwrap();
810 let link = root(&dir).join("link");
811 std::os::unix::fs::symlink(real.as_std_path(), link.as_std_path()).unwrap();
812
813 let error = clean(&link).unwrap_err();
814 assert!(error.to_string().contains("symlink"), "{error}");
815 assert!(real.exists(), "the link's target was removed");
816 }
817
818 #[test]
819 fn clean_refuses_a_project_root() {
820 let dir = tempfile::tempdir().unwrap();
821 let path = root(&dir).join("project");
822 crate::adapters::fs::write_file(&path.join(MANIFEST_PATH), b"{}").unwrap();
823 crate::adapters::fs::write_file(
824 &path.join(RECEIPT_FILE),
825 format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"{path}"}}"#).as_bytes(),
826 )
827 .unwrap();
828 let error = clean(&path).unwrap_err();
829 assert!(error.to_string().contains("project"), "{error}");
830 assert!(path.exists());
831 }
832
833 #[test]
834 fn clean_refuses_a_forged_receipt_over_a_directory_that_is_not_a_stage() {
835 let dir = tempfile::tempdir().unwrap();
836 let path = root(&dir).join("someones-files");
839 crate::adapters::fs::write_file(&path.join("notes.md"), b"mine").unwrap();
840 crate::adapters::fs::write_file(
841 &path.join(RECEIPT_FILE),
842 format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"{path}"}}"#).as_bytes(),
843 )
844 .unwrap();
845
846 let error = clean(&path).unwrap_err();
847 assert!(error.to_string().contains(ARTIFACTS_DIR), "{error}");
848 assert!(path.join("notes.md").exists(), "the directory was removed");
849 }
850
851 #[test]
852 fn clean_refuses_a_directory_holding_the_working_directory() {
853 let dir = tempfile::tempdir().unwrap();
854 let path = Utf8PathBuf::from_path_buf(std::env::current_dir().unwrap())
855 .unwrap()
856 .parent()
857 .unwrap()
858 .to_owned();
859 let _ = dir;
860 let error = clean(&path).unwrap_err();
861 assert_eq!(error.kind(), "Refused");
862 assert!(path.exists());
863 }
864
865 #[test]
866 fn clean_removes_one_valid_stage() {
867 let dir = tempfile::tempdir().unwrap();
868 let path = root(&dir).join("stage");
869 crate::adapters::fs::write_file(&path.join(ARTIFACTS_DIR).join("AGENTS.md"), b"x").unwrap();
870 crate::adapters::fs::write_file(
871 &path.join(RECEIPT_FILE),
872 format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"{path}"}}"#).as_bytes(),
873 )
874 .unwrap();
875 assert_eq!(clean(&path).unwrap().len(), 1);
876 assert!(!path.exists());
877 }
878}