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; 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/// What a stage was asked to render.
55///
56/// Every choice a landing takes is here too. A stage rendered under
57/// different choices than the landing that follows it would be evidence
58/// about a candidate nobody is going to write.
59#[derive(Debug, Clone)]
60pub struct Request {
61    /// The repository to render a candidate for.
62    pub target: Utf8PathBuf,
63    /// The profile to project. `None` takes the recorded profile, or the
64    /// codebase profile where nothing is recorded.
65    pub profile: Option<ProfileId>,
66    /// The stage directory the operator named.
67    pub output: Option<Utf8PathBuf>,
68    /// The documentation scratch the candidate would record.
69    pub docs_scratch: Option<Option<Utf8PathBuf>>,
70    /// Paths the candidate would record under `reserved:`.
71    pub reserve: Vec<String>,
72    /// The writing-style selection the candidate would record.
73    pub writing_style: Option<crate::domain::instance_config::WritingStyle>,
74    /// The acquisition decision the candidate would record.
75    pub acquisition: Option<crate::domain::instance_config::Acquisition>,
76}
77
78/// Which rule chose the stage root, for the report that names it.
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
80#[serde(rename_all = "kebab-case")]
81pub enum RootSource {
82    /// The `--output` flag.
83    Flag,
84    /// The `SDD_STAGE_ROOT` base an automation declared.
85    Environment,
86    /// This tool's own state root.
87    Default,
88}
89
90/// One artifact the stage carries, and what a landing would do with it.
91#[derive(Debug, Clone, Serialize)]
92pub struct Artifact {
93    /// The destination, relative to the target.
94    pub path: String,
95    /// Who owns the bytes after a landing.
96    pub ownership: String,
97    /// Whether the candidate carries the file or one region of it.
98    pub placement: String,
99}
100
101/// The receipt a stage carries, and the report the command prints.
102#[derive(Debug, Clone, Serialize)]
103pub struct Receipt {
104    /// The machine schema of this record.
105    pub schema: &'static str,
106    /// The version of the binary that rendered the candidate.
107    pub version: String,
108    /// The target this candidate was rendered for.
109    pub target: Utf8PathBuf,
110    /// The profile projected.
111    pub profile: ProfileId,
112    /// Where this stage sits.
113    pub root: Utf8PathBuf,
114    /// Which rule chose that root.
115    pub root_source: RootSource,
116    /// The version the target's own record claims, where one is readable.
117    pub recorded_version: Option<String>,
118    /// The documentation root the candidate records.
119    pub docs_root: String,
120    /// The documentation scratch the candidate records.
121    pub docs_scratch: Option<Utf8PathBuf>,
122    /// The paths the candidate's own declaration reserves.
123    pub reserve: Vec<String>,
124    /// The writing source the candidate's own declaration selects.
125    pub writing_style: String,
126    /// The acquisition decision the candidate's own declaration records.
127    pub acquisition: Option<crate::domain::instance_config::Acquisition>,
128    /// Every destination the candidate would land.
129    pub artifacts: Vec<Artifact>,
130    /// Every reference root copied, relative to the stage.
131    pub reference: Vec<String>,
132    /// What the projection chose to leave alone, and why.
133    pub notes: Vec<String>,
134}
135
136/// Where a stage goes, and which rule decided.
137///
138/// The flag wins, then the automation base, then this tool's state root.
139/// The base is a directory of stages rather than one stage, so an
140/// automation that stages many targets names one variable.
141///
142/// # Errors
143///
144/// [`AppError::Usage`] when the resolved path is relative.
145pub 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    // Whatever chose the root, a relative step in it resolves only once
168    // the directories exist, which is after the containment check has
169    // already run. The path the operator means is the one to give.
170    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
181/// The nearest existing ancestor of a path, resolved through every link.
182///
183/// A path that does not exist yet still has an ancestor that does, and
184/// that is what says where it will really be created.
185fn 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
203/// The writing source a declaration selects, as one word a reader keeps.
204fn 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
218/// A scratch sibling this run alone owns.
219///
220/// The name carries the process and a timestamp, and the directory is
221/// created exclusively, so the run never removes a path somebody else
222/// left. A collision refuses rather than clearing what is there.
223fn 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
237/// One target's stage directory name: its own name and a digest of its path.
238///
239/// Two checkouts of one repository stage side by side, and neither name is
240/// guessed from the other.
241pub(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
247/// Render one candidate into a stage, and report what it holds.
248///
249/// # Errors
250///
251/// [`AppError::Usage`] for a target or stage path the arguments cannot
252/// mean, [`AppError::Refused`] where the stage directory already holds
253/// something, and I/O errors writing the stage.
254pub 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    // A stage inside the target would be the one thing this command
265    // promises not to do: put the candidate and its reference corpus into
266    // the repository it is supposed to leave alone. The comparison is
267    // between resolved paths, because a link in the output's ancestry
268    // would otherwise carry it back inside.
269    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    // Render beside the destination and rename the finished directory into
296    // place, so a reader never meets a stage that is still being written.
297    // The scratch name is this run's own: a predictable one would make the
298    // command remove a sibling nothing proves it wrote.
299    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            // The directory is this run's own, so removing it takes back
305            // only what this run made. A failure that left it behind would
306            // accumulate debris no command removes.
307            let _ = std::fs::remove_dir_all(&partial);
308            Err(error)
309        }
310    }
311}
312
313/// Rename the finished directory into place.
314fn 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    // An empty directory at the destination is the one thing a rename
319    // cannot land on. Anything else there already refused above.
320    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
328/// Write one candidate and its reference material under `partial`.
329fn 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    // The skills are copied as the packages an agent resolves, not as the
369    // authored tree: a skill names its gates relative to its own root, and
370    // a copy that split them would carry two broken references.
371    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    // The release notes of the exact installed version, which is where a
387    // migration reads what this release asked of an instance.
388    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
439/// The profile a stage projects: the recorded one wherever an instance is.
440///
441/// A stage over an instance is evidence for that instance's next landing,
442/// so it projects the profile the record names. A different `--profile`
443/// refuses, because moving a profile moves the documentation root, which is
444/// a migration to ask for deliberately rather than an upgrade's candidate.
445///
446/// SATISFIES staging:a-stage-takes-the-recorded-choices
447///
448/// # Errors
449///
450/// [`AppError::Refused`] where the flag names another profile than the
451/// record.
452fn 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/// The choices one stage receipt records, as a landing takes them.
469#[derive(Debug, Clone)]
470pub struct StagedChoices {
471    /// The target the stage was rendered for.
472    pub target: Utf8PathBuf,
473    /// The profile it projected.
474    pub profile: ProfileId,
475    /// The documentation scratch the candidate records.
476    pub docs_scratch: Option<Utf8PathBuf>,
477    /// The paths the candidate's declaration reserves.
478    pub reserve: Vec<String>,
479    /// The writing-style selection the candidate's declaration records.
480    pub writing_style: crate::domain::instance_config::WritingStyle,
481    /// The acquisition decision the candidate's declaration records.
482    pub acquisition: Option<crate::domain::instance_config::Acquisition>,
483    /// Every destination the stage rendered, with its ownership.
484    pub artifacts: Vec<HeldArtifact>,
485}
486
487/// One destination a receipt lists.
488#[derive(Debug, Clone, Deserialize)]
489pub struct HeldArtifact {
490    /// The destination, relative to the target.
491    pub path: String,
492    /// Who owns the bytes after a landing, as the receipt spells it.
493    pub ownership: String,
494}
495
496/// The receipt fields a landing reads, and nothing else.
497#[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
514/// Read the choices a stage recorded, for a landing that takes them.
515///
516/// The receipt is the one file of a stage a landing reads, and only for the
517/// choices it names: every byte the landing writes is rendered again from
518/// this binary's own sources. A receipt another release wrote describes a
519/// candidate this binary does not carry, and a receipt for another target
520/// describes a landing nobody asked for here, so both refuse.
521///
522/// SATISFIES staging:a-landing-takes-the-choices-its-stage-recorded
523///
524/// # Errors
525///
526/// [`AppError::Usage`] for a relative path, and [`AppError::Refused`] where
527/// the path holds no receipt this tool wrote, where another release wrote
528/// it, or where it names another target than `target`.
529pub 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
590/// Remove one stage this tool wrote, and refuse anything else.
591///
592/// # Errors
593///
594/// [`AppError::Usage`] for a relative path, and [`AppError::Refused`] for a
595/// path that is not a stage, a stage whose receipt names another root, a
596/// link, or a root this tool will not recurse into.
597pub 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    // The final component is inspected without following it, so a link
604    // standing where a stage stood cannot redirect the removal.
605    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    // A receipt is ordinary user-writable JSON, so it proves nothing on
626    // its own. These refusals are what stand between a forged one and a
627    // recursive removal of somewhere that matters.
628    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    // A stage this tool wrote holds the tree it renders. A directory that
644    // carries a receipt and none of that structure is something else
645    // wearing the name.
646    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    // Move the validated directory aside under a name this run owns, then
676    // remove that. A directory swapped in after the checks is left where
677    // it is, because what this removes is the thing it just moved.
678    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        // Put it back under the name the operator knows, so a second try
683        // can find it. Where even that fails, name both paths: a stage
684        // nobody can address again is worse than the failure itself.
685        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        // A path with a nonexistent prefix and a `..` resolves somewhere
750        // the containment check cannot see until the directory exists.
751        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        // Somebody's directory of work, with a receipt dropped in it that
837        // names the directory as its own root.
838        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}