Skip to main content

spec_driven_docs/
stage.rs

1//! The stage: a persistent workbench holding one rendered candidate.
2//!
3//! A stage is evidence an agent reads. It holds every destination the
4//! candidate would land, the reference material of the exact installed
5//! version, and a receipt describing both. It is written outside the target
6//! and never into it, and no production verb reads a byte of it: a landing
7//! renders the candidate again from this binary's own sources.
8//!
9//! The directory is renamed into place once it is complete, so a stage a
10//! reader can see is a stage that finished. Only `sdd stage clean` removes
11//! one, and only after the receipt inside it says this tool wrote it.
12
13use 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
22/// The machine schema `stage.json` declares.
23pub const STAGE_SCHEMA: &str = "sdd.stage/1";
24
25/// The base directory an automation points every stage at.
26pub const STAGE_ROOT_VAR: &str = "SDD_STAGE_ROOT";
27
28/// The receipt every stage carries, and the one file `clean` trusts.
29pub const RECEIPT_FILE: &str = "stage.json";
30
31/// Where the candidate's own destinations are rendered.
32pub const ARTIFACTS_DIR: &str = "artifacts";
33
34/// Where the installed version's reference material is copied.
35pub const REFERENCE_DIR: &str = "reference";
36
37/// The payload roots a stage carries as reference material.
38///
39/// Every root the binary carries that an adopting project reads while it
40/// migrates. The repository's own decision records and tests are not here:
41/// they are this project's history and its proof, and neither is knowledge
42/// an adopting project reads.
43const REFERENCE_ROOTS: [&str; 6] = [
44    "method",
45    "templates",
46    "instance",
47    "comparison-docs",
48    "reference/prior-art",
49    "reference/tracker-markup",
50];
51
52/// What a stage was asked to render.
53///
54/// Every choice a landing takes is here too. A stage rendered under
55/// different choices than the landing that follows it would be evidence
56/// about a candidate nobody is going to write.
57#[derive(Debug, Clone)]
58pub struct Request {
59    /// The repository to render a candidate for.
60    pub target: Utf8PathBuf,
61    /// The profile to project. `None` takes the recorded profile, or the
62    /// codebase profile where nothing is recorded.
63    pub profile: Option<ProfileId>,
64    /// The stage directory the operator named.
65    pub output: Option<Utf8PathBuf>,
66    /// The documentation scratch the candidate would record.
67    pub docs_scratch: Option<Option<Utf8PathBuf>>,
68    /// Paths the candidate would record under `reserved:`.
69    pub reserve: Vec<String>,
70    /// The writing-style selection the candidate would record.
71    pub writing_style: Option<crate::domain::instance_config::WritingStyle>,
72    /// The acquisition decision the candidate would record.
73    pub acquisition: Option<crate::domain::instance_config::Acquisition>,
74}
75
76/// Which rule chose the stage root, for the report that names it.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
78#[serde(rename_all = "kebab-case")]
79pub enum RootSource {
80    /// The `--output` flag.
81    Flag,
82    /// The `SDD_STAGE_ROOT` base an automation declared.
83    Environment,
84    /// This tool's own state root.
85    Default,
86}
87
88/// One artifact the stage carries, and what a landing would do with it.
89#[derive(Debug, Clone, Serialize)]
90pub struct Artifact {
91    /// The destination, relative to the target.
92    pub path: String,
93    /// Who owns the bytes after a landing.
94    pub ownership: String,
95    /// Whether the candidate carries the file or one region of it.
96    pub placement: String,
97}
98
99/// The receipt a stage carries, and the report the command prints.
100#[derive(Debug, Clone, Serialize)]
101pub struct Receipt {
102    /// The machine schema of this record.
103    pub schema: &'static str,
104    /// The version of the binary that rendered the candidate.
105    pub version: String,
106    /// The target this candidate was rendered for.
107    pub target: Utf8PathBuf,
108    /// The profile projected.
109    pub profile: ProfileId,
110    /// Where this stage sits.
111    pub root: Utf8PathBuf,
112    /// Which rule chose that root.
113    pub root_source: RootSource,
114    /// The version the target's own record claims, where one is readable.
115    pub recorded_version: Option<String>,
116    /// The documentation root the candidate records.
117    pub docs_root: String,
118    /// The documentation scratch the candidate records.
119    pub docs_scratch: Option<Utf8PathBuf>,
120    /// The paths the candidate's own declaration reserves.
121    pub reserve: Vec<String>,
122    /// The writing source the candidate's own declaration selects.
123    pub writing_style: String,
124    /// The acquisition decision the candidate's own declaration records.
125    pub acquisition: Option<crate::domain::instance_config::Acquisition>,
126    /// Every destination the candidate would land.
127    pub artifacts: Vec<Artifact>,
128    /// Every recorded managed file the candidate no longer lands whose
129    /// bytes are the recorded ones, which the landing would delete.
130    pub retired: Vec<String>,
131    /// Every recorded managed file the candidate no longer lands that was
132    /// edited, which the landing would leave as the project's.
133    pub dropped: Vec<String>,
134    /// Every reference root copied, relative to the stage.
135    pub reference: Vec<String>,
136    /// What the projection chose to leave alone, and why.
137    pub notes: Vec<String>,
138}
139
140/// Where a stage goes, and which rule decided.
141///
142/// The flag wins, then the automation base, then this tool's state root.
143/// The base is a directory of stages rather than one stage, so an
144/// automation that stages many targets names one variable.
145///
146/// # Errors
147///
148/// [`AppError::Usage`] when the resolved path is relative.
149pub 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    // Whatever chose the root, a relative step in it resolves only once
172    // the directories exist, which is after the containment check has
173    // already run. The path the operator means is the one to give.
174    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
185/// The nearest existing ancestor of a path, resolved through every link.
186///
187/// A path that does not exist yet still has an ancestor that does, and
188/// that is what says where it will really be created.
189fn 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
207/// The writing source a declaration selects, as one word a reader keeps.
208fn 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
222/// A scratch sibling this run alone owns.
223///
224/// The name carries the process and a timestamp, and the directory is
225/// created exclusively, so the run never removes a path somebody else
226/// left. A collision refuses rather than clearing what is there.
227fn 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
241/// One target's stage directory name: its own name and a digest of its path.
242///
243/// Two checkouts of one repository stage side by side, and neither name is
244/// guessed from the other.
245pub(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
251/// Render one candidate into a stage, and report what it holds.
252///
253/// # Errors
254///
255/// [`AppError::Usage`] for a target or stage path the arguments cannot
256/// mean, [`AppError::Refused`] where the stage directory already holds
257/// something, and I/O errors writing the stage.
258pub 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    // A stage inside the target would be the one thing this command
269    // promises not to do: put the candidate and its reference corpus into
270    // the repository it is supposed to leave alone. The comparison is
271    // between resolved paths, because a link in the output's ancestry
272    // would otherwise carry it back inside.
273    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    // Render beside the destination and rename the finished directory into
300    // place, so a reader never meets a stage that is still being written.
301    // The scratch name is this run's own: a predictable one would make the
302    // command remove a sibling nothing proves it wrote.
303    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            // The directory is this run's own, so removing it takes back
309            // only what this run made. A failure that left it behind would
310            // accumulate debris no command removes.
311            let _ = std::fs::remove_dir_all(&partial);
312            Err(error)
313        }
314    }
315}
316
317/// Rename the finished directory into place.
318fn 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    // An empty directory at the destination is the one thing a rename
323    // cannot land on. Anything else there already refused above.
324    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
332/// Write the specs this binary serves, and the documentation root's lint
333/// configuration, under the reference directory at the paths an instance
334/// holds them.
335fn 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
352/// Write one candidate and its reference material under `partial`.
353fn 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    // The skills are copied as the packages an agent resolves, not as the
393    // authored tree: a skill names its gates relative to its own root, and
394    // a copy that split them would carry two broken references.
395    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    // The release notes of the exact installed version, which is where a
411    // migration reads what this release asked of an instance.
412    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    // The sort the landing itself runs, so the stage names what the apply
440    // deletes and what it leaves.
441    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
474/// The profile a stage projects: the recorded one wherever an instance is.
475///
476/// A stage over an instance is evidence for that instance's next landing,
477/// so it projects the profile the record names. A different `--profile`
478/// refuses, because moving a profile moves the documentation root, which is
479/// a migration to ask for deliberately rather than an upgrade's candidate.
480///
481/// SATISFIES staging:a-stage-takes-the-recorded-choices
482///
483/// # Errors
484///
485/// [`AppError::Refused`] where the flag names another profile than the
486/// record.
487fn 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/// The choices one stage receipt records, as a landing takes them.
504#[derive(Debug, Clone)]
505pub struct StagedChoices {
506    /// The target the stage was rendered for.
507    pub target: Utf8PathBuf,
508    /// The profile it projected.
509    pub profile: ProfileId,
510    /// The documentation scratch the candidate records.
511    pub docs_scratch: Option<Utf8PathBuf>,
512    /// The paths the candidate's declaration reserves.
513    pub reserve: Vec<String>,
514    /// The writing-style selection the candidate's declaration records.
515    pub writing_style: crate::domain::instance_config::WritingStyle,
516    /// The acquisition decision the candidate's declaration records.
517    pub acquisition: Option<crate::domain::instance_config::Acquisition>,
518    /// Every destination the stage rendered, with its ownership.
519    pub artifacts: Vec<HeldArtifact>,
520}
521
522/// One destination a receipt lists.
523#[derive(Debug, Clone, Deserialize)]
524pub struct HeldArtifact {
525    /// The destination, relative to the target.
526    pub path: String,
527    /// Who owns the bytes after a landing, as the receipt spells it.
528    pub ownership: String,
529}
530
531/// The receipt fields a landing reads, and nothing else.
532#[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
549/// Read the choices a stage recorded, for a landing that takes them.
550///
551/// The receipt is the one file of a stage a landing reads, and only for the
552/// choices it names: every byte the landing writes is rendered again from
553/// this binary's own sources. A receipt another release wrote describes a
554/// candidate this binary does not carry, and a receipt for another target
555/// describes a landing nobody asked for here, so both refuse.
556///
557/// SATISFIES staging:a-landing-takes-the-choices-its-stage-recorded
558///
559/// # Errors
560///
561/// [`AppError::Usage`] for a relative path, and [`AppError::Refused`] where
562/// the path holds no receipt this tool wrote, where another release wrote
563/// it, or where it names another target than `target`.
564pub 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
625/// Remove one stage this tool wrote, and refuse anything else.
626///
627/// # Errors
628///
629/// [`AppError::Usage`] for a relative path, and [`AppError::Refused`] for a
630/// path that is not a stage, a stage whose receipt names another root, a
631/// link, or a root this tool will not recurse into.
632pub 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    // The final component is inspected without following it, so a link
639    // standing where a stage stood cannot redirect the removal.
640    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    // A receipt is ordinary user-writable JSON, so it proves nothing on
661    // its own. These refusals are what stand between a forged one and a
662    // recursive removal of somewhere that matters.
663    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    // A stage this tool wrote holds the tree it renders. A directory that
679    // carries a receipt and none of that structure is something else
680    // wearing the name.
681    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    // Move the validated directory aside under a name this run owns, then
711    // remove that. A directory swapped in after the checks is left where
712    // it is, because what this removes is the thing it just moved.
713    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        // Put it back under the name the operator knows, so a second try
718        // can find it. Where even that fails, name both paths: a stage
719        // nobody can address again is worse than the failure itself.
720        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        // A path with a nonexistent prefix and a `..` resolves somewhere
785        // the containment check cannot see until the directory exists.
786        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        // Somebody's directory of work, with a receipt dropped in it that
872        // names the directory as its own root.
873        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}