1use camino::{Utf8Path, Utf8PathBuf};
12use serde::Serialize;
13
14use crate::adapters::fs::sha256_file;
15use crate::domain::manifest::{LegacyManifest, MANIFEST_PATH, Manifest, ManifestParseError};
16use crate::domain::ownership::Sha256;
17use crate::domain::profile::ProfileId;
18use crate::domain::version::CanonVersion;
19use crate::error::AppError;
20use crate::services::installer::{InitOptions, init, init_holding};
21
22#[derive(Debug, Clone)]
24pub struct UpgradeOptions {
25 pub target: Utf8PathBuf,
27 pub dry_run: bool,
29 pub staged: Option<crate::stage::StagedChoices>,
31 pub replace: Vec<String>,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
38#[serde(rename_all = "kebab-case")]
39pub enum ConflictKind {
40 EditedManagedFile,
42 MissingManagedFile,
44 EditedManagedBlock,
46 MissingIntegrationHost,
48 Unattributed,
51 UnattributedSkillPackage,
54}
55
56#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
58pub struct Conflict {
59 pub path: String,
61 pub kind: ConflictKind,
63}
64
65impl Conflict {
66 fn line(&self) -> String {
68 let what = match self.kind {
69 ConflictKind::EditedManagedFile => "locally edited managed file",
70 ConflictKind::MissingManagedFile => "missing managed file",
71 ConflictKind::EditedManagedBlock => "locally edited managed block",
72 ConflictKind::MissingIntegrationHost => "missing integration host",
73 ConflictKind::Unattributed => "destination holds bytes no record vouches for",
74 ConflictKind::UnattributedSkillPackage => {
75 return format!(
76 "CONFLICT {}",
77 crate::landing::apply::refused_package_line(&self.path)
78 );
79 }
80 };
81 format!("CONFLICT {what}: {}", self.path)
82 }
83}
84
85#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
87pub struct Replaced {
88 pub path: String,
90 pub saved_to: Option<Utf8PathBuf>,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
96pub struct Citation {
97 pub path: Utf8PathBuf,
99 pub line: usize,
101 pub id: String,
103}
104
105#[derive(Debug, Default)]
107pub struct UpgradeOutcome {
108 pub lines: Vec<String>,
110 pub failures: usize,
112 pub from: Option<CanonVersion>,
114 pub conflicts: Vec<Conflict>,
116 pub replaced: Vec<Replaced>,
118 pub retired_citations: Vec<Citation>,
120 pub retired: Vec<String>,
123 pub dropped: Vec<String>,
126 pub next: Option<&'static str>,
129}
130
131struct Installed {
132 version: CanonVersion,
133 profile: ProfileId,
134 docs_root: String,
135 managed: Vec<(Utf8PathBuf, Sha256)>,
136 integration: Vec<(Utf8PathBuf, Sha256)>,
137 adopted_moved: bool,
140 schema_current: bool,
147}
148
149fn markers_for(path: &str) -> (&'static str, &'static str) {
151 use crate::domain::marker::{AGENTS_BEGIN, AGENTS_END, BEGIN, END};
152 if path == crate::domain::paths::HOOKS_CONFIG_PATH {
153 (BEGIN, END)
154 } else {
155 (AGENTS_BEGIN, AGENTS_END)
156 }
157}
158
159fn read_installed(target: &Utf8Path) -> Result<Installed, AppError> {
160 let path = target.join(MANIFEST_PATH);
161 if !path.is_file() {
162 return Err(AppError::ManifestMissing(path));
163 }
164 let text = std::fs::read_to_string(&path)?;
165 match Manifest::parse(&text) {
166 Ok(manifest) => Ok(Installed {
167 adopted_moved: manifest.adopted_files.iter().any(|entry| {
168 sha256_file(&target.join(&entry.destination)).ok().as_ref() != Some(&entry.sha256)
169 }),
170 version: manifest.canon_version,
171 profile: manifest.profile,
172 docs_root: manifest.docs_root.as_str().to_string(),
173 managed: manifest
174 .managed_files
175 .into_iter()
176 .map(|entry| (entry.destination, entry.sha256))
177 .collect(),
178 integration: manifest
179 .integration_blocks
180 .into_iter()
181 .map(|block| (block.path, block.marker_hash))
182 .collect(),
183 schema_current: true,
184 }),
185 Err(ManifestParseError::Older(_)) => {
186 let legacy: LegacyManifest = serde_json::from_str(&text)
187 .map_err(|e| AppError::ManifestInvalid(e.to_string()))?;
188 Ok(Installed {
189 adopted_moved: false,
192 version: legacy.canon_version,
193 profile: legacy.profile,
194 docs_root: legacy.docs_root.as_str().to_string(),
195 managed: legacy
196 .managed_files
197 .into_iter()
198 .map(|entry| (entry.destination, entry.sha256))
199 .collect(),
200 integration: legacy
201 .integration_blocks
202 .into_iter()
203 .map(|block| (block.path, block.marker_hash))
204 .collect(),
205 schema_current: false,
206 })
207 }
208 Err(error) => Err(AppError::ManifestInvalid(error.to_string())),
209 }
210}
211
212fn conflicts_at(
240 target: &Utf8Path,
241 installed: &Installed,
242 candidate: &crate::candidate::Candidate,
243) -> Result<Vec<Conflict>, AppError> {
244 let lands = |destination: &Utf8Path| {
245 candidate
246 .destinations
247 .iter()
248 .any(|landed| landed.path == destination)
249 };
250 let mut conflicts = Vec::new();
251 let mut push = |path: &Utf8Path, kind| {
252 conflicts.push(Conflict {
253 path: path.to_string(),
254 kind,
255 });
256 };
257 for (destination, recorded) in &installed.managed {
258 if !lands(destination) {
259 continue;
260 }
261 let file = target.join(destination);
262 if !file.is_file() {
263 push(destination, ConflictKind::MissingManagedFile);
264 continue;
265 }
266 if sha256_file(&file)? != *recorded {
267 push(destination, ConflictKind::EditedManagedFile);
268 }
269 }
270 for (path, recorded) in &installed.integration {
271 let full = target.join(path);
272 if !full.is_file() {
273 push(path, ConflictKind::MissingIntegrationHost);
274 continue;
275 }
276 let (begin, end) = markers_for(path.as_str());
277 let host = std::fs::read_to_string(&full)?;
278 match crate::domain::marker::block_hash_with(&host, begin, end) {
279 Some(present) if present == *recorded => {}
280 _ => push(path, ConflictKind::EditedManagedBlock),
281 }
282 }
283 Ok(conflicts)
284}
285
286fn unattributed(
289 target: &Utf8Path,
290 candidate: &crate::candidate::Candidate,
291 known: &[Conflict],
292) -> Vec<Conflict> {
293 let recorded = crate::services::installer::recorded(target);
294 let packages = crate::landing::apply::refused_skill_packages(target, &recorded);
295 let mut found: Vec<Conflict> = packages
296 .iter()
297 .map(|folder| Conflict {
298 path: folder.clone(),
299 kind: ConflictKind::UnattributedSkillPackage,
300 })
301 .collect();
302 for destination in &candidate.destinations {
303 if packages
304 .iter()
305 .any(|folder| destination.path.as_str().starts_with(folder.as_str()))
306 {
307 continue;
308 }
309 let Ok(held) = std::fs::read(target.join(&destination.path)) else {
310 continue;
311 };
312 if held == destination.bytes
313 || crate::landing::apply::vouches(
314 &recorded,
315 &destination.path,
316 destination.ownership,
317 &held,
318 )
319 || known
320 .iter()
321 .any(|conflict| conflict.path == destination.path.as_str())
322 {
323 continue;
324 }
325 found.push(Conflict {
326 path: destination.path.to_string(),
327 kind: ConflictKind::Unattributed,
328 });
329 }
330 found
331}
332
333fn reinstall_options(
339 target: &Utf8Path,
340 profile: ProfileId,
341 options: &UpgradeOptions,
342) -> InitOptions {
343 let staged = options.staged.as_ref();
344 InitOptions {
345 target: target.to_path_buf(),
346 profile,
347 apply: false,
348 dry_run: true,
349 docs_scratch: staged.map(|choices| choices.docs_scratch.clone()),
350 reserve: staged
351 .map(|choices| choices.reserve.clone())
352 .unwrap_or_default(),
353 writing_style: staged.map(|choices| choices.writing_style.clone()),
354 acquisition: staged.and_then(|choices| choices.acquisition.clone()),
355 replace: options.replace.clone(),
356 }
357}
358
359fn report_departures(
364 retired: Vec<String>,
365 dropped: Vec<String>,
366 prefix: &str,
367 outcome: &mut UpgradeOutcome,
368) {
369 for path in &retired {
370 outcome
371 .lines
372 .push(format!("{prefix}retired managed file, deleted: {path}"));
373 }
374 for path in &dropped {
375 outcome.lines.push(format!(
376 "{prefix}dropped managed file, kept as the project's: {path}"
377 ));
378 if let Some(line) = still_acts(path) {
379 outcome.lines.push(format!("{prefix}{line}"));
380 }
381 }
382 outcome.retired = retired;
383 outcome.dropped = dropped;
384}
385
386fn still_acts(path: &str) -> Option<String> {
393 let folder = path.strip_suffix(&format!("/{}", crate::domain::paths::SKILL_FILE))?;
394 crate::embedded::SKILL_ROOTS
395 .iter()
396 .any(|root| {
397 folder
398 .strip_prefix(root)
399 .and_then(|rest| rest.strip_prefix('/'))
400 .is_some_and(|name| !name.is_empty() && !name.contains('/'))
401 })
402 .then(|| {
403 format!(
404 "note: {folder}/ still loads as a skill that this release no longer ships; delete the folder, or keep it as the project's own skill"
405 )
406 })
407}
408
409pub fn upgrade(options: &UpgradeOptions) -> Result<UpgradeOutcome, AppError> {
418 if !options.target.is_absolute() {
419 return Err(AppError::Usage("target must be absolute".to_string()));
420 }
421 if !options.target.is_dir() {
422 return Err(AppError::Usage(format!(
423 "unresolved target: {}",
424 options.target
425 )));
426 }
427 let target = Utf8PathBuf::from_path_buf(std::fs::canonicalize(&options.target)?)
428 .map_err(|p| AppError::Usage(format!("target is not UTF-8: {}", p.display())))?;
429
430 let held = if options.dry_run {
435 None
436 } else {
437 Some(crate::landing::lock::hold(&target)?)
438 };
439
440 let installed = read_installed(&target)?;
441 let new = CanonVersion::current();
444 let old = installed.version;
445
446 if old > new {
447 return Err(AppError::Refused(format!(
448 "sdd {new} is older than the installed canon {old}; upgrade sdd"
449 )));
450 }
451
452 if let Some(staged) = options.staged.as_ref()
453 && staged.profile != installed.profile
454 {
455 return Err(AppError::Refused(format!(
456 "the stage projects the {} profile and {target} records {}; moving a profile is a migration to ask for deliberately",
457 staged.profile, installed.profile
458 )));
459 }
460 let mut outcome = UpgradeOutcome::from_record(old, new);
461 let reinstall = reinstall_options(&target, installed.profile, options);
462 outcome.retired_citations = retired_citations(&target, &installed);
463
464 let conflicts = scan(&target, &installed, &reinstall, &options.replace)?;
469 outcome.conflicts.clone_from(&conflicts);
470 let unnamed: Vec<&Conflict> = conflicts
471 .iter()
472 .filter(|conflict| !options.replace.contains(&conflict.path))
473 .collect();
474 if !unnamed.is_empty() {
475 outcome.failures += unnamed.len();
476 outcome
477 .lines
478 .extend(unnamed.iter().map(|conflict| conflict.line()));
479 report_citations(&mut outcome);
480 return Ok(outcome);
481 }
482
483 if old == new
486 && installed.schema_current
487 && !installed.adopted_moved
488 && options.replace.is_empty()
489 && options.staged.is_none()
490 {
491 outcome.lines.push(format!("OK already at {new}"));
492 report_citations(&mut outcome);
493 return Ok(outcome);
494 }
495
496 let save_root = save_root(&target, &options.replace, !options.dry_run)?;
497 if options.dry_run {
498 preview(
499 &target,
500 installed.schema_current && installed.adopted_moved,
501 options,
502 &reinstall,
503 save_root.as_deref(),
504 &mut outcome,
505 )?;
506 report_citations(&mut outcome);
507 return Ok(outcome);
508 }
509
510 keep_named(
513 &target,
514 &options.replace,
515 save_root.as_deref(),
516 &mut outcome,
517 )?;
518
519 let reinstalled = init_holding(
520 held,
521 &InitOptions {
522 apply: true,
523 dry_run: false,
524 ..reinstall
525 },
526 crate::landing::classify::Intent::Reconcile,
529 )
530 .map_err(|error| {
531 AppError::Refused(format!(
532 "upgrade aborted during reinstall from {old} to {new}: {error}"
533 ))
534 })?;
535 finish(&target, &installed, reinstalled, &mut outcome);
536 Ok(outcome)
537}
538
539fn scan(
545 target: &Utf8Path,
546 installed: &Installed,
547 reinstall: &InitOptions,
548 named: &[String],
549) -> Result<Vec<Conflict>, AppError> {
550 let (conflicts, candidate) = conflicts_with_candidate(target, installed, reinstall)?;
551 for name in named {
557 let Some(conflict) = conflicts.iter().find(|conflict| &conflict.path == name) else {
558 return Err(AppError::Usage(format!(
559 "--replace {name} names no conflict; the conflicts are the destinations this run lists"
560 )));
561 };
562 if conflict.kind == ConflictKind::UnattributedSkillPackage {
563 return Err(AppError::Refused(format!(
564 "--replace {name} names a skill package folder, which is never replaced; move it aside, then run this again"
565 )));
566 }
567 if let Some((component, kind)) =
568 crate::landing::apply::refuses_named(target, &candidate, name)
569 {
570 return Err(AppError::Refused(format!(
571 "--replace {name} names a destination the landing cannot write: {component} {kind}; move it aside, then run this again"
572 )));
573 }
574 }
575 Ok(conflicts)
576}
577
578fn conflicts_with_candidate(
580 target: &Utf8Path,
581 installed: &Installed,
582 reinstall: &InitOptions,
583) -> Result<(Vec<Conflict>, crate::candidate::Candidate), AppError> {
584 let candidate =
585 crate::services::installer::candidate_for(target, reinstall).map_err(|error| {
586 AppError::Refused(format!(
587 "upgrade could not render the candidate for {target}: {error}"
588 ))
589 })?;
590 let mut conflicts = conflicts_at(target, installed, &candidate)?;
591 let unattributed = unattributed(target, &candidate, &conflicts);
592 conflicts.extend(unattributed);
593 Ok((conflicts, candidate))
594}
595
596pub(crate) fn replaceable(staged: &crate::stage::StagedChoices) -> Result<Vec<String>, AppError> {
608 let target = &staged.target;
609 if crate::commands::front::serves(crate::landing::classify::Intent::Upgrade, target).is_err() {
610 return Ok(Vec::new());
611 }
612 let Ok(installed) = read_installed(target) else {
613 return Ok(Vec::new());
614 };
615 if installed.version > CanonVersion::current() || staged.profile != installed.profile {
616 return Ok(Vec::new());
617 }
618 let options = UpgradeOptions {
619 target: target.clone(),
620 dry_run: true,
621 staged: Some(staged.clone()),
622 replace: Vec::new(),
623 };
624 let reinstall = reinstall_options(target, installed.profile, &options);
625 let (conflicts, candidate) = conflicts_with_candidate(target, &installed, &reinstall)?;
626 Ok(conflicts
627 .into_iter()
628 .filter(|conflict| {
629 conflict.kind != ConflictKind::UnattributedSkillPackage
630 && crate::landing::apply::refuses_named(target, &candidate, &conflict.path)
631 .is_none()
632 })
633 .map(|conflict| conflict.path)
634 .collect())
635}
636
637fn preview(
640 target: &Utf8Path,
641 adopted_edits: bool,
642 options: &UpgradeOptions,
643 reinstall: &InitOptions,
644 save_root: Option<&Utf8Path>,
645 outcome: &mut UpgradeOutcome,
646) -> Result<(), AppError> {
647 let new = CanonVersion::current();
648 let old = outcome.from.unwrap_or(new);
649 if old != new {
653 outcome
654 .lines
655 .push(format!("DRY RUN upgrade {old} to {new}"));
656 } else if options.replace.is_empty() {
657 outcome.lines.push(if adopted_edits {
658 format!("DRY RUN record the adopted edits at {new}")
659 } else {
660 format!("DRY RUN migrate the record of {new}")
661 });
662 } else {
663 outcome.lines.push(format!("DRY RUN repair {new}"));
664 }
665 for named in &options.replace {
666 let saved_to = target
667 .join(named)
668 .is_file()
669 .then(|| save_root.map(|root| root.join(named)))
670 .flatten();
671 outcome.lines.push(saved_to.as_ref().map_or_else(
672 || format!("DRY RUN write {named}, which the target lacks"),
673 |saved| format!("DRY RUN save {named} to {saved}, then replace it"),
674 ));
675 outcome.replaced.push(Replaced {
676 path: named.clone(),
677 saved_to,
678 });
679 }
680 let preview =
683 init(reinstall, crate::landing::classify::Intent::Reconcile).map_err(|error| {
684 AppError::Refused(format!(
685 "upgrade could not be previewed from {old} to {new}: {error}"
686 ))
687 })?;
688 outcome.lines.extend(
689 preview
690 .lines
691 .into_iter()
692 .filter(|line| line.starts_with("note:")),
693 );
694 report_departures(preview.removed, preview.dropped, "DRY RUN ", outcome);
695 Ok(())
696}
697
698impl UpgradeOutcome {
699 fn from_record(old: CanonVersion, new: CanonVersion) -> Self {
705 let mut outcome = Self {
706 from: Some(old),
707 ..Self::default()
708 };
709 if old < new {
710 outcome.next = Some(crate::self_depend::guidance::MOVED);
711 outcome
712 .lines
713 .push(crate::self_depend::guidance::MOVED.to_string());
714 }
715 outcome
716 }
717}
718
719fn report_citations(outcome: &mut UpgradeOutcome) {
721 for citation in &outcome.retired_citations {
722 outcome.lines.push(format!(
723 "retired rule ID cited: {}:{} `{}`; re-point it to the rule the changelog names",
724 citation.path, citation.line, citation.id
725 ));
726 }
727}
728
729fn save_root(
741 target: &Utf8Path,
742 named: &[String],
743 claim: bool,
744) -> Result<Option<Utf8PathBuf>, AppError> {
745 if named.is_empty() {
746 return Ok(None);
747 }
748 let env = crate::domain::paths::UserEnv::from_process();
749 let recorded = crate::services::installer::recorded_field(target, "docs_scratch")
750 .and_then(|value| value.as_str().map(Utf8PathBuf::from))
751 .filter(|path| !path.as_str().is_empty());
752 let scratch = env.docs_scratch.clone().map(Utf8PathBuf::from).or(recorded);
753 if let Some(scratch) = scratch {
754 return Ok(Some(target.join(scratch).join("replaced")));
755 }
756 let Some(state) = env.state_root() else {
757 return Ok(None);
758 };
759 let runs = state
760 .path
761 .join("snapshots")
762 .join(crate::stage::stage_name(target));
763 let stamp = jiff::Timestamp::now()
764 .strftime("%Y%m%dT%H%M%SZ")
765 .to_string();
766 let run = if claim {
767 crate::adapters::fs::claim_run_dir(&runs, &stamp)?
768 } else {
769 runs.join(stamp)
770 };
771 Ok(Some(run.join("replaced")))
772}
773
774fn keep_named(
776 target: &Utf8Path,
777 named: &[String],
778 root: Option<&Utf8Path>,
779 outcome: &mut UpgradeOutcome,
780) -> Result<(), AppError> {
781 for name in named {
782 let saved_to = save(target, name, root)?;
783 if let Some(saved) = &saved_to {
784 outcome.lines.push(format!("saved {name} to {saved}"));
785 }
786 outcome.replaced.push(Replaced {
787 path: name.clone(),
788 saved_to,
789 });
790 }
791 Ok(())
792}
793
794fn save(
799 target: &Utf8Path,
800 named: &str,
801 root: Option<&Utf8Path>,
802) -> Result<Option<Utf8PathBuf>, AppError> {
803 let held = match std::fs::read(target.join(named)) {
804 Ok(held) => held,
805 Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(None),
806 Err(source) => return Err(AppError::Io(source)),
807 };
808 let Some(root) = root else {
809 return Err(AppError::Refused(format!(
810 "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"
811 )));
812 };
813 let saved = root.join(named);
814 match std::fs::read(&saved) {
815 Ok(existing) if existing == held => return Ok(Some(saved)),
816 Ok(_) => {
817 return Err(AppError::Refused(format!(
818 "{saved} already keeps other bytes of {named}; move it aside, then run this again"
819 )));
820 }
821 Err(_) => {}
822 }
823 crate::adapters::fs::write_file(&saved, &held)?;
824 Ok(Some(saved))
825}
826
827fn instance_rule_ids(target: &Utf8Path, docs_root: &str) -> std::collections::BTreeSet<String> {
830 let mut ids = std::collections::BTreeSet::new();
831 let specs = target.join(docs_root).join("specs");
832 if let Ok(entries) = specs.read_dir_utf8() {
833 for entry in entries.filter_map(Result::ok) {
834 if let Ok(text) = std::fs::read_to_string(entry.path()) {
835 ids.extend(crate::embedded::rule_ids_in(&text));
836 }
837 }
838 }
839 ids
840}
841
842fn retired_citations(target: &Utf8Path, installed: &Installed) -> Vec<Citation> {
857 let defined = crate::embedded::spec_rule_ids();
858 let domains: std::collections::BTreeSet<&str> = defined
859 .iter()
860 .filter_map(|id| id.split_once(':').map(|(domain, _)| domain))
861 .collect();
862 let shipped: std::collections::BTreeSet<String> = crate::embedded::spec_texts()
865 .flat_map(|text| {
866 text.lines()
867 .flat_map(crate::gates::adr_cites_a_live_rule::cited_ids)
868 .map(String::from)
869 .collect::<Vec<_>>()
870 })
871 .collect();
872 let local = instance_rule_ids(target, &installed.docs_root);
875 let managed: Vec<&Utf8PathBuf> = installed.managed.iter().map(|(path, _)| path).collect();
876 let decisions = Utf8Path::new(&installed.docs_root).join("decisions");
877 let mut found = Vec::new();
878 let walker = walkdir::WalkDir::new(target)
879 .sort_by_file_name()
880 .into_iter()
881 .filter_entry(|entry| {
882 let name = entry.file_name().to_string_lossy();
883 !(entry.depth() > 0
884 && entry.file_type().is_dir()
885 && (crate::gates::PRUNED_DIRS.contains(&name.as_ref())
886 || name == crate::domain::paths::INSTANCE_DIR
887 || crate::domain::paths::DOCS_SCRATCH_LEAVES.contains(&name.as_ref())))
888 });
889 for entry in walker.filter_map(Result::ok) {
890 if !entry.file_type().is_file() {
891 continue;
892 }
893 let Some(path) = entry.path().to_str() else {
894 continue;
895 };
896 let Ok(relative) = Utf8Path::new(path).strip_prefix(target) else {
897 continue;
898 };
899 if relative.extension() != Some("md")
900 || relative == "CHANGELOG.md"
901 || managed.iter().any(|held| *held == relative)
902 {
903 continue;
904 }
905 let Ok(text) = std::fs::read_to_string(entry.path()) else {
906 continue;
907 };
908 let record = relative.starts_with(&decisions);
909 if record && crate::gates::adr_cites_a_live_rule::superseded(&text) {
912 continue;
913 }
914 let enforced: std::collections::BTreeSet<usize> = if record {
915 crate::gates::adr_cites_a_live_rule::enforced_by(&text)
916 .into_iter()
917 .map(|(number, _)| number)
918 .collect()
919 } else {
920 std::collections::BTreeSet::new()
921 };
922 for (index, line) in text.lines().enumerate() {
923 if line.starts_with("### `") || (record && !enforced.contains(&(index + 1))) {
924 continue;
925 }
926 for id in crate::gates::adr_cites_a_live_rule::cited_ids(line) {
927 let domain = id.split_once(':').map_or(id, |(domain, _)| domain);
928 if domains.contains(domain)
929 && !defined.contains(id)
930 && !shipped.contains(id)
931 && !local.contains(id)
932 {
933 found.push(Citation {
934 path: relative.to_owned(),
935 line: index + 1,
936 id: id.to_string(),
937 });
938 }
939 }
940 }
941 }
942 found
943}
944
945fn finish(
946 target: &Utf8Path,
947 installed: &Installed,
948 reinstalled: crate::services::installer::InitOutcome,
949 outcome: &mut UpgradeOutcome,
950) {
951 let old = installed.version;
952 let new = CanonVersion::current();
953 outcome.lines.extend(
957 reinstalled
958 .lines
959 .into_iter()
960 .filter(|line| line.starts_with("note:")),
961 );
962 report_departures(reinstalled.removed, reinstalled.dropped, "", outcome);
963
964 let local_ids = instance_rule_ids(target, &installed.docs_root);
965 let upstream_only: Vec<String> = crate::embedded::spec_rule_ids()
966 .difference(&local_ids)
967 .cloned()
968 .collect();
969 if !upstream_only.is_empty() {
970 outcome
971 .lines
972 .push("upstream rule IDs not present locally:".to_string());
973 for id in upstream_only {
974 outcome.lines.push(format!(" {id}"));
975 }
976 }
977
978 if outcome.failures > 0 {
979 outcome.lines.push(format!(
980 "FAIL upgraded {old} to {new} with unfinished removals above"
981 ));
982 } else if old == new {
983 outcome
984 .lines
985 .push(if installed.schema_current && installed.adopted_moved {
986 format!("OK recorded the adopted edits at {new}")
987 } else {
988 format!("OK migrated the record of {new}")
989 });
990 } else {
991 outcome.lines.push(format!("OK upgraded {old} to {new}"));
992 }
993}
994
995#[cfg(test)]
996mod tests {
997 use super::*;
998
999 #[test]
1001 fn two_saves_in_one_second_keep_both_copies() {
1002 let dir = tempfile::tempdir().unwrap();
1003 let root = Utf8Path::from_path(dir.path()).unwrap();
1004 let target = root.join("target");
1005 let runs = root.join("snapshots");
1006 let stamp = "20261009T213000Z";
1007
1008 crate::adapters::fs::write_file(&target.join("AGENTS.md"), b"first").unwrap();
1009 let first = crate::adapters::fs::claim_run_dir(&runs, stamp).unwrap();
1010 let kept = save(&target, "AGENTS.md", Some(&first)).unwrap().unwrap();
1011
1012 crate::adapters::fs::write_file(&target.join("AGENTS.md"), b"second").unwrap();
1013 let second = crate::adapters::fs::claim_run_dir(&runs, stamp).unwrap();
1014 let again = save(&target, "AGENTS.md", Some(&second)).unwrap().unwrap();
1015
1016 assert_ne!(kept, again);
1017 assert_eq!(std::fs::read(&kept).unwrap(), b"first");
1018 assert_eq!(std::fs::read(&again).unwrap(), b"second");
1019 }
1020
1021 fn installed() -> Installed {
1023 Installed {
1024 version: CanonVersion::current(),
1025 profile: ProfileId::Codebase,
1026 docs_root: "docs".to_string(),
1027 managed: Vec::new(),
1028 integration: Vec::new(),
1029 adopted_moved: false,
1030 schema_current: true,
1031 }
1032 }
1033
1034 fn record_with_status(status: &str) -> tempfile::TempDir {
1036 let dir = tempfile::tempdir().unwrap();
1037 let root = Utf8Path::from_path(dir.path()).unwrap();
1038 crate::adapters::fs::write_file(
1039 &root.join("docs/decisions/ADR-old-choice.md"),
1040 format!(
1041 "# Old choice\n\n## Status\n\n{status}\n\n## Decision\n\nEnforced by `staging:a-rule-no-release-defines`.\n"
1042 )
1043 .as_bytes(),
1044 )
1045 .unwrap();
1046 dir
1047 }
1048
1049 #[test]
1051 fn a_superseded_record_gives_no_retired_citation() {
1052 let dir = record_with_status("Superseded by [ADR-new-choice](ADR-new-choice.md)");
1053 let target = Utf8Path::from_path(dir.path()).unwrap();
1054 assert!(retired_citations(target, &installed()).is_empty());
1055 }
1056
1057 #[test]
1059 fn a_record_with_no_superseded_line_still_gives_its_retired_citation() {
1060 let dir = record_with_status("Accepted");
1061 let target = Utf8Path::from_path(dir.path()).unwrap();
1062 let found = retired_citations(target, &installed());
1063 assert_eq!(found.len(), 1, "{found:?}");
1064 assert_eq!(found[0].id, "staging:a-rule-no-release-defines");
1065 assert_eq!(found[0].path, "docs/decisions/ADR-old-choice.md");
1066 }
1067}