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 Snapshot {
42 pub user_id: u32,
43 pub host: HostContext,
44 pub repository: PathBuf,
45 pub manifest: Entry,
46 pub local_config: Entry,
47 pub active_profiles: BTreeSet<String>,
48 pub request: Request,
49 pub files: Vec<FileSnapshot>,
50}
51
52pub fn observe(
55 host: &HostContext,
56 repository: &Path,
57 profiles: &[String],
58 request: Request,
59) -> Result<Snapshot> {
60 observation::validate_output_path(repository)?;
61 let (manifest, manifest_entry) = observation::read_manifest(&repository.join("dort.toml"))?;
62 let active = manifest.validate_for_host(host, profiles, Some(repository))?;
63 if let Request::Adopt { mapping } = &request {
64 validate_adoption(&manifest, mapping, host, profiles, repository)?;
65 }
66 let mappings: Vec<_> = match &request {
67 Request::Adopt { mapping } => vec![mapping.clone()],
68 Request::Apply => manifest
69 .files
70 .iter()
71 .filter(|f| selected(&f.profiles, &active))
72 .cloned()
73 .collect(),
74 Request::Unmanage { id, .. } => vec![
75 manifest
76 .files
77 .iter()
78 .find(|f| &f.id == id && selected(&f.profiles, &active))
79 .cloned()
80 .ok_or_else(|| Error::Invalid(format!("no active file mapping: {id}")))?,
81 ],
82 };
83 let mut files = vec![];
84 for mapping in mappings {
85 let source_path = repository.join(
86 mapping
87 .overrides
88 .get(&host.platform)
89 .unwrap_or(&mapping.source),
90 );
91 let target_path = host.target_path(&mapping.target, Some(repository))?;
92 let mut blockers = vec![];
93 if mapping.mode != FileMode::Link {
94 blockers.push(format!(
95 "{:?} deployment is unsupported; never treated as link",
96 mapping.mode
97 ));
98 }
99 if !mapping.requires.is_empty() {
100 blockers.push("tool prerequisites cannot yet be verified".into());
101 }
102 let hash = blockers.is_empty();
103 let mut capture = |path: &Path| match observation::inspect(path, hash) {
104 Ok(entry) => Some(entry),
105 Err(error) => {
106 blockers.push(error.to_string());
107 None
108 }
109 };
110 let source = capture(&source_path);
111 let destination = capture(&target_path);
112 files.push(FileSnapshot {
113 mapping,
114 source_path,
115 target_path,
116 source,
117 destination,
118 blockers,
119 });
120 }
121 files.sort_by(|a, b| a.mapping.id.cmp(&b.mapping.id));
122 Ok(Snapshot {
123 user_id: rustix::process::geteuid().as_raw(),
124 host: host.clone(),
125 repository: repository.to_owned(),
126 manifest: manifest_entry,
127 local_config: observation::inspect(&host.local_config_path(), false)?,
128 active_profiles: active,
129 request,
130 files,
131 })
132}
133
134fn validate_adoption(
135 manifest: &Manifest,
136 mapping: &ManagedFile,
137 host: &HostContext,
138 profiles: &[String],
139 repository: &Path,
140) -> Result<()> {
141 let mut candidate = manifest.clone();
142 candidate.files.push(mapping.clone());
143 let active = candidate.validate_for_host(host, profiles, Some(repository))?;
144 if !selected(&mapping.profiles, &active) {
145 return Err(Error::Invalid("adoption mapping must be active".into()));
146 }
147 if !mapping.overrides.is_empty() {
148 return Err(Error::Invalid(
149 "adoption cannot create platform overrides".into(),
150 ));
151 }
152 for existing in &manifest.files {
153 for source in std::iter::once(&existing.source).chain(existing.overrides.values()) {
154 if source.starts_with(&mapping.source) || mapping.source.starts_with(source) {
155 return Err(Error::Invalid(
156 "adoption source overlaps an existing mapping".into(),
157 ));
158 }
159 }
160 }
161 Ok(())
162}
163
164#[derive(Debug, Clone, Serialize)]
165#[serde(tag = "action", rename_all = "snake_case")]
166pub enum Effect {
167 Backup {
168 path: PathBuf,
169 },
170 EnsureParents {
171 path: PathBuf,
172 permissions: String,
173 },
174 CopySource {
175 from: PathBuf,
176 to: PathBuf,
177 permissions: String,
178 },
179 AddMapping {
180 manifest: PathBuf,
181 mapping: ManagedFile,
182 },
183 RemoveMapping {
184 manifest: PathBuf,
185 id: String,
186 },
187 Link {
188 target: PathBuf,
189 source: PathBuf,
190 },
191 Materialize {
192 source: PathBuf,
193 target: PathBuf,
194 permissions: String,
195 },
196 RemoveDestination {
197 target: PathBuf,
198 },
199}
200
201#[derive(Debug, Clone, Serialize)]
202#[serde(rename_all = "snake_case")]
203pub enum Outcome {
204 Change,
205 NoOp,
206 Blocked,
207}
208
209#[derive(Debug, Clone, Serialize)]
210pub struct FilePlan {
211 pub id: String,
212 pub outcome: Outcome,
213 pub effects: Vec<Effect>,
214 pub blockers: Vec<String>,
215 pub destructive: bool,
216 pub requires_removal_acknowledgement: bool,
217}
218
219#[derive(Debug, Clone, Serialize)]
220pub struct Plan {
221 pub schema: u32,
222 pub preview_only: bool,
223 pub inputs: Snapshot,
224 pub files: Vec<FilePlan>,
225 pub warnings: Vec<String>,
226}
227
228fn regular(entry: &Entry, label: &str, user_id: u32, blockers: &mut Vec<String>) {
229 if entry.kind != Kind::Regular {
230 blockers.push(format!(
231 "{label} must be a regular file (found {:?})",
232 entry.kind
233 ));
234 return;
235 }
236 if entry
237 .fingerprint
238 .as_ref()
239 .is_none_or(|f| f.links != 1 || f.uid != user_id || f.mode & 0o7000 != 0)
240 {
241 blockers.push(format!(
242 "{label} must be owned by this user, single-link, without special permission bits"
243 ));
244 }
245 if entry.sensitive {
246 blockers.push(format!(
247 "{label} appears sensitive; ordinary link/adoption is refused"
248 ));
249 }
250 if entry.sha256.is_none() {
251 blockers.push(format!("{label} has no safe content fingerprint"));
252 }
253}
254
255fn permissions(entry: &Entry) -> String {
256 format!(
257 "{:04o}",
258 entry.fingerprint.as_ref().map_or(0, |f| f.mode & 0o777)
259 )
260}
261
262pub fn plan(snapshot: Snapshot) -> Plan {
264 let mut files = vec![];
265 let manifest = snapshot.manifest.path.clone();
266 for file in &snapshot.files {
267 let mut result = FilePlan {
268 id: file.mapping.id.clone(),
269 outcome: Outcome::Change,
270 effects: vec![],
271 blockers: file.blockers.clone(),
272 destructive: false,
273 requires_removal_acknowledgement: false,
274 };
275 if file.mapping.mode != FileMode::Link {
276 result.blockers.push("only link mode is supported".into());
277 }
278 if !file.mapping.requires.is_empty() {
279 result
280 .blockers
281 .push("tool prerequisite verification is unsupported".into());
282 }
283 if let (Some(source), Some(destination)) = (&file.source, &file.destination) {
284 if destination.sensitive {
285 result.blockers.push(
286 "destination appears sensitive; ordinary link operations are refused".into(),
287 );
288 }
289 if destination
290 .fingerprint
291 .as_ref()
292 .is_some_and(|f| f.links != 1 || f.uid != snapshot.user_id)
293 {
294 result
295 .blockers
296 .push("destination must be owned by this user and not hard-linked".into());
297 }
298 match &snapshot.request {
299 Request::Adopt { .. } => {
300 if source.kind != Kind::Missing {
301 result
302 .blockers
303 .push("adoption source must not exist".into());
304 }
305 regular(
306 destination,
307 "destination",
308 snapshot.user_id,
309 &mut result.blockers,
310 );
311 if observation::sensitive_path(&file.source_path) {
312 result
313 .blockers
314 .push("adoption source path appears sensitive".into());
315 }
316 result.destructive = true;
317 result.effects = vec![
318 Effect::Backup {
319 path: manifest.clone(),
320 },
321 Effect::EnsureParents {
322 path: file.source_path.clone(),
323 permissions: "0700".into(),
324 },
325 Effect::CopySource {
326 from: file.target_path.clone(),
327 to: file.source_path.clone(),
328 permissions: permissions(destination),
329 },
330 Effect::AddMapping {
331 manifest: manifest.clone(),
332 mapping: file.mapping.clone(),
333 },
334 Effect::Backup {
335 path: file.target_path.clone(),
336 },
337 Effect::Link {
338 target: file.target_path.clone(),
339 source: file.source_path.clone(),
340 },
341 ];
342 }
343 Request::Apply => {
344 regular(source, "source", snapshot.user_id, &mut result.blockers);
345 if destination.kind == Kind::Symlink
346 && observation::link_path(destination).as_ref() == Some(&file.source_path)
347 {
348 result.outcome = Outcome::NoOp;
349 } else {
350 match destination.kind {
351 Kind::Missing => {},
352 Kind::Regular => {
353 regular(destination, "destination", snapshot.user_id, &mut result.blockers);
354 result.effects.push(Effect::Backup { path: file.target_path.clone() });
355 result.destructive = true;
356 }
357 _ => result.blockers.push("destination is a foreign/broken link, directory or special file; replacement is refused".into()),
358 }
359 result.effects.push(Effect::EnsureParents {
360 path: file.target_path.clone(),
361 permissions: "0700".into(),
362 });
363 result.effects.push(Effect::Link {
364 target: file.target_path.clone(),
365 source: file.source_path.clone(),
366 });
367 }
368 }
369 Request::Unmanage { mode, .. } => {
370 regular(source, "source", snapshot.user_id, &mut result.blockers);
371 if destination.kind != Kind::Symlink
372 || observation::link_path(destination).as_ref() != Some(&file.source_path)
373 {
374 result.blockers.push("unmanage requires the currently correct managed link; destination drift is refused".into());
375 }
376 result.destructive = true;
377 result.requires_removal_acknowledgement = *mode == UnmanageMode::Remove;
378 result.effects.push(Effect::Backup {
379 path: manifest.clone(),
380 });
381 result.effects.push(Effect::Backup {
382 path: file.target_path.clone(),
383 });
384 result.effects.push(match mode {
385 UnmanageMode::Keep => Effect::Materialize {
386 source: file.source_path.clone(),
387 target: file.target_path.clone(),
388 permissions: permissions(source),
389 },
390 UnmanageMode::Remove => Effect::RemoveDestination {
391 target: file.target_path.clone(),
392 },
393 });
394 result.effects.push(Effect::RemoveMapping {
395 manifest: manifest.clone(),
396 id: file.mapping.id.clone(),
397 });
398 }
399 }
400 } else if result.blockers.is_empty() {
401 result.blockers.push("incomplete observation".into());
402 }
403 if !result.blockers.is_empty() {
404 result.outcome = Outcome::Blocked;
405 result.effects.clear();
406 result.destructive = false;
407 result.requires_removal_acknowledgement = false;
408 }
409 files.push(result);
410 }
411 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()] }
412}
413
414impl Plan {
415 pub fn has_blockers(&self) -> bool {
416 self.files.iter().any(|f| !f.blockers.is_empty())
417 }
418
419 pub fn human(&self) -> String {
420 use std::fmt::Write;
421 let mut text = String::from("Read-only plan (schema 1; not executable)\n");
422 for file in &self.files {
423 let _ = writeln!(text, "{}: {:?}", file.id, file.outcome);
424 if let Some(input) = self
425 .inputs
426 .files
427 .iter()
428 .find(|input| input.mapping.id == file.id)
429 {
430 let _ = writeln!(
431 text,
432 " Source: {} (permissions: {})",
433 input.source_path.display(),
434 input
435 .source
436 .as_ref()
437 .filter(|e| e.fingerprint.is_some())
438 .map_or("absent/unknown".into(), permissions)
439 );
440 let _ = writeln!(
441 text,
442 " Destination: {} (permissions: {})",
443 input.target_path.display(),
444 input
445 .destination
446 .as_ref()
447 .filter(|e| e.fingerprint.is_some())
448 .map_or("absent/unknown".into(), permissions)
449 );
450 }
451 for blocker in &file.blockers {
452 let _ = writeln!(text, " BLOCKED: {blocker}");
453 }
454 for effect in &file.effects {
455 let _ = writeln!(text, " {effect:?}");
456 }
457 if file.destructive {
458 text.push_str(
459 " Destructive destination replacement/removal; durable backup required.\n",
460 );
461 }
462 if file.requires_removal_acknowledgement {
463 text.push_str(" Separate destructive-removal acknowledgement required.\n");
464 }
465 }
466 for warning in &self.warnings {
467 let _ = writeln!(text, "Warning: {warning}");
468 }
469 text
470 }
471}