1use crate::{
3 Error, Manifest, Result,
4 context::HostContext,
5 model::{FileMode, ManagedFile},
6 observation::{self, Entry, Kind},
7 profiles::selected,
8};
9use serde::Serialize;
10use std::{
11 collections::BTreeSet,
12 path::{Path, PathBuf},
13};
14
15#[derive(Debug, Clone, Serialize)]
16#[serde(tag = "operation", rename_all = "snake_case")]
17pub enum Request {
18 Apply,
19 Adopt { mapping: ManagedFile },
20 Unmanage { id: String, mode: UnmanageMode },
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
24#[serde(rename_all = "snake_case")]
25pub enum UnmanageMode {
26 Keep,
27 Remove,
28}
29
30#[derive(Debug, Clone, Serialize)]
31pub struct FileSnapshot {
32 pub mapping: ManagedFile,
33 pub source_path: PathBuf,
34 pub target_path: PathBuf,
35 pub source: Option<Entry>,
36 pub destination: Option<Entry>,
37 pub blockers: Vec<String>,
38}
39
40#[derive(Debug, Clone, Serialize)]
41pub struct InactiveLink {
42 pub id: String,
43 pub target: PathBuf,
44 pub source: PathBuf,
45 pub profiles: Vec<String>,
46}
47
48#[derive(Debug, Clone, Serialize)]
49pub struct Snapshot {
50 pub user_id: u32,
51 pub host: HostContext,
52 pub repository: PathBuf,
53 pub manifest: Entry,
54 pub local_config: Entry,
55 pub active_profiles: BTreeSet<String>,
56 #[serde(skip_serializing_if = "Vec::is_empty")]
57 pub temporary_profiles: Vec<String>,
58 #[serde(skip_serializing_if = "Vec::is_empty")]
59 pub profiles: Vec<crate::profiles::Row>,
60 #[serde(skip_serializing_if = "Vec::is_empty")]
61 pub inactive_links: Vec<InactiveLink>,
62 pub request: Request,
63 pub files: Vec<FileSnapshot>,
64}
65
66pub fn observe(
69 host: &HostContext,
70 repository: &Path,
71 profiles: &[String],
72 request: Request,
73) -> Result<Snapshot> {
74 observe_inner(host, repository, profiles, request, false)
75}
76
77pub(crate) fn observe_environment(
78 host: &HostContext,
79 repository: &Path,
80 profiles: &[String],
81) -> Result<Snapshot> {
82 observe_inner(host, repository, profiles, Request::Apply, true)
83}
84
85fn observe_inner(
86 host: &HostContext,
87 repository: &Path,
88 profiles: &[String],
89 request: Request,
90 environment: bool,
91) -> Result<Snapshot> {
92 observation::validate_output_path(repository)?;
93 let (manifest, manifest_entry) = observation::read_manifest(&repository.join("dort.toml"))?;
94 let config = observation::inspect(&host.local_config_path(), false)?;
95 let rows = manifest.profile_rows(host, Some(repository), profiles)?;
96 let active = crate::profiles::active(&rows);
97 if environment {
98 manifest.validate_file_targets(host, &active, Some(repository), None)?;
99 } else {
100 manifest.validate_selection(host, &active, Some(repository))?;
101 }
102 if let Request::Adopt { mapping } = &request {
103 validate_adoption(&manifest, mapping, host, &active, repository)?;
104 }
105 let mappings: Vec<_> = match &request {
106 Request::Adopt { mapping } => vec![mapping.clone()],
107 Request::Apply => manifest
108 .files
109 .iter()
110 .filter(|f| selected(&f.profiles, &active))
111 .cloned()
112 .collect(),
113 Request::Unmanage { id, .. } => vec![
114 manifest
115 .files
116 .iter()
117 .find(|f| &f.id == id)
118 .cloned()
119 .ok_or_else(|| Error::Invalid(format!("no file mapping: {id}")))?,
120 ],
121 };
122 let mut files = vec![];
123 for mapping in mappings {
124 let source_path = repository.join(
125 mapping
126 .overrides
127 .get(&host.platform)
128 .unwrap_or(&mapping.source),
129 );
130 let target_path = host.target_path(&mapping.target, Some(repository))?;
131 let mut blockers = vec![];
132 if mapping.mode != FileMode::Link {
133 blockers.push(format!(
134 "{:?} deployment is unsupported; never treated as link",
135 mapping.mode
136 ));
137 }
138 if !environment && !mapping.requires.is_empty() {
139 blockers.push(format!(
140 "Requires {}. Choose Review environment in Files, or run dort environment plan.",
141 mapping.requires.join(", ")
142 ));
143 }
144 let hash = blockers.is_empty();
145 let mut capture = |path: &Path| match observation::inspect(path, hash) {
146 Ok(entry) => Some(entry),
147 Err(error) => {
148 blockers.push(error.to_string());
149 None
150 }
151 };
152 let source = capture(&source_path);
153 let destination = capture(&target_path);
154 files.push(FileSnapshot {
155 mapping,
156 source_path,
157 target_path,
158 source,
159 destination,
160 blockers,
161 });
162 }
163 let mut inactive_links = vec![];
164 if matches!(request, Request::Apply) {
165 for mapping in manifest
166 .files
167 .iter()
168 .filter(|f| f.mode == FileMode::Link && !selected(&f.profiles, &active))
169 {
170 let source = repository.join(
171 mapping
172 .overrides
173 .get(&host.platform)
174 .unwrap_or(&mapping.source),
175 );
176 if let Ok(target) = host.target_path(&mapping.target, Some(repository))
177 && let Ok(entry) = observation::inspect(&target, false)
178 && observation::link_path(&entry).as_ref() == Some(&source)
179 {
180 inactive_links.push(InactiveLink {
181 id: mapping.id.clone(),
182 target,
183 source,
184 profiles: mapping.profiles.clone(),
185 });
186 }
187 }
188 inactive_links.sort_by(|a, b| a.id.cmp(&b.id));
189 }
190 let after = observation::inspect(&host.local_config_path(), false)?;
191 if !crate::adoption::same(&config, &after, true) {
192 return Err(Error::Invalid(
193 "local configuration changed during observation".into(),
194 ));
195 }
196 files.sort_by(|a, b| a.mapping.id.cmp(&b.mapping.id));
197 Ok(Snapshot {
198 user_id: rustix::process::geteuid().as_raw(),
199 host: host.clone(),
200 repository: repository.to_owned(),
201 manifest: manifest_entry,
202 local_config: after,
203 active_profiles: active,
204 temporary_profiles: profiles.to_vec(),
205 profiles: rows,
206 inactive_links,
207 request,
208 files,
209 })
210}
211
212fn validate_adoption(
213 manifest: &Manifest,
214 mapping: &ManagedFile,
215 host: &HostContext,
216 active: &BTreeSet<String>,
217 repository: &Path,
218) -> Result<()> {
219 let mut candidate = manifest.clone();
220 candidate.files.push(mapping.clone());
221 candidate.validate_selection(host, active, Some(repository))?;
222 if !selected(&mapping.profiles, active) {
223 return Err(Error::Invalid("adoption mapping must be active".into()));
224 }
225 if !mapping.overrides.is_empty() {
226 return Err(Error::Invalid(
227 "adoption cannot create platform overrides".into(),
228 ));
229 }
230 for existing in &manifest.files {
231 for source in std::iter::once(&existing.source).chain(existing.overrides.values()) {
232 if source.starts_with(&mapping.source) || mapping.source.starts_with(source) {
233 return Err(Error::Invalid(
234 "Source overlaps an existing mapping. Choose a different repository source."
235 .into(),
236 ));
237 }
238 }
239 }
240 Ok(())
241}
242
243#[derive(Debug, Clone, Serialize)]
244#[serde(tag = "action", rename_all = "snake_case")]
245pub enum Effect {
246 Backup {
247 path: PathBuf,
248 },
249 EnsureParents {
250 path: PathBuf,
251 permissions: String,
252 },
253 CopySource {
254 from: PathBuf,
255 to: PathBuf,
256 permissions: String,
257 },
258 AddMapping {
259 manifest: PathBuf,
260 mapping: ManagedFile,
261 },
262 RemoveMapping {
263 manifest: PathBuf,
264 id: String,
265 },
266 Link {
267 target: PathBuf,
268 source: PathBuf,
269 },
270 Materialize {
271 source: PathBuf,
272 target: PathBuf,
273 permissions: String,
274 },
275 RemoveDestination {
276 target: PathBuf,
277 },
278}
279
280#[derive(Debug, Clone, Serialize)]
281#[serde(rename_all = "snake_case")]
282pub enum Outcome {
283 Change,
284 NoOp,
285 Blocked,
286}
287
288#[derive(Debug, Clone, Serialize)]
289pub struct FilePlan {
290 pub id: String,
291 pub outcome: Outcome,
292 pub effects: Vec<Effect>,
293 pub blockers: Vec<String>,
294 pub destructive: bool,
295 pub requires_removal_acknowledgement: bool,
296}
297
298#[derive(Debug, Clone, Serialize)]
299pub struct Plan {
300 pub schema: u32,
301 pub preview_only: bool,
302 pub inputs: Snapshot,
303 pub files: Vec<FilePlan>,
304 pub warnings: Vec<String>,
305}
306
307fn regular(entry: &Entry, label: &str, user_id: u32, blockers: &mut Vec<String>) {
308 if entry.kind != Kind::Regular {
309 blockers.push(format!(
310 "{label} must be a regular file (found {:?})",
311 entry.kind
312 ));
313 return;
314 }
315 if entry
316 .fingerprint
317 .as_ref()
318 .is_none_or(|f| f.links != 1 || f.uid != user_id || f.mode & 0o7000 != 0)
319 {
320 blockers.push(format!(
321 "{label} must be owned by this user, single-link, without special permission bits"
322 ));
323 }
324 if entry.sensitive {
325 blockers.push(format!(
326 "{label} appears sensitive; ordinary link/adoption is refused"
327 ));
328 }
329 if entry.sha256.is_none() {
330 blockers.push(format!("{label} has no safe content fingerprint"));
331 }
332}
333
334fn permissions(entry: &Entry) -> String {
335 format!(
336 "{:04o}",
337 entry.fingerprint.as_ref().map_or(0, |f| f.mode & 0o777)
338 )
339}
340
341pub fn plan(snapshot: Snapshot) -> Plan {
343 plan_inner(snapshot, false)
344}
345
346pub(crate) fn plan_environment(snapshot: Snapshot) -> Plan {
347 plan_inner(snapshot, true)
348}
349
350fn plan_inner(snapshot: Snapshot, environment: bool) -> Plan {
351 let mut files = vec![];
352 let manifest = snapshot.manifest.path.clone();
353 for file in &snapshot.files {
354 let mut result = FilePlan {
355 id: file.mapping.id.clone(),
356 outcome: Outcome::Change,
357 effects: vec![],
358 blockers: file.blockers.clone(),
359 destructive: false,
360 requires_removal_acknowledgement: false,
361 };
362 if file.mapping.mode != FileMode::Link {
363 result.blockers.push("only link mode is supported".into());
364 }
365 if !environment && !file.mapping.requires.is_empty() {
366 result
367 .blockers
368 .push("tool prerequisite verification is unsupported".into());
369 }
370 if let (Some(source), Some(destination)) = (&file.source, &file.destination) {
371 if destination.sensitive {
372 result.blockers.push(
373 "destination appears sensitive; ordinary link operations are refused".into(),
374 );
375 }
376 if destination
377 .fingerprint
378 .as_ref()
379 .is_some_and(|f| f.links != 1 || f.uid != snapshot.user_id)
380 {
381 result
382 .blockers
383 .push("destination must be owned by this user and not hard-linked".into());
384 }
385 match &snapshot.request {
386 Request::Adopt { .. } => {
387 if source.kind != Kind::Missing {
388 result
389 .blockers
390 .push("adoption source must not exist".into());
391 }
392 regular(
393 destination,
394 "destination",
395 snapshot.user_id,
396 &mut result.blockers,
397 );
398 if observation::sensitive_path(&file.source_path) {
399 result
400 .blockers
401 .push("adoption source path appears sensitive".into());
402 }
403 result.destructive = true;
404 result.effects = vec![
405 Effect::Backup {
406 path: manifest.clone(),
407 },
408 Effect::EnsureParents {
409 path: file.source_path.clone(),
410 permissions: "0700".into(),
411 },
412 Effect::CopySource {
413 from: file.target_path.clone(),
414 to: file.source_path.clone(),
415 permissions: permissions(destination),
416 },
417 Effect::AddMapping {
418 manifest: manifest.clone(),
419 mapping: file.mapping.clone(),
420 },
421 Effect::Backup {
422 path: file.target_path.clone(),
423 },
424 Effect::Link {
425 target: file.target_path.clone(),
426 source: file.source_path.clone(),
427 },
428 ];
429 }
430 Request::Apply => {
431 regular(source, "source", snapshot.user_id, &mut result.blockers);
432 if destination.kind == Kind::Symlink
433 && observation::link_path(destination).as_ref() == Some(&file.source_path)
434 {
435 result.outcome = Outcome::NoOp;
436 } else {
437 match destination.kind {
438 Kind::Missing => {},
439 Kind::Regular => {
440 regular(destination, "destination", snapshot.user_id, &mut result.blockers);
441 result.effects.push(Effect::Backup { path: file.target_path.clone() });
442 result.destructive = true;
443 }
444 _ => result.blockers.push("destination is a foreign/broken link, directory or special file; replacement is refused".into()),
445 }
446 result.effects.push(Effect::EnsureParents {
447 path: file.target_path.clone(),
448 permissions: "0700".into(),
449 });
450 result.effects.push(Effect::Link {
451 target: file.target_path.clone(),
452 source: file.source_path.clone(),
453 });
454 }
455 }
456 Request::Unmanage { mode, .. } => {
457 regular(source, "source", snapshot.user_id, &mut result.blockers);
458 if destination.kind != Kind::Symlink
459 || observation::link_path(destination).as_ref() != Some(&file.source_path)
460 {
461 result.blockers.push("unmanage requires the currently correct managed link; destination drift is refused".into());
462 }
463 result.destructive = true;
464 result.requires_removal_acknowledgement = *mode == UnmanageMode::Remove;
465 result.effects.push(Effect::Backup {
466 path: manifest.clone(),
467 });
468 result.effects.push(Effect::Backup {
469 path: file.target_path.clone(),
470 });
471 result.effects.push(match mode {
472 UnmanageMode::Keep => Effect::Materialize {
473 source: file.source_path.clone(),
474 target: file.target_path.clone(),
475 permissions: permissions(source),
476 },
477 UnmanageMode::Remove => Effect::RemoveDestination {
478 target: file.target_path.clone(),
479 },
480 });
481 result.effects.push(Effect::RemoveMapping {
482 manifest: manifest.clone(),
483 id: file.mapping.id.clone(),
484 });
485 }
486 }
487 } else if result.blockers.is_empty() {
488 result.blockers.push("incomplete observation".into());
489 }
490 if !result.blockers.is_empty() {
491 result.outcome = Outcome::Blocked;
492 result.effects.clear();
493 result.destructive = false;
494 result.requires_removal_acknowledgement = false;
495 }
496 files.push(result);
497 }
498 Plan { schema: 1, preview_only: true, inputs: snapshot, files, warnings: vec!["Preview only: planning creates no backups or journals. Core execution requires explicit approval, the writer lock and independent re-observation.".into(), "Backups must be durable and transaction intent persisted before destructive effects. Adoption's source copy, manifest edit and link replacement are one recoverable transaction, not independent writes.".into(), "Sensitivity checks are heuristic. Review content privately before adoption; no file contents are printed. Unmanage always retains the repository source.".into()] }
499}
500
501impl Plan {
502 pub fn has_blockers(&self) -> bool {
503 self.files.iter().any(|f| !f.blockers.is_empty())
504 }
505
506 pub fn human(&self) -> String {
507 use std::fmt::Write;
508 let mut text = String::from("Read-only plan (schema 1; not executable)\n");
509 for row in &self.inputs.profiles {
510 let _ = writeln!(text, "Profile {}", row.label());
511 }
512 for link in &self.inputs.inactive_links {
513 let _ = writeln!(
514 text,
515 "{}: No longer selected. Keep {} in place. Profiles: {}",
516 link.id,
517 link.target.display(),
518 link.profiles.join(", ")
519 );
520 }
521 for file in &self.files {
522 let _ = writeln!(text, "{}: {:?}", file.id, file.outcome);
523 if let Some(input) = self
524 .inputs
525 .files
526 .iter()
527 .find(|input| input.mapping.id == file.id)
528 {
529 let _ = writeln!(
530 text,
531 " Source: {} (permissions: {})",
532 input.source_path.display(),
533 input
534 .source
535 .as_ref()
536 .filter(|e| e.fingerprint.is_some())
537 .map_or("absent/unknown".into(), permissions)
538 );
539 let _ = writeln!(
540 text,
541 " Destination: {} (permissions: {})",
542 input.target_path.display(),
543 input
544 .destination
545 .as_ref()
546 .filter(|e| e.fingerprint.is_some())
547 .map_or("absent/unknown".into(), permissions)
548 );
549 }
550 for blocker in &file.blockers {
551 let _ = writeln!(text, " BLOCKED: {blocker}");
552 }
553 for effect in &file.effects {
554 let _ = writeln!(text, " {effect:?}");
555 }
556 if file.destructive {
557 text.push_str(
558 " Destructive destination replacement/removal; durable backup required.\n",
559 );
560 }
561 if file.requires_removal_acknowledgement {
562 text.push_str(" Separate destructive-removal acknowledgement required.\n");
563 }
564 }
565 for warning in &self.warnings {
566 let _ = writeln!(text, "Warning: {warning}");
567 }
568 text
569 }
570}