1use 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#[derive(Debug, Clone)]
23pub struct UpgradeOptions {
24 pub target: Utf8PathBuf,
26 pub dry_run: bool,
28 pub staged: Option<crate::stage::StagedChoices>,
30 pub replace: Vec<String>,
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
37#[serde(rename_all = "kebab-case")]
38pub enum ConflictKind {
39 EditedManagedFile,
41 MissingManagedFile,
43 EditedManagedBlock,
45 MissingIntegrationHost,
47 Unattributed,
50 UnattributedSkillPackage,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
57pub struct Conflict {
58 pub path: String,
60 pub kind: ConflictKind,
62}
63
64impl Conflict {
65 fn line(&self) -> String {
67 let what = match self.kind {
68 ConflictKind::EditedManagedFile => "locally edited managed file",
69 ConflictKind::MissingManagedFile => "missing managed file",
70 ConflictKind::EditedManagedBlock => "locally edited managed block",
71 ConflictKind::MissingIntegrationHost => "missing integration host",
72 ConflictKind::Unattributed => "destination holds bytes no record vouches for",
73 ConflictKind::UnattributedSkillPackage => {
74 return format!(
75 "CONFLICT {}",
76 crate::landing::apply::refused_package_line(&self.path)
77 );
78 }
79 };
80 format!("CONFLICT {what}: {}", self.path)
81 }
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
86pub struct Replaced {
87 pub path: String,
89 pub saved_to: Option<Utf8PathBuf>,
91}
92
93#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
95pub struct Citation {
96 pub path: Utf8PathBuf,
98 pub line: usize,
100 pub id: String,
102}
103
104#[derive(Debug, Default)]
106pub struct UpgradeOutcome {
107 pub lines: Vec<String>,
109 pub failures: usize,
111 pub from: Option<CanonVersion>,
113 pub conflicts: Vec<Conflict>,
115 pub replaced: Vec<Replaced>,
117 pub retired_citations: Vec<Citation>,
119 pub next: Option<&'static str>,
122}
123
124struct Installed {
125 version: CanonVersion,
126 profile: ProfileId,
127 docs_root: String,
128 managed: Vec<(Utf8PathBuf, Sha256)>,
129 integration: Vec<(Utf8PathBuf, Sha256)>,
130 schema_current: bool,
137}
138
139fn markers_for(path: &str) -> (&'static str, &'static str) {
141 use crate::domain::marker::{AGENTS_BEGIN, AGENTS_END, BEGIN, END};
142 if path == crate::domain::paths::HOOKS_CONFIG_PATH {
143 (BEGIN, END)
144 } else {
145 (AGENTS_BEGIN, AGENTS_END)
146 }
147}
148
149fn read_installed(target: &Utf8Path) -> Result<Installed, AppError> {
150 let path = target.join(MANIFEST_PATH);
151 if !path.is_file() {
152 return Err(AppError::ManifestMissing(path));
153 }
154 let text = std::fs::read_to_string(&path)?;
155 match Manifest::parse(&text) {
156 Ok(manifest) => Ok(Installed {
157 version: manifest.canon_version,
158 profile: manifest.profile,
159 docs_root: manifest.docs_root.as_str().to_string(),
160 managed: manifest
161 .managed_files
162 .into_iter()
163 .map(|entry| (entry.destination, entry.sha256))
164 .collect(),
165 integration: manifest
166 .integration_blocks
167 .into_iter()
168 .map(|block| (block.path, block.marker_hash))
169 .collect(),
170 schema_current: true,
171 }),
172 Err(ManifestParseError::Older(_)) => {
173 let legacy: LegacyManifest = serde_json::from_str(&text)
174 .map_err(|e| AppError::ManifestInvalid(e.to_string()))?;
175 Ok(Installed {
176 version: legacy.canon_version,
177 profile: legacy.profile,
178 docs_root: legacy.docs_root.as_str().to_string(),
179 managed: legacy
180 .managed_files
181 .into_iter()
182 .map(|entry| (entry.destination, entry.sha256))
183 .collect(),
184 integration: legacy
185 .integration_blocks
186 .into_iter()
187 .map(|block| (block.path, block.marker_hash))
188 .collect(),
189 schema_current: false,
190 })
191 }
192 Err(error) => Err(AppError::ManifestInvalid(error.to_string())),
193 }
194}
195
196fn conflicts_at(target: &Utf8Path, installed: &Installed) -> Result<Vec<Conflict>, AppError> {
218 let mut conflicts = Vec::new();
219 let mut push = |path: &Utf8Path, kind| {
220 conflicts.push(Conflict {
221 path: path.to_string(),
222 kind,
223 });
224 };
225 for (destination, recorded) in &installed.managed {
226 let file = target.join(destination);
227 if !file.is_file() {
228 push(destination, ConflictKind::MissingManagedFile);
229 continue;
230 }
231 if sha256_file(&file)? != *recorded {
232 push(destination, ConflictKind::EditedManagedFile);
233 }
234 }
235 for (path, recorded) in &installed.integration {
236 let full = target.join(path);
237 if !full.is_file() {
238 push(path, ConflictKind::MissingIntegrationHost);
239 continue;
240 }
241 let (begin, end) = markers_for(path.as_str());
242 let host = std::fs::read_to_string(&full)?;
243 match crate::domain::marker::block_hash_with(&host, begin, end) {
244 Some(present) if present == *recorded => {}
245 _ => push(path, ConflictKind::EditedManagedBlock),
246 }
247 }
248 Ok(conflicts)
249}
250
251fn unattributed(
254 target: &Utf8Path,
255 candidate: &crate::candidate::Candidate,
256 known: &[Conflict],
257) -> Vec<Conflict> {
258 let recorded = crate::services::installer::recorded(target);
259 let packages = crate::landing::apply::refused_skill_packages(target, &recorded);
260 let mut found: Vec<Conflict> = packages
261 .iter()
262 .map(|folder| Conflict {
263 path: folder.clone(),
264 kind: ConflictKind::UnattributedSkillPackage,
265 })
266 .collect();
267 for destination in &candidate.destinations {
268 if packages
269 .iter()
270 .any(|folder| destination.path.as_str().starts_with(folder.as_str()))
271 {
272 continue;
273 }
274 let Ok(held) = std::fs::read(target.join(&destination.path)) else {
275 continue;
276 };
277 if held == destination.bytes
278 || crate::landing::apply::vouches(
279 &recorded,
280 &destination.path,
281 destination.ownership,
282 &held,
283 )
284 || known
285 .iter()
286 .any(|conflict| conflict.path == destination.path.as_str())
287 {
288 continue;
289 }
290 found.push(Conflict {
291 path: destination.path.to_string(),
292 kind: ConflictKind::Unattributed,
293 });
294 }
295 found
296}
297
298fn reinstall_options(
304 target: &Utf8Path,
305 profile: ProfileId,
306 options: &UpgradeOptions,
307) -> InitOptions {
308 let staged = options.staged.as_ref();
309 InitOptions {
310 target: target.to_path_buf(),
311 profile,
312 apply: false,
313 dry_run: true,
314 docs_scratch: staged.map(|choices| choices.docs_scratch.clone()),
315 reserve: staged
316 .map(|choices| choices.reserve.clone())
317 .unwrap_or_default(),
318 writing_style: staged.map(|choices| choices.writing_style.clone()),
319 acquisition: staged.and_then(|choices| choices.acquisition.clone()),
320 replace: options.replace.clone(),
321 }
322}
323
324fn report_removals(removed: &[String], outcome: &mut UpgradeOutcome) {
329 for raw in removed {
330 outcome
331 .lines
332 .push(format!("removed managed file no longer owned: {raw}"));
333 }
334}
335
336pub fn upgrade(options: &UpgradeOptions) -> Result<UpgradeOutcome, AppError> {
345 if !options.target.is_absolute() {
346 return Err(AppError::Usage("target must be absolute".to_string()));
347 }
348 if !options.target.is_dir() {
349 return Err(AppError::Usage(format!(
350 "unresolved target: {}",
351 options.target
352 )));
353 }
354 let target = Utf8PathBuf::from_path_buf(std::fs::canonicalize(&options.target)?)
355 .map_err(|p| AppError::Usage(format!("target is not UTF-8: {}", p.display())))?;
356
357 let held = if options.dry_run {
362 None
363 } else {
364 Some(crate::landing::lock::hold(&target)?)
365 };
366
367 let installed = read_installed(&target)?;
368 let new = CanonVersion::current();
371 let old = installed.version;
372
373 if old > new {
374 return Err(AppError::Refused(format!(
375 "sdd {new} is older than the installed canon {old}; upgrade sdd"
376 )));
377 }
378
379 if let Some(staged) = options.staged.as_ref()
380 && staged.profile != installed.profile
381 {
382 return Err(AppError::Refused(format!(
383 "the stage projects the {} profile and {target} records {}; moving a profile is a migration to ask for deliberately",
384 staged.profile, installed.profile
385 )));
386 }
387 let mut outcome = UpgradeOutcome::from_record(old, new);
388 let reinstall = reinstall_options(&target, installed.profile, options);
389 outcome.retired_citations = retired_citations(&target, &installed);
390
391 let conflicts = scan(&target, &installed, &reinstall, &options.replace)?;
396 outcome.conflicts.clone_from(&conflicts);
397 let unnamed: Vec<&Conflict> = conflicts
398 .iter()
399 .filter(|conflict| !options.replace.contains(&conflict.path))
400 .collect();
401 if !unnamed.is_empty() {
402 outcome.failures += unnamed.len();
403 outcome
404 .lines
405 .extend(unnamed.iter().map(|conflict| conflict.line()));
406 report_citations(&mut outcome);
407 return Ok(outcome);
408 }
409
410 if old == new
411 && installed.schema_current
412 && options.replace.is_empty()
413 && options.staged.is_none()
414 {
415 outcome.lines.push(format!("OK already at {new}"));
416 report_citations(&mut outcome);
417 return Ok(outcome);
418 }
419
420 let save_root = save_root(&target, &options.replace, !options.dry_run)?;
421 if options.dry_run {
422 preview(
423 &target,
424 options,
425 &reinstall,
426 save_root.as_deref(),
427 &mut outcome,
428 )?;
429 report_citations(&mut outcome);
430 return Ok(outcome);
431 }
432
433 keep_named(
436 &target,
437 &options.replace,
438 save_root.as_deref(),
439 &mut outcome,
440 )?;
441
442 let reinstalled = init_holding(
443 held,
444 &InitOptions {
445 apply: true,
446 dry_run: false,
447 ..reinstall
448 },
449 crate::landing::classify::Intent::Reconcile,
452 )
453 .map_err(|error| {
454 AppError::Refused(format!(
455 "upgrade aborted during reinstall from {old} to {new}: {error}"
456 ))
457 })?;
458 let removed = reinstalled.removed.clone();
462 outcome.lines.extend(
463 reinstalled
464 .lines
465 .into_iter()
466 .filter(|line| line.starts_with("note:")),
467 );
468
469 finish(&target, &installed, &removed, old, new, &mut outcome);
470 Ok(outcome)
471}
472
473fn scan(
479 target: &Utf8Path,
480 installed: &Installed,
481 reinstall: &InitOptions,
482 named: &[String],
483) -> Result<Vec<Conflict>, AppError> {
484 let (conflicts, candidate) = conflicts_with_candidate(target, installed, reinstall)?;
485 for name in named {
491 let Some(conflict) = conflicts.iter().find(|conflict| &conflict.path == name) else {
492 return Err(AppError::Usage(format!(
493 "--replace {name} names no conflict; the conflicts are the destinations this run lists"
494 )));
495 };
496 if conflict.kind == ConflictKind::UnattributedSkillPackage {
497 return Err(AppError::Refused(format!(
498 "--replace {name} names a skill package folder, which is never replaced; move it aside, then run this again"
499 )));
500 }
501 if let Some((component, kind)) =
502 crate::landing::apply::refuses_named(target, &candidate, name)
503 {
504 return Err(AppError::Refused(format!(
505 "--replace {name} names a destination the landing cannot write: {component} {kind}; move it aside, then run this again"
506 )));
507 }
508 }
509 Ok(conflicts)
510}
511
512fn conflicts_with_candidate(
514 target: &Utf8Path,
515 installed: &Installed,
516 reinstall: &InitOptions,
517) -> Result<(Vec<Conflict>, crate::candidate::Candidate), AppError> {
518 let mut conflicts = conflicts_at(target, installed)?;
519 let candidate =
520 crate::services::installer::candidate_for(target, reinstall).map_err(|error| {
521 AppError::Refused(format!(
522 "upgrade could not render the candidate for {target}: {error}"
523 ))
524 })?;
525 let unattributed = unattributed(target, &candidate, &conflicts);
526 conflicts.extend(unattributed);
527 Ok((conflicts, candidate))
528}
529
530pub(crate) fn replaceable(staged: &crate::stage::StagedChoices) -> Result<Vec<String>, AppError> {
542 let target = &staged.target;
543 if crate::commands::front::serves(crate::landing::classify::Intent::Upgrade, target).is_err() {
544 return Ok(Vec::new());
545 }
546 let Ok(installed) = read_installed(target) else {
547 return Ok(Vec::new());
548 };
549 if installed.version > CanonVersion::current() || staged.profile != installed.profile {
550 return Ok(Vec::new());
551 }
552 let options = UpgradeOptions {
553 target: target.clone(),
554 dry_run: true,
555 staged: Some(staged.clone()),
556 replace: Vec::new(),
557 };
558 let reinstall = reinstall_options(target, installed.profile, &options);
559 let (conflicts, candidate) = conflicts_with_candidate(target, &installed, &reinstall)?;
560 Ok(conflicts
561 .into_iter()
562 .filter(|conflict| {
563 conflict.kind != ConflictKind::UnattributedSkillPackage
564 && crate::landing::apply::refuses_named(target, &candidate, &conflict.path)
565 .is_none()
566 })
567 .map(|conflict| conflict.path)
568 .collect())
569}
570
571fn preview(
574 target: &Utf8Path,
575 options: &UpgradeOptions,
576 reinstall: &InitOptions,
577 save_root: Option<&Utf8Path>,
578 outcome: &mut UpgradeOutcome,
579) -> Result<(), AppError> {
580 let new = CanonVersion::current();
581 let old = outcome.from.unwrap_or(new);
582 if old != new {
586 outcome
587 .lines
588 .push(format!("DRY RUN upgrade {old} to {new}"));
589 } else if options.replace.is_empty() {
590 outcome
591 .lines
592 .push(format!("DRY RUN migrate the record of {new}"));
593 } else {
594 outcome.lines.push(format!("DRY RUN repair {new}"));
595 }
596 for named in &options.replace {
597 let saved_to = target
598 .join(named)
599 .is_file()
600 .then(|| save_root.map(|root| root.join(named)))
601 .flatten();
602 outcome.lines.push(saved_to.as_ref().map_or_else(
603 || format!("DRY RUN write {named}, which the target lacks"),
604 |saved| format!("DRY RUN save {named} to {saved}, then replace it"),
605 ));
606 outcome.replaced.push(Replaced {
607 path: named.clone(),
608 saved_to,
609 });
610 }
611 let preview =
614 init(reinstall, crate::landing::classify::Intent::Reconcile).map_err(|error| {
615 AppError::Refused(format!(
616 "upgrade could not be previewed from {old} to {new}: {error}"
617 ))
618 })?;
619 outcome.lines.extend(
620 preview
621 .lines
622 .into_iter()
623 .filter(|line| line.starts_with("note:")),
624 );
625 Ok(())
626}
627
628impl UpgradeOutcome {
629 fn from_record(old: CanonVersion, new: CanonVersion) -> Self {
635 let mut outcome = Self {
636 from: Some(old),
637 ..Self::default()
638 };
639 if old < new {
640 outcome.next = Some(crate::self_depend::guidance::MOVED);
641 outcome
642 .lines
643 .push(crate::self_depend::guidance::MOVED.to_string());
644 }
645 outcome
646 }
647}
648
649fn report_citations(outcome: &mut UpgradeOutcome) {
651 for citation in &outcome.retired_citations {
652 outcome.lines.push(format!(
653 "retired rule ID cited: {}:{} `{}`; re-point it to the rule the changelog names",
654 citation.path, citation.line, citation.id
655 ));
656 }
657}
658
659fn save_root(
671 target: &Utf8Path,
672 named: &[String],
673 claim: bool,
674) -> Result<Option<Utf8PathBuf>, AppError> {
675 if named.is_empty() {
676 return Ok(None);
677 }
678 let env = crate::domain::paths::UserEnv::from_process();
679 let recorded = crate::services::installer::recorded_field(target, "docs_scratch")
680 .and_then(|value| value.as_str().map(Utf8PathBuf::from))
681 .filter(|path| !path.as_str().is_empty());
682 let scratch = env.docs_scratch.clone().map(Utf8PathBuf::from).or(recorded);
683 if let Some(scratch) = scratch {
684 return Ok(Some(target.join(scratch).join("replaced")));
685 }
686 let Some(state) = env.state_root() else {
687 return Ok(None);
688 };
689 let runs = state
690 .path
691 .join("snapshots")
692 .join(crate::stage::stage_name(target));
693 let stamp = jiff::Timestamp::now()
694 .strftime("%Y%m%dT%H%M%SZ")
695 .to_string();
696 let run = if claim {
697 crate::adapters::fs::claim_run_dir(&runs, &stamp)?
698 } else {
699 runs.join(stamp)
700 };
701 Ok(Some(run.join("replaced")))
702}
703
704fn keep_named(
706 target: &Utf8Path,
707 named: &[String],
708 root: Option<&Utf8Path>,
709 outcome: &mut UpgradeOutcome,
710) -> Result<(), AppError> {
711 for name in named {
712 let saved_to = save(target, name, root)?;
713 if let Some(saved) = &saved_to {
714 outcome.lines.push(format!("saved {name} to {saved}"));
715 }
716 outcome.replaced.push(Replaced {
717 path: name.clone(),
718 saved_to,
719 });
720 }
721 Ok(())
722}
723
724fn save(
729 target: &Utf8Path,
730 named: &str,
731 root: Option<&Utf8Path>,
732) -> Result<Option<Utf8PathBuf>, AppError> {
733 let held = match std::fs::read(target.join(named)) {
734 Ok(held) => held,
735 Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(None),
736 Err(source) => return Err(AppError::Io(source)),
737 };
738 let Some(root) = root else {
739 return Err(AppError::Refused(format!(
740 "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"
741 )));
742 };
743 let saved = root.join(named);
744 match std::fs::read(&saved) {
745 Ok(existing) if existing == held => return Ok(Some(saved)),
746 Ok(_) => {
747 return Err(AppError::Refused(format!(
748 "{saved} already keeps other bytes of {named}; move it aside, then run this again"
749 )));
750 }
751 Err(_) => {}
752 }
753 crate::adapters::fs::write_file(&saved, &held)?;
754 Ok(Some(saved))
755}
756
757fn instance_rule_ids(target: &Utf8Path, docs_root: &str) -> std::collections::BTreeSet<String> {
760 let mut ids = std::collections::BTreeSet::new();
761 let specs = target.join(docs_root).join("specs");
762 if let Ok(entries) = specs.read_dir_utf8() {
763 for entry in entries.filter_map(Result::ok) {
764 if let Ok(text) = std::fs::read_to_string(entry.path()) {
765 ids.extend(crate::embedded::rule_ids_in(&text));
766 }
767 }
768 }
769 ids
770}
771
772fn retired_citations(target: &Utf8Path, installed: &Installed) -> Vec<Citation> {
787 let defined = crate::embedded::spec_rule_ids();
788 let domains: std::collections::BTreeSet<&str> = defined
789 .iter()
790 .filter_map(|id| id.split_once(':').map(|(domain, _)| domain))
791 .collect();
792 let shipped: std::collections::BTreeSet<String> = crate::embedded::spec_texts()
795 .flat_map(|text| {
796 text.lines()
797 .flat_map(crate::gates::adr_cites_a_live_rule::cited_ids)
798 .map(String::from)
799 .collect::<Vec<_>>()
800 })
801 .collect();
802 let local = instance_rule_ids(target, &installed.docs_root);
805 let managed: Vec<&Utf8PathBuf> = installed.managed.iter().map(|(path, _)| path).collect();
806 let decisions = Utf8Path::new(&installed.docs_root).join("decisions");
807 let mut found = Vec::new();
808 let walker = walkdir::WalkDir::new(target)
809 .sort_by_file_name()
810 .into_iter()
811 .filter_entry(|entry| {
812 let name = entry.file_name().to_string_lossy();
813 !(entry.depth() > 0
814 && entry.file_type().is_dir()
815 && (crate::gates::PRUNED_DIRS.contains(&name.as_ref())
816 || name == crate::domain::paths::INSTANCE_DIR
817 || crate::domain::paths::DOCS_SCRATCH_LEAVES.contains(&name.as_ref())))
818 });
819 for entry in walker.filter_map(Result::ok) {
820 if !entry.file_type().is_file() {
821 continue;
822 }
823 let Some(path) = entry.path().to_str() else {
824 continue;
825 };
826 let Ok(relative) = Utf8Path::new(path).strip_prefix(target) else {
827 continue;
828 };
829 if relative.extension() != Some("md")
830 || relative == "CHANGELOG.md"
831 || managed.iter().any(|held| *held == relative)
832 {
833 continue;
834 }
835 let Ok(text) = std::fs::read_to_string(entry.path()) else {
836 continue;
837 };
838 let record = relative.starts_with(&decisions);
839 if record && crate::gates::adr_cites_a_live_rule::superseded(&text) {
842 continue;
843 }
844 let enforced: std::collections::BTreeSet<usize> = if record {
845 crate::gates::adr_cites_a_live_rule::enforced_by(&text)
846 .into_iter()
847 .map(|(number, _)| number)
848 .collect()
849 } else {
850 std::collections::BTreeSet::new()
851 };
852 for (index, line) in text.lines().enumerate() {
853 if line.starts_with("### `") || (record && !enforced.contains(&(index + 1))) {
854 continue;
855 }
856 for id in crate::gates::adr_cites_a_live_rule::cited_ids(line) {
857 let domain = id.split_once(':').map_or(id, |(domain, _)| domain);
858 if domains.contains(domain)
859 && !defined.contains(id)
860 && !shipped.contains(id)
861 && !local.contains(id)
862 {
863 found.push(Citation {
864 path: relative.to_owned(),
865 line: index + 1,
866 id: id.to_string(),
867 });
868 }
869 }
870 }
871 }
872 found
873}
874
875fn finish(
876 target: &Utf8Path,
877 installed: &Installed,
878 removed: &[String],
879 old: CanonVersion,
880 new: CanonVersion,
881 outcome: &mut UpgradeOutcome,
882) {
883 report_removals(removed, outcome);
884
885 let local_ids = instance_rule_ids(target, &installed.docs_root);
886 let upstream_only: Vec<String> = crate::embedded::spec_rule_ids()
887 .difference(&local_ids)
888 .cloned()
889 .collect();
890 if !upstream_only.is_empty() {
891 outcome
892 .lines
893 .push("upstream rule IDs not present locally:".to_string());
894 for id in upstream_only {
895 outcome.lines.push(format!(" {id}"));
896 }
897 }
898
899 if outcome.failures > 0 {
900 outcome.lines.push(format!(
901 "FAIL upgraded {old} to {new} with unfinished removals above"
902 ));
903 } else if old == new {
904 outcome
905 .lines
906 .push(format!("OK migrated the record of {new}"));
907 } else {
908 outcome.lines.push(format!("OK upgraded {old} to {new}"));
909 }
910}
911
912#[cfg(test)]
913mod tests {
914 use super::*;
915
916 #[test]
918 fn two_saves_in_one_second_keep_both_copies() {
919 let dir = tempfile::tempdir().unwrap();
920 let root = Utf8Path::from_path(dir.path()).unwrap();
921 let target = root.join("target");
922 let runs = root.join("snapshots");
923 let stamp = "20261009T213000Z";
924
925 crate::adapters::fs::write_file(&target.join("AGENTS.md"), b"first").unwrap();
926 let first = crate::adapters::fs::claim_run_dir(&runs, stamp).unwrap();
927 let kept = save(&target, "AGENTS.md", Some(&first)).unwrap().unwrap();
928
929 crate::adapters::fs::write_file(&target.join("AGENTS.md"), b"second").unwrap();
930 let second = crate::adapters::fs::claim_run_dir(&runs, stamp).unwrap();
931 let again = save(&target, "AGENTS.md", Some(&second)).unwrap().unwrap();
932
933 assert_ne!(kept, again);
934 assert_eq!(std::fs::read(&kept).unwrap(), b"first");
935 assert_eq!(std::fs::read(&again).unwrap(), b"second");
936 }
937
938 fn installed() -> Installed {
940 Installed {
941 version: CanonVersion::current(),
942 profile: ProfileId::Codebase,
943 docs_root: "docs".to_string(),
944 managed: Vec::new(),
945 integration: Vec::new(),
946 schema_current: true,
947 }
948 }
949
950 fn record_with_status(status: &str) -> tempfile::TempDir {
952 let dir = tempfile::tempdir().unwrap();
953 let root = Utf8Path::from_path(dir.path()).unwrap();
954 crate::adapters::fs::write_file(
955 &root.join("docs/decisions/ADR-old-choice.md"),
956 format!(
957 "# Old choice\n\n## Status\n\n{status}\n\n## Decision\n\nEnforced by `staging:a-rule-no-release-defines`.\n"
958 )
959 .as_bytes(),
960 )
961 .unwrap();
962 dir
963 }
964
965 #[test]
967 fn a_superseded_record_gives_no_retired_citation() {
968 let dir = record_with_status("Superseded by [ADR-new-choice](ADR-new-choice.md)");
969 let target = Utf8Path::from_path(dir.path()).unwrap();
970 assert!(retired_citations(target, &installed()).is_empty());
971 }
972
973 #[test]
975 fn a_record_with_no_superseded_line_still_gives_its_retired_citation() {
976 let dir = record_with_status("Accepted");
977 let target = Utf8Path::from_path(dir.path()).unwrap();
978 let found = retired_citations(target, &installed());
979 assert_eq!(found.len(), 1, "{found:?}");
980 assert_eq!(found[0].id, "staging:a-rule-no-release-defines");
981 assert_eq!(found[0].path, "docs/decisions/ADR-old-choice.md");
982 }
983}