Skip to main content

spec_driven_docs/services/
upgrader.rs

1//! Binary-driven instance upgrade.
2//!
3//! The newer binary carries the newer payload, so an upgrade is mechanical:
4//! refuse atomically while any managed file is locally edited, reinstall
5//! from the embedded payload, prune what the new version stopped managing —
6//! inside the vendored directory only, and never through a symlink — and
7//! report the rule-ID diff the operator reconciles by hand. Copier's model;
8//! what changed between versions is the changelog's business.
9
10use camino::{Utf8Path, Utf8PathBuf};
11use serde::Serialize;
12
13use crate::adapters::fs::sha256_file;
14use crate::domain::manifest::{LegacyManifest, MANIFEST_PATH, Manifest, ManifestParseError};
15use crate::domain::ownership::Sha256;
16use crate::domain::profile::ProfileId;
17use crate::domain::version::CanonVersion;
18use crate::error::AppError;
19use crate::services::installer::{InitOptions, init, init_holding};
20
21/// What an upgrade was asked to do.
22#[derive(Debug, Clone)]
23pub struct UpgradeOptions {
24    /// The absolute target instance.
25    pub target: Utf8PathBuf,
26    /// Report what would change and change nothing.
27    pub dry_run: bool,
28    /// The choices a stage recorded, where the landing takes them.
29    pub staged: Option<crate::stage::StagedChoices>,
30    /// The conflicts the operator named for replacement, as the record
31    /// names each destination.
32    pub replace: Vec<String>,
33}
34
35/// What kind of conflict one destination is.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
37#[serde(rename_all = "kebab-case")]
38pub enum ConflictKind {
39    /// A managed file whose bytes are not the recorded ones.
40    EditedManagedFile,
41    /// A managed file the record names and the target lacks.
42    MissingManagedFile,
43    /// A managed region whose bytes are not the recorded ones.
44    EditedManagedBlock,
45    /// The file a recorded managed region lives in is gone.
46    MissingIntegrationHost,
47    /// A destination the candidate lands that holds bytes no record
48    /// vouches for.
49    Unattributed,
50}
51
52/// One destination the upgrade cannot overwrite unasked.
53#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
54pub struct Conflict {
55    /// The destination, relative to the target.
56    pub path: String,
57    /// What kind of conflict it is.
58    pub kind: ConflictKind,
59}
60
61impl Conflict {
62    /// The line the text report prints.
63    fn line(&self) -> String {
64        let what = match self.kind {
65            ConflictKind::EditedManagedFile => "locally edited managed file",
66            ConflictKind::MissingManagedFile => "missing managed file",
67            ConflictKind::EditedManagedBlock => "locally edited managed block",
68            ConflictKind::MissingIntegrationHost => "missing integration host",
69            ConflictKind::Unattributed => "destination holds bytes no record vouches for",
70        };
71        format!("CONFLICT {what}: {}", self.path)
72    }
73}
74
75/// One named conflict, and where its bytes were saved before the landing.
76#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
77pub struct Replaced {
78    /// The destination, relative to the target.
79    pub path: String,
80    /// Where its bytes are kept, or nothing where the target held none.
81    pub saved_to: Option<Utf8PathBuf>,
82}
83
84/// One citation of a rule ID this binary no longer defines.
85#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
86pub struct Citation {
87    /// The citing file, relative to the target.
88    pub path: Utf8PathBuf,
89    /// The one-based line the citation sits on.
90    pub line: usize,
91    /// The rule ID cited.
92    pub id: String,
93}
94
95/// What an upgrade did.
96#[derive(Debug, Default)]
97pub struct UpgradeOutcome {
98    /// Every line to print, in order.
99    pub lines: Vec<String>,
100    /// How many lines are conflicts or failures.
101    pub failures: usize,
102    /// The release the record names, where one was read.
103    pub from: Option<CanonVersion>,
104    /// Every conflict the target holds, named or not.
105    pub conflicts: Vec<Conflict>,
106    /// Every named conflict and where its bytes went.
107    pub replaced: Vec<Replaced>,
108    /// Every citation of a rule ID this binary no longer defines.
109    pub retired_citations: Vec<Citation>,
110}
111
112struct Installed {
113    version: CanonVersion,
114    profile: ProfileId,
115    docs_root: String,
116    managed: Vec<(Utf8PathBuf, Sha256)>,
117    integration: Vec<(Utf8PathBuf, Sha256)>,
118    /// Whether the record is already at this binary's schema.
119    ///
120    /// The two versions move independently, so an instance can carry this
121    /// binary's canon version and an older schema. Without this the "already
122    /// at" shortcut would return before migrating, while every other verb
123    /// refuses the record and sends the operator back here.
124    schema_current: bool,
125}
126
127/// The marker pair a host file's managed region uses.
128fn markers_for(path: &str) -> (&'static str, &'static str) {
129    use crate::domain::marker::{AGENTS_BEGIN, AGENTS_END, BEGIN, END};
130    if path == crate::domain::paths::HOOKS_CONFIG_PATH {
131        (BEGIN, END)
132    } else {
133        (AGENTS_BEGIN, AGENTS_END)
134    }
135}
136
137fn read_installed(target: &Utf8Path) -> Result<Installed, AppError> {
138    let path = target.join(MANIFEST_PATH);
139    if !path.is_file() {
140        return Err(AppError::ManifestMissing(path));
141    }
142    let text = std::fs::read_to_string(&path)?;
143    match Manifest::parse(&text) {
144        Ok(manifest) => Ok(Installed {
145            version: manifest.canon_version,
146            profile: manifest.profile,
147            docs_root: manifest.docs_root.as_str().to_string(),
148            managed: manifest
149                .managed_files
150                .into_iter()
151                .map(|entry| (entry.destination, entry.sha256))
152                .collect(),
153            integration: manifest
154                .integration_blocks
155                .into_iter()
156                .map(|block| (block.path, block.marker_hash))
157                .collect(),
158            schema_current: true,
159        }),
160        Err(ManifestParseError::Older(_)) => {
161            let legacy: LegacyManifest = serde_json::from_str(&text)
162                .map_err(|e| AppError::ManifestInvalid(e.to_string()))?;
163            Ok(Installed {
164                version: legacy.canon_version,
165                profile: legacy.profile,
166                docs_root: legacy.docs_root.as_str().to_string(),
167                managed: legacy
168                    .managed_files
169                    .into_iter()
170                    .map(|entry| (entry.destination, entry.sha256))
171                    .collect(),
172                integration: legacy
173                    .integration_blocks
174                    .into_iter()
175                    .map(|block| (block.path, block.marker_hash))
176                    .collect(),
177                schema_current: false,
178            })
179        }
180        Err(error) => Err(AppError::ManifestInvalid(error.to_string())),
181    }
182}
183
184/// Refuse an answer on a path where no plan offers a decision.
185///
186/// A target with nothing to do and one whose managed files were edited
187/// both end before a plan exists. An answer given on either is an answer
188/// to a question nobody asked, and letting it pass silently would make
189/// typing look like consent on the one path where nothing checked it.
190/// A downgrade refuses on its own terms before this can matter.
191///
192/// # Errors
193///
194/// [`AppError::Usage`] naming the decision nothing offered.
195/// Every managed file and region the target no longer holds as recorded.
196///
197/// A reinstall replaces a managed file and re-splices a managed region, so
198/// an edit to either would be lost. An edit outside the markers is the
199/// project's own and survives, which is why the region is compared by its
200/// own hash rather than the host file's.
201///
202/// # Errors
203///
204/// Any I/O error reading a destination.
205fn conflicts_at(target: &Utf8Path, installed: &Installed) -> Result<Vec<Conflict>, AppError> {
206    let mut conflicts = Vec::new();
207    let mut push = |path: &Utf8Path, kind| {
208        conflicts.push(Conflict {
209            path: path.to_string(),
210            kind,
211        });
212    };
213    for (destination, recorded) in &installed.managed {
214        let file = target.join(destination);
215        if !file.is_file() {
216            push(destination, ConflictKind::MissingManagedFile);
217            continue;
218        }
219        if sha256_file(&file)? != *recorded {
220            push(destination, ConflictKind::EditedManagedFile);
221        }
222    }
223    for (path, recorded) in &installed.integration {
224        let full = target.join(path);
225        if !full.is_file() {
226            push(path, ConflictKind::MissingIntegrationHost);
227            continue;
228        }
229        let (begin, end) = markers_for(path.as_str());
230        let host = std::fs::read_to_string(&full)?;
231        match crate::domain::marker::block_hash_with(&host, begin, end) {
232            Some(present) if present == *recorded => {}
233            _ => push(path, ConflictKind::EditedManagedBlock),
234        }
235    }
236    Ok(conflicts)
237}
238
239/// Every destination the candidate lands that the landing would refuse,
240/// beyond what the record already names.
241fn unattributed(
242    target: &Utf8Path,
243    candidate: &crate::candidate::Candidate,
244    known: &[Conflict],
245) -> Vec<Conflict> {
246    let recorded = crate::services::installer::recorded(target);
247    let mut found = Vec::new();
248    for destination in &candidate.destinations {
249        let Ok(held) = std::fs::read(target.join(&destination.path)) else {
250            continue;
251        };
252        if held == destination.bytes
253            || crate::landing::apply::vouches(
254                &recorded,
255                &destination.path,
256                destination.ownership,
257                &held,
258            )
259            || known
260                .iter()
261                .any(|conflict| conflict.path == destination.path.as_str())
262        {
263            continue;
264        }
265        found.push(Conflict {
266            path: destination.path.to_string(),
267            kind: ConflictKind::Unattributed,
268        });
269    }
270    found
271}
272
273/// The options a reinstall carries.
274///
275/// No flag: the reinstall carries the recorded declarations forward, and
276/// the project's own declaration file is adopted, so the reinstall reads
277/// it rather than replacing it.
278fn reinstall_options(
279    target: &Utf8Path,
280    profile: ProfileId,
281    options: &UpgradeOptions,
282) -> InitOptions {
283    let staged = options.staged.as_ref();
284    InitOptions {
285        target: target.to_path_buf(),
286        profile,
287        apply: false,
288        dry_run: true,
289        docs_scratch: staged.map(|choices| choices.docs_scratch.clone()),
290        reserve: staged
291            .map(|choices| choices.reserve.clone())
292            .unwrap_or_default(),
293        writing_style: staged.map(|choices| choices.writing_style.clone()),
294        acquisition: staged.and_then(|choices| choices.acquisition.clone()),
295        replace: options.replace.clone(),
296    }
297}
298
299/// Report what the landing took back.
300///
301/// The removals are the landing's own, taken only where the record
302/// vouched for the bytes it removed. This only says what happened.
303fn report_removals(removed: &[String], outcome: &mut UpgradeOutcome) {
304    for raw in removed {
305        outcome
306            .lines
307            .push(format!("removed managed file no longer owned: {raw}"));
308    }
309}
310
311/// Upgrade an installed instance to this binary's version.
312///
313/// # Errors
314///
315/// [`AppError::Violations`] when conflicts block the upgrade or removals
316/// remain unfinished, [`AppError::Refused`] when the binary is older than
317/// the instance or the reinstall refuses, and manifest errors when the
318/// record cannot be read.
319pub fn upgrade(options: &UpgradeOptions) -> Result<UpgradeOutcome, AppError> {
320    if !options.target.is_absolute() {
321        return Err(AppError::Usage("target must be absolute".to_string()));
322    }
323    if !options.target.is_dir() {
324        return Err(AppError::Usage(format!(
325            "unresolved target: {}",
326            options.target
327        )));
328    }
329    let target = Utf8PathBuf::from_path_buf(std::fs::canonicalize(&options.target)?)
330        .map_err(|p| AppError::Usage(format!("target is not UTF-8: {}", p.display())))?;
331
332    // An apply holds the target for the whole run, the observation below
333    // included. Without it, a second run could read the tree another
334    // landing is halfway through and report that as drift rather than
335    // naming the holder.
336    let held = if options.dry_run {
337        None
338    } else {
339        Some(crate::landing::lock::hold(&target)?)
340    };
341
342    let installed = read_installed(&target)?;
343    // The version landed is the version running. The operator chose which
344    // binary to install, and that binary projects only itself.
345    let new = CanonVersion::current();
346    let old = installed.version;
347    let mut outcome = UpgradeOutcome::default();
348
349    if old > new {
350        return Err(AppError::Refused(format!(
351            "sdd {new} is older than the installed canon {old}; upgrade sdd"
352        )));
353    }
354
355    if let Some(staged) = options.staged.as_ref()
356        && staged.profile != installed.profile
357    {
358        return Err(AppError::Refused(format!(
359            "the stage projects the {} profile and {target} records {}; moving a profile is a migration to ask for deliberately",
360            staged.profile, installed.profile
361        )));
362    }
363    outcome.from = Some(old);
364    let reinstall = reinstall_options(&target, installed.profile, options);
365    outcome.retired_citations = retired_citations(&target, &installed);
366
367    // The conflict scan comes before the version shortcut. A managed file
368    // edited in a current instance is exactly the drift this verb serves,
369    // and a shortcut that reported success first would leave the one route
370    // to it unable to do its job.
371    let conflicts = scan(&target, &installed, &reinstall, &options.replace)?;
372    outcome.conflicts.clone_from(&conflicts);
373    let unnamed: Vec<&Conflict> = conflicts
374        .iter()
375        .filter(|conflict| !options.replace.contains(&conflict.path))
376        .collect();
377    if !unnamed.is_empty() {
378        outcome.failures += unnamed.len();
379        outcome
380            .lines
381            .extend(unnamed.iter().map(|conflict| conflict.line()));
382        report_citations(&mut outcome);
383        return Ok(outcome);
384    }
385
386    if old == new
387        && installed.schema_current
388        && options.replace.is_empty()
389        && options.staged.is_none()
390    {
391        outcome.lines.push(format!("OK already at {new}"));
392        report_citations(&mut outcome);
393        return Ok(outcome);
394    }
395
396    let save_root = save_root(&target, &options.replace, !options.dry_run)?;
397    if options.dry_run {
398        preview(
399            &target,
400            options,
401            &reinstall,
402            save_root.as_deref(),
403            &mut outcome,
404        )?;
405        report_citations(&mut outcome);
406        return Ok(outcome);
407    }
408
409    // Every named conflict's bytes are kept before the first write, so the
410    // answer "discard" and the answer "keep" lose nothing either way.
411    keep_named(
412        &target,
413        &options.replace,
414        save_root.as_deref(),
415        &mut outcome,
416    )?;
417
418    let reinstalled = init_holding(
419        held,
420        &InitOptions {
421            apply: true,
422            dry_run: false,
423            ..reinstall
424        },
425        // The upgrade already classified the target; the reinstall is its
426        // own act rather than a second landing decision.
427        crate::landing::classify::Intent::Reconcile,
428    )
429    .map_err(|error| {
430        AppError::Refused(format!(
431            "upgrade aborted during reinstall from {old} to {new}: {error}"
432        ))
433    })?;
434    // The reinstall's destination list is noise here, and its notes are
435    // not: a seed that did not land because the project already holds the
436    // destination is something the operator must hear about once.
437    let removed = reinstalled.removed.clone();
438    outcome.lines.extend(
439        reinstalled
440            .lines
441            .into_iter()
442            .filter(|line| line.starts_with("note:")),
443    );
444
445    finish(&target, &installed, &removed, old, new, &mut outcome);
446    Ok(outcome)
447}
448
449/// Every conflict the target holds, and a refusal for a name that is none.
450///
451/// The record's own conflicts come first, then every destination the
452/// candidate lands that holds bytes no record vouches for, because the
453/// landing would refuse those too.
454fn scan(
455    target: &Utf8Path,
456    installed: &Installed,
457    reinstall: &InitOptions,
458    named: &[String],
459) -> Result<Vec<Conflict>, AppError> {
460    let (conflicts, candidate) = conflicts_with_candidate(target, installed, reinstall)?;
461    // A name is an answer to a question the scan asked. One that names no
462    // conflict answers nothing, and taking it would make typing look like
463    // consent to overwrite a file nobody looked at. One the landing would
464    // refuse resolves nothing either, so it is refused here, before a copy
465    // is saved, rather than by the landing after.
466    for name in named {
467        if !conflicts.iter().any(|conflict| &conflict.path == name) {
468            return Err(AppError::Usage(format!(
469                "--replace {name} names no conflict; the conflicts are the destinations this run lists"
470            )));
471        }
472        if let Some((component, kind)) =
473            crate::landing::apply::refuses_named(target, &candidate, name)
474        {
475            return Err(AppError::Refused(format!(
476                "--replace {name} names a destination the landing cannot write: {component} {kind}; move it aside, then run this again"
477            )));
478        }
479    }
480    Ok(conflicts)
481}
482
483/// Every conflict the target holds, with the candidate that judged them.
484fn conflicts_with_candidate(
485    target: &Utf8Path,
486    installed: &Installed,
487    reinstall: &InitOptions,
488) -> Result<(Vec<Conflict>, crate::candidate::Candidate), AppError> {
489    let mut conflicts = conflicts_at(target, installed)?;
490    let candidate =
491        crate::services::installer::candidate_for(target, reinstall).map_err(|error| {
492            AppError::Refused(format!(
493                "upgrade could not render the candidate for {target}: {error}"
494            ))
495        })?;
496    let unattributed = unattributed(target, &candidate, &conflicts);
497    conflicts.extend(unattributed);
498    Ok((conflicts, candidate))
499}
500
501/// The destinations `sdd upgrade --replace` accepts after the stage that
502/// recorded `staged`, by the check that verb applies to each name.
503///
504/// Empty where no instance is recorded, because `sdd init` takes no name,
505/// and wherever the upgrade refuses before it scans: the front gate that
506/// classifies the target, an instance newer than this binary, or a stage
507/// of another profile.
508///
509/// # Errors
510///
511/// Whatever rendering the candidate refuses.
512pub(crate) fn replaceable(staged: &crate::stage::StagedChoices) -> Result<Vec<String>, AppError> {
513    let target = &staged.target;
514    if crate::commands::front::serves(crate::landing::classify::Intent::Upgrade, target).is_err() {
515        return Ok(Vec::new());
516    }
517    let Ok(installed) = read_installed(target) else {
518        return Ok(Vec::new());
519    };
520    if installed.version > CanonVersion::current() || staged.profile != installed.profile {
521        return Ok(Vec::new());
522    }
523    let options = UpgradeOptions {
524        target: target.clone(),
525        dry_run: true,
526        staged: Some(staged.clone()),
527        replace: Vec::new(),
528    };
529    let reinstall = reinstall_options(target, installed.profile, &options);
530    let (conflicts, candidate) = conflicts_with_candidate(target, &installed, &reinstall)?;
531    Ok(conflicts
532        .into_iter()
533        .filter(|conflict| {
534            crate::landing::apply::refuses_named(target, &candidate, &conflict.path).is_none()
535        })
536        .map(|conflict| conflict.path)
537        .collect())
538}
539
540/// What a dry run reports: the move, each named conflict and where its
541/// bytes would go, and the notes the landing would print.
542fn preview(
543    target: &Utf8Path,
544    options: &UpgradeOptions,
545    reinstall: &InitOptions,
546    save_root: Option<&Utf8Path>,
547    outcome: &mut UpgradeOutcome,
548) -> Result<(), AppError> {
549    let new = CanonVersion::current();
550    let old = outcome.from.unwrap_or(new);
551    // At the same canon version the work is the record's schema alone, or
552    // the repair of what the operator named, so saying "upgrade X to X"
553    // would describe nothing.
554    if old != new {
555        outcome
556            .lines
557            .push(format!("DRY RUN upgrade {old} to {new}"));
558    } else if options.replace.is_empty() {
559        outcome
560            .lines
561            .push(format!("DRY RUN migrate the record of {new}"));
562    } else {
563        outcome.lines.push(format!("DRY RUN repair {new}"));
564    }
565    for named in &options.replace {
566        let saved_to = target
567            .join(named)
568            .is_file()
569            .then(|| save_root.map(|root| root.join(named)))
570            .flatten();
571        outcome.lines.push(saved_to.as_ref().map_or_else(
572            || format!("DRY RUN write {named}, which the target lacks"),
573            |saved| format!("DRY RUN save {named} to {saved}, then replace it"),
574        ));
575        outcome.replaced.push(Replaced {
576            path: named.clone(),
577            saved_to,
578        });
579    }
580    // A seed the landing will not write, and a file it cannot account for,
581    // are what a dry run exists to show.
582    let preview =
583        init(reinstall, crate::landing::classify::Intent::Reconcile).map_err(|error| {
584            AppError::Refused(format!(
585                "upgrade could not be previewed from {old} to {new}: {error}"
586            ))
587        })?;
588    outcome.lines.extend(
589        preview
590            .lines
591            .into_iter()
592            .filter(|line| line.starts_with("note:")),
593    );
594    Ok(())
595}
596
597/// Print every retired citation, one line each.
598fn report_citations(outcome: &mut UpgradeOutcome) {
599    for citation in &outcome.retired_citations {
600        outcome.lines.push(format!(
601            "retired rule ID cited: {}:{} `{}`; re-point it to the rule the changelog names",
602            citation.path, citation.line, citation.id
603        ));
604    }
605}
606
607/// Where the bytes of a replaced destination are kept.
608///
609/// Under the docs scratch the instance declares, or that its variable
610/// names, in `replaced/`. Where neither names one, under this tool's state
611/// root, in a directory of this run's own. Never inside a stage, so
612/// cleaning a stage never deletes a saved copy.
613///
614/// SATISFIES staging:a-replacement-keeps-the-bytes-it-replaces
615///
616/// A run that writes claims its state-root directory exclusively, so two
617/// runs in one second never share one; a preview only names where it would.
618fn save_root(
619    target: &Utf8Path,
620    named: &[String],
621    claim: bool,
622) -> Result<Option<Utf8PathBuf>, AppError> {
623    if named.is_empty() {
624        return Ok(None);
625    }
626    let env = crate::domain::paths::UserEnv::from_process();
627    let recorded = crate::services::installer::recorded_field(target, "docs_scratch")
628        .and_then(|value| value.as_str().map(Utf8PathBuf::from))
629        .filter(|path| !path.as_str().is_empty());
630    let scratch = env.docs_scratch.clone().map(Utf8PathBuf::from).or(recorded);
631    if let Some(scratch) = scratch {
632        return Ok(Some(target.join(scratch).join("replaced")));
633    }
634    let Some(state) = env.state_root() else {
635        return Ok(None);
636    };
637    let runs = state
638        .path
639        .join("snapshots")
640        .join(crate::stage::stage_name(target));
641    let stamp = jiff::Timestamp::now()
642        .strftime("%Y%m%dT%H%M%SZ")
643        .to_string();
644    let run = if claim {
645        crate::adapters::fs::claim_run_dir(&runs, &stamp)?
646    } else {
647        runs.join(stamp)
648    };
649    Ok(Some(run.join("replaced")))
650}
651
652/// Keep every named destination's bytes, and report where each went.
653fn keep_named(
654    target: &Utf8Path,
655    named: &[String],
656    root: Option<&Utf8Path>,
657    outcome: &mut UpgradeOutcome,
658) -> Result<(), AppError> {
659    for name in named {
660        let saved_to = save(target, name, root)?;
661        if let Some(saved) = &saved_to {
662            outcome.lines.push(format!("saved {name} to {saved}"));
663        }
664        outcome.replaced.push(Replaced {
665            path: name.clone(),
666            saved_to,
667        });
668    }
669    Ok(())
670}
671
672/// Keep one destination's bytes before it is replaced.
673///
674/// A copy already there with other bytes is somebody's earlier answer, and
675/// writing over it would lose the bytes this step exists to keep.
676fn save(
677    target: &Utf8Path,
678    named: &str,
679    root: Option<&Utf8Path>,
680) -> Result<Option<Utf8PathBuf>, AppError> {
681    let held = match std::fs::read(target.join(named)) {
682        Ok(held) => held,
683        Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(None),
684        Err(source) => return Err(AppError::Io(source)),
685    };
686    let Some(root) = root else {
687        return Err(AppError::Refused(format!(
688            "no docs scratch and no state root resolve, so the bytes of {named} have nowhere to be kept; set XDG_STATE_HOME or declare a docs scratch"
689        )));
690    };
691    let saved = root.join(named);
692    match std::fs::read(&saved) {
693        Ok(existing) if existing == held => return Ok(Some(saved)),
694        Ok(_) => {
695            return Err(AppError::Refused(format!(
696                "{saved} already keeps other bytes of {named}; move it aside, then run this again"
697            )));
698        }
699        Err(_) => {}
700    }
701    crate::adapters::fs::write_file(&saved, &held)?;
702    Ok(Some(saved))
703}
704
705/// Every citation of a rule ID this binary no longer defines.
706///
707/// A citation is an inline-code token in a domain this binary defines
708/// rules in, naming a rule it does not define. A rule heading is a
709/// definition rather than a citation, a decision record is judged on its
710/// `Enforced by` line alone, because its prose may describe a retirement,
711/// and a file this tool manages is about to be replaced, so none of those
712/// is listed. The changelog is history and is never re-pointed, and a
713/// token this binary's own specs carry is an example it ships.
714///
715/// SATISFIES staging:an-upgrade-lists-every-retired-citation-first
716fn retired_citations(target: &Utf8Path, installed: &Installed) -> Vec<Citation> {
717    let defined = crate::embedded::spec_rule_ids();
718    let domains: std::collections::BTreeSet<&str> = defined
719        .iter()
720        .filter_map(|id| id.split_once(':').map(|(domain, _)| domain))
721        .collect();
722    // A token this binary's own specs carry is an example it ships, such as
723    // a scenario showing a dead citation, never a retirement it caused.
724    let shipped: std::collections::BTreeSet<String> = crate::embedded::spec_texts()
725        .flat_map(|text| {
726            text.lines()
727                .flat_map(crate::gates::adr_cites_a_live_rule::cited_ids)
728                .map(String::from)
729                .collect::<Vec<_>>()
730        })
731        .collect();
732    let managed: Vec<&Utf8PathBuf> = installed.managed.iter().map(|(path, _)| path).collect();
733    let decisions = Utf8Path::new(&installed.docs_root).join("decisions");
734    let mut found = Vec::new();
735    let walker = walkdir::WalkDir::new(target)
736        .sort_by_file_name()
737        .into_iter()
738        .filter_entry(|entry| {
739            let name = entry.file_name().to_string_lossy();
740            !(entry.depth() > 0
741                && entry.file_type().is_dir()
742                && (crate::gates::PRUNED_DIRS.contains(&name.as_ref())
743                    || name == crate::domain::paths::INSTANCE_DIR
744                    || crate::domain::paths::DOCS_SCRATCH_LEAVES.contains(&name.as_ref())))
745        });
746    for entry in walker.filter_map(Result::ok) {
747        if !entry.file_type().is_file() {
748            continue;
749        }
750        let Some(path) = entry.path().to_str() else {
751            continue;
752        };
753        let Ok(relative) = Utf8Path::new(path).strip_prefix(target) else {
754            continue;
755        };
756        if relative.extension() != Some("md")
757            || relative == "CHANGELOG.md"
758            || managed.iter().any(|held| *held == relative)
759        {
760            continue;
761        }
762        let Ok(text) = std::fs::read_to_string(entry.path()) else {
763            continue;
764        };
765        let record = relative.starts_with(&decisions);
766        for (index, line) in text.lines().enumerate() {
767            if line.starts_with("### `") || (record && !line.starts_with("Enforced by ")) {
768                continue;
769            }
770            for id in crate::gates::adr_cites_a_live_rule::cited_ids(line) {
771                let domain = id.split_once(':').map_or(id, |(domain, _)| domain);
772                if domains.contains(domain) && !defined.contains(id) && !shipped.contains(id) {
773                    found.push(Citation {
774                        path: relative.to_owned(),
775                        line: index + 1,
776                        id: id.to_string(),
777                    });
778                }
779            }
780        }
781    }
782    found
783}
784
785fn finish(
786    target: &Utf8Path,
787    installed: &Installed,
788    removed: &[String],
789    old: CanonVersion,
790    new: CanonVersion,
791    outcome: &mut UpgradeOutcome,
792) {
793    report_removals(removed, outcome);
794
795    let mut local_ids = std::collections::BTreeSet::new();
796    let specs = target.join(&installed.docs_root).join("specs");
797    if let Ok(entries) = specs.read_dir_utf8() {
798        for entry in entries.filter_map(Result::ok) {
799            if let Ok(text) = std::fs::read_to_string(entry.path()) {
800                local_ids.extend(crate::embedded::rule_ids_in(&text));
801            }
802        }
803    }
804    let upstream_only: Vec<String> = crate::embedded::spec_rule_ids()
805        .difference(&local_ids)
806        .cloned()
807        .collect();
808    if !upstream_only.is_empty() {
809        outcome
810            .lines
811            .push("upstream rule IDs not present locally:".to_string());
812        for id in upstream_only {
813            outcome.lines.push(format!("  {id}"));
814        }
815    }
816
817    if outcome.failures > 0 {
818        outcome.lines.push(format!(
819            "FAIL upgraded {old} to {new} with unfinished removals above"
820        ));
821    } else if old == new {
822        outcome
823            .lines
824            .push(format!("OK migrated the record of {new}"));
825    } else {
826        outcome.lines.push(format!("OK upgraded {old} to {new}"));
827    }
828}
829
830#[cfg(test)]
831mod tests {
832    use super::*;
833
834    /// SATISFIES staging:a-replacement-keeps-the-bytes-it-replaces
835    #[test]
836    fn two_saves_in_one_second_keep_both_copies() {
837        let dir = tempfile::tempdir().unwrap();
838        let root = Utf8Path::from_path(dir.path()).unwrap();
839        let target = root.join("target");
840        let runs = root.join("snapshots");
841        let stamp = "20261009T213000Z";
842
843        crate::adapters::fs::write_file(&target.join("AGENTS.md"), b"first").unwrap();
844        let first = crate::adapters::fs::claim_run_dir(&runs, stamp).unwrap();
845        let kept = save(&target, "AGENTS.md", Some(&first)).unwrap().unwrap();
846
847        crate::adapters::fs::write_file(&target.join("AGENTS.md"), b"second").unwrap();
848        let second = crate::adapters::fs::claim_run_dir(&runs, stamp).unwrap();
849        let again = save(&target, "AGENTS.md", Some(&second)).unwrap().unwrap();
850
851        assert_ne!(kept, again);
852        assert_eq!(std::fs::read(&kept).unwrap(), b"first");
853        assert_eq!(std::fs::read(&again).unwrap(), b"second");
854    }
855}