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 reference root copied, relative to the stage.
129    pub reference: Vec<String>,
130    /// What the projection chose to leave alone, and why.
131    pub notes: Vec<String>,
132}
133
134/// Where a stage goes, and which rule decided.
135///
136/// The flag wins, then the automation base, then this tool's state root.
137/// The base is a directory of stages rather than one stage, so an
138/// automation that stages many targets names one variable.
139///
140/// # Errors
141///
142/// [`AppError::Usage`] when the resolved path is relative.
143pub fn resolve_root(
144    target: &Utf8Path,
145    output: Option<&Utf8Path>,
146    env: Option<&str>,
147    state_root: &Utf8Path,
148) -> Result<(Utf8PathBuf, RootSource), AppError> {
149    let (root, source) = match (output, env) {
150        (Some(named), _) => (named.to_owned(), RootSource::Flag),
151        (None, Some(base)) if !base.is_empty() => (
152            Utf8Path::new(base).join(stage_name(target)),
153            RootSource::Environment,
154        ),
155        _ => (
156            state_root.join("stages").join(stage_name(target)),
157            RootSource::Default,
158        ),
159    };
160    if !root.is_absolute() {
161        return Err(AppError::Usage(format!(
162            "the stage root must be absolute: {root}"
163        )));
164    }
165    // Whatever chose the root, a relative step in it resolves only once
166    // the directories exist, which is after the containment check has
167    // already run. The path the operator means is the one to give.
168    if root
169        .components()
170        .any(|part| part.as_str() == ".." || part.as_str() == ".")
171    {
172        return Err(AppError::Usage(format!(
173            "the stage root names a relative step: {root}; give the path it resolves to"
174        )));
175    }
176    Ok((root, source))
177}
178
179/// The nearest existing ancestor of a path, resolved through every link.
180///
181/// A path that does not exist yet still has an ancestor that does, and
182/// that is what says where it will really be created.
183fn resolved_ancestor(path: &Utf8Path) -> Utf8PathBuf {
184    let mut walked = path.to_owned();
185    loop {
186        if let Ok(canonical) = std::fs::canonicalize(walked.as_std_path())
187            && let Ok(canonical) = Utf8PathBuf::from_path_buf(canonical)
188        {
189            let rest = path
190                .strip_prefix(&walked)
191                .unwrap_or_else(|_| Utf8Path::new(""));
192            return canonical.join(rest);
193        }
194        let Some(parent) = walked.parent() else {
195            return path.to_owned();
196        };
197        walked = parent.to_owned();
198    }
199}
200
201/// The writing source a declaration selects, as one word a reader keeps.
202fn writing_style_of(declaration: &crate::domain::instance_config::InstanceConfig) -> String {
203    use crate::domain::instance_config::WritingSource;
204
205    match declaration.writing_style.source {
206        WritingSource::Builtin => "builtin".to_string(),
207        WritingSource::None => "none".to_string(),
208        WritingSource::Project => declaration
209            .writing_style
210            .path
211            .as_ref()
212            .map_or_else(|| "project".to_string(), |path| format!("project:{path}")),
213    }
214}
215
216/// A scratch sibling this run alone owns.
217///
218/// The name carries the process and a timestamp, and the directory is
219/// created exclusively, so the run never removes a path somebody else
220/// left. A collision refuses rather than clearing what is there.
221fn scratch_beside(root: &Utf8Path) -> Result<Utf8PathBuf, AppError> {
222    let stamp = jiff::Timestamp::now().as_nanosecond();
223    let partial = Utf8PathBuf::from(format!("{root}.partial-{}-{stamp}", std::process::id()));
224    if let Some(parent) = partial.parent() {
225        std::fs::create_dir_all(parent)?;
226    }
227    std::fs::create_dir(&partial).map_err(|source| {
228        AppError::Refused(format!(
229            "{partial} could not be created for this run: {source}"
230        ))
231    })?;
232    Ok(partial)
233}
234
235/// One target's stage directory name: its own name and a digest of its path.
236///
237/// Two checkouts of one repository stage side by side, and neither name is
238/// guessed from the other.
239pub(crate) fn stage_name(target: &Utf8Path) -> String {
240    let digest = crate::domain::ownership::Sha256::of(target.as_str().as_bytes()).to_string();
241    let leaf = target.file_name().unwrap_or("target");
242    format!("{leaf}-{}", &digest[..12])
243}
244
245/// Render one candidate into a stage, and report what it holds.
246///
247/// # Errors
248///
249/// [`AppError::Usage`] for a target or stage path the arguments cannot
250/// mean, [`AppError::Refused`] where the stage directory already holds
251/// something, and I/O errors writing the stage.
252pub fn create(request: &Request, state_root: &Utf8Path) -> Result<Receipt, AppError> {
253    let target = crate::services::installer::resolved_target(&request.target)?;
254    let env = std::env::var(STAGE_ROOT_VAR).ok();
255    let (root, root_source) = resolve_root(
256        &target,
257        request.output.as_deref(),
258        env.as_deref(),
259        state_root,
260    )?;
261
262    // A stage inside the target would be the one thing this command
263    // promises not to do: put the candidate and its reference corpus into
264    // the repository it is supposed to leave alone. The comparison is
265    // between resolved paths, because a link in the output's ancestry
266    // would otherwise carry it back inside.
267    let resolved = resolved_ancestor(&root);
268    if resolved == target || resolved.starts_with(&target) {
269        return Err(AppError::Refused(format!(
270            "{root} is inside {target}, and a stage is written outside the target it describes"
271        )));
272    }
273    if root.exists() && root.read_dir_utf8().is_ok_and(|mut it| it.next().is_some()) {
274        return Err(AppError::Refused(format!(
275            "{root} already holds a stage; read it, or remove it with 'sdd stage clean {root}'"
276        )));
277    }
278
279    let profile = staged_profile(&target, request.profile)?;
280    let options = crate::services::installer::InitOptions {
281        target: target.clone(),
282        profile,
283        apply: false,
284        dry_run: true,
285        docs_scratch: request.docs_scratch.clone(),
286        reserve: request.reserve.clone(),
287        writing_style: request.writing_style.clone(),
288        acquisition: request.acquisition.clone(),
289        replace: Vec::new(),
290    };
291    let candidate = crate::services::installer::candidate_for(&target, &options)?;
292
293    // Render beside the destination and rename the finished directory into
294    // place, so a reader never meets a stage that is still being written.
295    // The scratch name is this run's own: a predictable one would make the
296    // command remove a sibling nothing proves it wrote.
297    let partial = scratch_beside(&root)?;
298    let render = render(&partial, &target, &root, root_source, &candidate, profile);
299    match render {
300        Ok(receipt) => finish(&partial, &root, receipt),
301        Err(error) => {
302            // The directory is this run's own, so removing it takes back
303            // only what this run made. A failure that left it behind would
304            // accumulate debris no command removes.
305            let _ = std::fs::remove_dir_all(&partial);
306            Err(error)
307        }
308    }
309}
310
311/// Rename the finished directory into place.
312fn finish(partial: &Utf8Path, root: &Utf8Path, receipt: Receipt) -> Result<Receipt, AppError> {
313    if let Some(parent) = root.parent() {
314        std::fs::create_dir_all(parent)?;
315    }
316    // An empty directory at the destination is the one thing a rename
317    // cannot land on. Anything else there already refused above.
318    let _ = std::fs::remove_dir(root);
319    if let Err(source) = std::fs::rename(partial, root) {
320        let _ = std::fs::remove_dir_all(partial);
321        return Err(AppError::Io(source));
322    }
323    Ok(receipt)
324}
325
326/// Write the specs this binary serves, and the documentation root's lint
327/// configuration, under the reference directory at the paths an instance
328/// holds them.
329fn served_reference(partial: &Utf8Path, reference: &mut Vec<String>) -> Result<(), AppError> {
330    for (name, file) in crate::embedded::spec_files() {
331        crate::adapters::fs::write_file(
332            &partial.join(REFERENCE_DIR).join("_docs/specs").join(name),
333            file.contents(),
334        )?;
335    }
336    reference.push(format!("{REFERENCE_DIR}/_docs/specs"));
337    let lint = "_docs/.markdownlint-cli2.jsonc";
338    if let Some(bytes) = crate::embedded::asset(&format!("{}/{lint}", crate::embedded::PAYLOAD_DIR))
339    {
340        crate::adapters::fs::write_file(&partial.join(REFERENCE_DIR).join(lint), bytes)?;
341        reference.push(format!("{REFERENCE_DIR}/{lint}"));
342    }
343    Ok(())
344}
345
346/// Write one candidate and its reference material under `partial`.
347fn render(
348    partial: &Utf8Path,
349    target: &Utf8Path,
350    root: &Utf8Path,
351    root_source: RootSource,
352    candidate: &crate::candidate::Candidate,
353    profile: ProfileId,
354) -> Result<Receipt, AppError> {
355    let mut artifacts = Vec::new();
356    for destination in &candidate.destinations {
357        let path = partial.join(ARTIFACTS_DIR).join(&destination.path);
358        crate::adapters::fs::write_file(&path, &destination.bytes)?;
359        artifacts.push(Artifact {
360            path: destination.path.to_string(),
361            ownership: match destination.ownership {
362                crate::candidate::Ownership::Managed => "managed",
363                crate::candidate::Ownership::Adopted => "adopted",
364                crate::candidate::Ownership::Integration => "integration",
365            }
366            .to_string(),
367            placement: match destination.placement {
368                crate::candidate::Placement::WholeFile => "whole-file",
369                crate::candidate::Placement::MarkedRegion => "marked-region",
370            }
371            .to_string(),
372        });
373    }
374    crate::adapters::fs::write_file(
375        &partial.join(ARTIFACTS_DIR).join(MANIFEST_PATH),
376        candidate.manifest.to_json().as_bytes(),
377    )?;
378    artifacts.push(Artifact {
379        path: MANIFEST_PATH.to_string(),
380        ownership: "record".to_string(),
381        placement: "whole-file".to_string(),
382    });
383
384    let mut reference = Vec::new();
385
386    // The skills are copied as the packages an agent resolves, not as the
387    // authored tree: a skill names its gates relative to its own root, and
388    // a copy that split them would carry two broken references.
389    for name in crate::embedded::skill_names() {
390        let package = crate::embedded::skill_package(name).map_err(anyhow::Error::from)?;
391        for (relative, bytes) in package {
392            crate::adapters::fs::write_file(
393                &partial
394                    .join(REFERENCE_DIR)
395                    .join("skills")
396                    .join(name)
397                    .join(&relative),
398                bytes,
399            )?;
400        }
401    }
402    reference.push(format!("{REFERENCE_DIR}/skills"));
403
404    // The release notes of the exact installed version, which is where a
405    // migration reads what this release asked of an instance.
406    crate::adapters::fs::write_file(
407        &partial.join(REFERENCE_DIR).join("CHANGELOG.md"),
408        crate::embedded::CHANGELOG.as_bytes(),
409    )?;
410    reference.push(format!("{REFERENCE_DIR}/CHANGELOG.md"));
411
412    for root_name in REFERENCE_ROOTS {
413        let mut carried = false;
414        for (path, bytes) in crate::embedded::assets_under(root_name) {
415            crate::adapters::fs::write_file(&partial.join(REFERENCE_DIR).join(&path), bytes)?;
416            carried = true;
417        }
418        if carried {
419            reference.push(format!("{REFERENCE_DIR}/{root_name}"));
420        }
421    }
422    served_reference(partial, &mut reference)?;
423    if let Some(bytes) = crate::embedded::asset("instance/docs-catalog.toml") {
424        crate::adapters::fs::write_file(
425            &partial
426                .join(REFERENCE_DIR)
427                .join("instance/docs-catalog.toml"),
428            bytes,
429        )?;
430        reference.push(format!("{REFERENCE_DIR}/instance/docs-catalog.toml"));
431    }
432
433    let receipt = Receipt {
434        schema: STAGE_SCHEMA,
435        version: crate::domain::version::CanonVersion::current().to_string(),
436        target: target.to_owned(),
437        profile,
438        root: root.to_owned(),
439        root_source,
440        recorded_version: crate::services::installer::recorded_field(target, "canon_version")
441            .and_then(|value| value.as_str().map(String::from)),
442        docs_root: candidate.manifest.docs_root.to_string(),
443        docs_scratch: candidate.manifest.docs_scratch.clone(),
444        reserve: candidate.declaration.reserved.clone(),
445        writing_style: writing_style_of(&candidate.declaration),
446        acquisition: candidate.declaration.acquisition.clone(),
447        artifacts,
448        reference,
449        notes: candidate.notes.clone(),
450    };
451    let json = serde_json::to_string_pretty(&receipt)
452        .map_err(|error| anyhow::anyhow!("the stage receipt does not serialize: {error}"))?;
453    crate::adapters::fs::write_file(&partial.join(RECEIPT_FILE), json.as_bytes())?;
454
455    Ok(receipt)
456}
457
458/// The profile a stage projects: the recorded one wherever an instance is.
459///
460/// A stage over an instance is evidence for that instance's next landing,
461/// so it projects the profile the record names. A different `--profile`
462/// refuses, because moving a profile moves the documentation root, which is
463/// a migration to ask for deliberately rather than an upgrade's candidate.
464///
465/// SATISFIES staging:a-stage-takes-the-recorded-choices
466///
467/// # Errors
468///
469/// [`AppError::Refused`] where the flag names another profile than the
470/// record.
471fn staged_profile(target: &Utf8Path, flag: Option<ProfileId>) -> Result<ProfileId, AppError> {
472    let recorded =
473        crate::services::installer::recorded_field(target, "profile").and_then(|value| {
474            ProfileId::every().find(|profile| Some(profile.as_str()) == value.as_str())
475        });
476    match (recorded, flag) {
477        (Some(recorded), Some(asked)) if recorded != asked => Err(AppError::Refused(format!(
478            "{target} records the {recorded} profile and this stage asks for {asked}; \
479             moving a profile moves the documentation root, which is a migration to ask for deliberately"
480        ))),
481        (Some(recorded), _) => Ok(recorded),
482        (None, Some(asked)) => Ok(asked),
483        (None, None) => Ok(ProfileId::Codebase),
484    }
485}
486
487/// The choices one stage receipt records, as a landing takes them.
488#[derive(Debug, Clone)]
489pub struct StagedChoices {
490    /// The target the stage was rendered for.
491    pub target: Utf8PathBuf,
492    /// The profile it projected.
493    pub profile: ProfileId,
494    /// The documentation scratch the candidate records.
495    pub docs_scratch: Option<Utf8PathBuf>,
496    /// The paths the candidate's declaration reserves.
497    pub reserve: Vec<String>,
498    /// The writing-style selection the candidate's declaration records.
499    pub writing_style: crate::domain::instance_config::WritingStyle,
500    /// The acquisition decision the candidate's declaration records.
501    pub acquisition: Option<crate::domain::instance_config::Acquisition>,
502    /// Every destination the stage rendered, with its ownership.
503    pub artifacts: Vec<HeldArtifact>,
504}
505
506/// One destination a receipt lists.
507#[derive(Debug, Clone, Deserialize)]
508pub struct HeldArtifact {
509    /// The destination, relative to the target.
510    pub path: String,
511    /// Who owns the bytes after a landing, as the receipt spells it.
512    pub ownership: String,
513}
514
515/// The receipt fields a landing reads, and nothing else.
516#[derive(Debug, Deserialize)]
517struct HeldReceipt {
518    schema: String,
519    version: String,
520    target: Utf8PathBuf,
521    profile: ProfileId,
522    root: Utf8PathBuf,
523    docs_scratch: Option<Utf8PathBuf>,
524    #[serde(default)]
525    reserve: Vec<String>,
526    writing_style: String,
527    #[serde(default)]
528    acquisition: Option<crate::domain::instance_config::Acquisition>,
529    #[serde(default)]
530    artifacts: Vec<HeldArtifact>,
531}
532
533/// Read the choices a stage recorded, for a landing that takes them.
534///
535/// The receipt is the one file of a stage a landing reads, and only for the
536/// choices it names: every byte the landing writes is rendered again from
537/// this binary's own sources. A receipt another release wrote describes a
538/// candidate this binary does not carry, and a receipt for another target
539/// describes a landing nobody asked for here, so both refuse.
540///
541/// SATISFIES staging:a-landing-takes-the-choices-its-stage-recorded
542///
543/// # Errors
544///
545/// [`AppError::Usage`] for a relative path, and [`AppError::Refused`] where
546/// the path holds no receipt this tool wrote, where another release wrote
547/// it, or where it names another target than `target`.
548pub fn read_choices(root: &Utf8Path, target: &Utf8Path) -> Result<StagedChoices, AppError> {
549    if !root.is_absolute() {
550        return Err(AppError::Usage(format!(
551            "the stage path must be absolute: {root}"
552        )));
553    }
554    let path = root.join(RECEIPT_FILE);
555    let text = std::fs::read_to_string(&path).map_err(|source| {
556        AppError::Refused(format!(
557            "{path} is not readable, so {root} is not a stage this tool wrote: {source}"
558        ))
559    })?;
560    let held: HeldReceipt = serde_json::from_str(&text).map_err(|source| {
561        AppError::Refused(format!(
562            "{path} is not a receipt this release reads: {source}"
563        ))
564    })?;
565    if held.schema != STAGE_SCHEMA {
566        return Err(AppError::Refused(format!(
567            "{path} does not declare {STAGE_SCHEMA}, so this is not a stage"
568        )));
569    }
570    if held.root != root {
571        return Err(AppError::Refused(format!(
572            "{path} declares the root {}, and this path is {root}",
573            held.root
574        )));
575    }
576    let current = crate::domain::version::CanonVersion::current().to_string();
577    if held.version != current {
578        return Err(AppError::Refused(format!(
579            "the stage at {root} was rendered by sdd {}, and this is sdd {current}; stage again with this binary",
580            held.version
581        )));
582    }
583    let target = crate::services::installer::resolved_target(target)?;
584    if held.target != target {
585        return Err(AppError::Refused(format!(
586            "the stage at {root} was rendered for {}, and this landing targets {target}",
587            held.target
588        )));
589    }
590    let writing_style = crate::domain::instance_config::WritingStyle::parse_flag(
591        &held.writing_style,
592    )
593    .map_err(|error| {
594        AppError::Refused(format!(
595            "{path} records a writing style this release refuses: {error}"
596        ))
597    })?;
598    Ok(StagedChoices {
599        target,
600        profile: held.profile,
601        docs_scratch: held.docs_scratch,
602        reserve: held.reserve,
603        writing_style,
604        acquisition: held.acquisition,
605        artifacts: held.artifacts,
606    })
607}
608
609/// Remove one stage this tool wrote, and refuse anything else.
610///
611/// # Errors
612///
613/// [`AppError::Usage`] for a relative path, and [`AppError::Refused`] for a
614/// path that is not a stage, a stage whose receipt names another root, a
615/// link, or a root this tool will not recurse into.
616pub fn clean(path: &Utf8Path) -> Result<Vec<String>, AppError> {
617    if !path.is_absolute() {
618        return Err(AppError::Usage(format!(
619            "the stage path must be absolute: {path}"
620        )));
621    }
622    // The final component is inspected without following it, so a link
623    // standing where a stage stood cannot redirect the removal.
624    let held = std::fs::symlink_metadata(path)
625        .map_err(|source| AppError::Refused(format!("{path}: {source}")))?;
626    if held.file_type().is_symlink() {
627        return Err(AppError::Refused(format!(
628            "{path} is a symlink; a stage is a directory this tool wrote"
629        )));
630    }
631    if !held.is_dir() {
632        return Err(AppError::Refused(format!("{path} is not a directory")));
633    }
634    if path.parent().is_none() || path.as_str().matches('/').count() < 2 {
635        return Err(AppError::Refused(format!(
636            "{path} is too close to the filesystem root to remove"
637        )));
638    }
639    if path.join(MANIFEST_PATH).exists() || path.join(".git").exists() {
640        return Err(AppError::Refused(format!(
641            "{path} looks like a project rather than a stage"
642        )));
643    }
644    // A receipt is ordinary user-writable JSON, so it proves nothing on
645    // its own. These refusals are what stand between a forged one and a
646    // recursive removal of somewhere that matters.
647    if let Some(home) = crate::domain::paths::UserEnv::from_process().home
648        && path == home
649    {
650        return Err(AppError::Refused(format!(
651            "{path} is the home directory, which is never a stage"
652        )));
653    }
654    if let Ok(cwd) = std::env::current_dir()
655        && let Ok(cwd) = Utf8PathBuf::from_path_buf(cwd)
656        && cwd.starts_with(path)
657    {
658        return Err(AppError::Refused(format!(
659            "{path} holds the working directory, so it is not a stage this tool wrote"
660        )));
661    }
662    // A stage this tool wrote holds the tree it renders. A directory that
663    // carries a receipt and none of that structure is something else
664    // wearing the name.
665    if !path.join(ARTIFACTS_DIR).is_dir() {
666        return Err(AppError::Refused(format!(
667            "{path} carries no {ARTIFACTS_DIR}/ directory, so it is not a stage this tool wrote"
668        )));
669    }
670
671    let receipt_path = path.join(RECEIPT_FILE);
672    let text = std::fs::read_to_string(&receipt_path).map_err(|source| {
673        AppError::Refused(format!(
674            "{receipt_path} is not readable, so this is not a stage this tool wrote: {source}"
675        ))
676    })?;
677    let receipt: serde_json::Value = serde_json::from_str(&text)
678        .map_err(|source| AppError::Refused(format!("{receipt_path} does not parse: {source}")))?;
679    if receipt.get("schema").and_then(serde_json::Value::as_str) != Some(STAGE_SCHEMA) {
680        return Err(AppError::Refused(format!(
681            "{receipt_path} does not declare {STAGE_SCHEMA}, so this is not a stage"
682        )));
683    }
684    let declared = receipt
685        .get("root")
686        .and_then(serde_json::Value::as_str)
687        .ok_or_else(|| AppError::Refused(format!("{receipt_path} declares no root")))?;
688    if declared != path.as_str() {
689        return Err(AppError::Refused(format!(
690            "{receipt_path} declares the root {declared}, and this path is {path}"
691        )));
692    }
693
694    // Move the validated directory aside under a name this run owns, then
695    // remove that. A directory swapped in after the checks is left where
696    // it is, because what this removes is the thing it just moved.
697    let aside = scratch_beside(path)?;
698    let _ = std::fs::remove_dir(&aside);
699    std::fs::rename(path, &aside)?;
700    if let Err(source) = std::fs::remove_dir_all(&aside) {
701        // Put it back under the name the operator knows, so a second try
702        // can find it. Where even that fails, name both paths: a stage
703        // nobody can address again is worse than the failure itself.
704        if std::fs::rename(&aside, path).is_err() {
705            return Err(AppError::Refused(format!(
706                "{path} could not be removed and is now at {aside}: {source}"
707            )));
708        }
709        return Err(AppError::Io(source));
710    }
711    Ok(vec![format!("removed {path}")])
712}
713
714#[cfg(test)]
715mod tests {
716    #![allow(
717        clippy::unwrap_used,
718        reason = "a test panics as its failure signal, not as control flow"
719    )]
720
721    use super::*;
722
723    fn root(dir: &tempfile::TempDir) -> Utf8PathBuf {
724        Utf8PathBuf::from(dir.path().to_str().unwrap())
725    }
726
727    #[test]
728    fn the_flag_wins_then_the_base_then_the_state_root() {
729        let target = Utf8Path::new("/work/project");
730        let state = Utf8Path::new("/state/spec-driven-docs");
731
732        let (path, source) = resolve_root(
733            target,
734            Some(Utf8Path::new("/tmp/here")),
735            Some("/base"),
736            state,
737        )
738        .unwrap();
739        assert_eq!(path, "/tmp/here");
740        assert_eq!(source, RootSource::Flag);
741
742        let (path, source) = resolve_root(target, None, Some("/base"), state).unwrap();
743        assert!(path.as_str().starts_with("/base/project-"), "{path}");
744        assert_eq!(source, RootSource::Environment);
745
746        let (path, source) = resolve_root(target, None, None, state).unwrap();
747        assert!(
748            path.as_str().starts_with(state.join("stages").as_str()),
749            "{path}"
750        );
751        assert_eq!(source, RootSource::Default);
752    }
753
754    #[test]
755    fn a_relative_stage_root_is_a_usage_error() {
756        let error = resolve_root(
757            Utf8Path::new("/work/project"),
758            Some(Utf8Path::new("stage")),
759            None,
760            Utf8Path::new("/state"),
761        )
762        .unwrap_err();
763        assert_eq!(error.kind(), "Usage");
764    }
765
766    #[test]
767    fn a_relative_step_in_the_stage_root_is_a_usage_error() {
768        // A path with a nonexistent prefix and a `..` resolves somewhere
769        // the containment check cannot see until the directory exists.
770        for (output, env) in [
771            (Some(Utf8Path::new("/work/project/absent/../inside")), None),
772            (None, Some("/tmp/absent/../../work")),
773        ] {
774            let error = resolve_root(
775                Utf8Path::new("/work/project"),
776                output,
777                env,
778                Utf8Path::new("/state"),
779            )
780            .unwrap_err();
781            assert_eq!(error.kind(), "Usage");
782            assert!(error.to_string().contains("relative step"), "{error}");
783        }
784    }
785
786    #[test]
787    fn two_targets_stage_under_different_names() {
788        assert_ne!(
789            stage_name(Utf8Path::new("/one/project")),
790            stage_name(Utf8Path::new("/two/project"))
791        );
792    }
793
794    #[test]
795    fn clean_refuses_a_directory_that_is_not_a_stage() {
796        let dir = tempfile::tempdir().unwrap();
797        let path = root(&dir).join("not-a-stage");
798        std::fs::create_dir_all(&path).unwrap();
799        let error = clean(&path).unwrap_err();
800        assert_eq!(error.kind(), "Refused");
801        assert!(path.exists(), "the directory was removed anyway");
802    }
803
804    #[test]
805    fn clean_refuses_a_receipt_that_names_another_root() {
806        let dir = tempfile::tempdir().unwrap();
807        let path = root(&dir).join("stage");
808        std::fs::create_dir_all(path.join(ARTIFACTS_DIR)).unwrap();
809        crate::adapters::fs::write_file(
810            &path.join(RECEIPT_FILE),
811            format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"/elsewhere"}}"#).as_bytes(),
812        )
813        .unwrap();
814        let error = clean(&path).unwrap_err();
815        assert!(error.to_string().contains("/elsewhere"), "{error}");
816        assert!(path.exists());
817    }
818
819    #[test]
820    fn clean_refuses_a_link_standing_where_a_stage_stood() {
821        let dir = tempfile::tempdir().unwrap();
822        let real = root(&dir).join("stage");
823        std::fs::create_dir_all(real.join(ARTIFACTS_DIR)).unwrap();
824        crate::adapters::fs::write_file(
825            &real.join(RECEIPT_FILE),
826            format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"{real}"}}"#).as_bytes(),
827        )
828        .unwrap();
829        let link = root(&dir).join("link");
830        std::os::unix::fs::symlink(real.as_std_path(), link.as_std_path()).unwrap();
831
832        let error = clean(&link).unwrap_err();
833        assert!(error.to_string().contains("symlink"), "{error}");
834        assert!(real.exists(), "the link's target was removed");
835    }
836
837    #[test]
838    fn clean_refuses_a_project_root() {
839        let dir = tempfile::tempdir().unwrap();
840        let path = root(&dir).join("project");
841        crate::adapters::fs::write_file(&path.join(MANIFEST_PATH), b"{}").unwrap();
842        crate::adapters::fs::write_file(
843            &path.join(RECEIPT_FILE),
844            format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"{path}"}}"#).as_bytes(),
845        )
846        .unwrap();
847        let error = clean(&path).unwrap_err();
848        assert!(error.to_string().contains("project"), "{error}");
849        assert!(path.exists());
850    }
851
852    #[test]
853    fn clean_refuses_a_forged_receipt_over_a_directory_that_is_not_a_stage() {
854        let dir = tempfile::tempdir().unwrap();
855        // Somebody's directory of work, with a receipt dropped in it that
856        // names the directory as its own root.
857        let path = root(&dir).join("someones-files");
858        crate::adapters::fs::write_file(&path.join("notes.md"), b"mine").unwrap();
859        crate::adapters::fs::write_file(
860            &path.join(RECEIPT_FILE),
861            format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"{path}"}}"#).as_bytes(),
862        )
863        .unwrap();
864
865        let error = clean(&path).unwrap_err();
866        assert!(error.to_string().contains(ARTIFACTS_DIR), "{error}");
867        assert!(path.join("notes.md").exists(), "the directory was removed");
868    }
869
870    #[test]
871    fn clean_refuses_a_directory_holding_the_working_directory() {
872        let dir = tempfile::tempdir().unwrap();
873        let path = Utf8PathBuf::from_path_buf(std::env::current_dir().unwrap())
874            .unwrap()
875            .parent()
876            .unwrap()
877            .to_owned();
878        let _ = dir;
879        let error = clean(&path).unwrap_err();
880        assert_eq!(error.kind(), "Refused");
881        assert!(path.exists());
882    }
883
884    #[test]
885    fn clean_removes_one_valid_stage() {
886        let dir = tempfile::tempdir().unwrap();
887        let path = root(&dir).join("stage");
888        crate::adapters::fs::write_file(&path.join(ARTIFACTS_DIR).join("AGENTS.md"), b"x").unwrap();
889        crate::adapters::fs::write_file(
890            &path.join(RECEIPT_FILE),
891            format!(r#"{{"schema":"{STAGE_SCHEMA}","root":"{path}"}}"#).as_bytes(),
892        )
893        .unwrap();
894        assert_eq!(clean(&path).unwrap().len(), 1);
895        assert!(!path.exists());
896    }
897}