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}
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
54pub struct Conflict {
55 pub path: String,
57 pub kind: ConflictKind,
59}
60
61impl Conflict {
62 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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
77pub struct Replaced {
78 pub path: String,
80 pub saved_to: Option<Utf8PathBuf>,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
86pub struct Citation {
87 pub path: Utf8PathBuf,
89 pub line: usize,
91 pub id: String,
93}
94
95#[derive(Debug, Default)]
97pub struct UpgradeOutcome {
98 pub lines: Vec<String>,
100 pub failures: usize,
102 pub from: Option<CanonVersion>,
104 pub conflicts: Vec<Conflict>,
106 pub replaced: Vec<Replaced>,
108 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 schema_current: bool,
125}
126
127fn 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
184fn 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
239fn 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
273fn 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
299fn 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
311pub 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 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 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 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 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 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 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
449fn 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 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
483fn 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
501pub(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
540fn 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 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 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
597fn 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
607fn 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
652fn 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
672fn 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
705fn 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 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 #[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}