dort 0.1.0

Experimental, TUI-first local dotfile manager with guarded recovery
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
//! UI-independent action preparation and dispatch over the existing core services.
use crate::services::{BootstrapApproval, BootstrapPreview, FileApproval};
use dort_core::{
    Error, Result,
    adoption::Event,
    bootstrap,
    context::HostContext,
    journal,
    local::LocalConfig,
    planner::{self, Plan, Request, UnmanageMode},
    recovery,
    state::WriterLock,
};
use std::path::{Path, PathBuf};

pub struct ManagedRow {
    pub id: String,
    pub source: PathBuf,
    pub target: PathBuf,
    pub state: &'static str,
    pub source_kind: &'static str,
    pub target_kind: &'static str,
    pub blockers: Vec<String>,
}

fn entry_kind(entry: Option<&dort_core::observation::Entry>) -> &'static str {
    use dort_core::observation::Kind;
    match entry.map(|e| &e.kind) {
        Some(Kind::Missing) => "Missing",
        Some(Kind::Regular) => "Regular file",
        Some(Kind::Directory) => "Directory",
        Some(Kind::Symlink) => "Symbolic link",
        Some(Kind::Special) => "Special file",
        None => "Unavailable",
    }
}
/// Read-only summary facts, never reconstructed from human report strings.
pub struct Overview {
    pub host: HostContext,
    pub registered: Option<bool>,
    pub registry_count: Option<usize>,
    pub configuration_error: Option<String>,
    pub files: Option<FileCounts>,
}
#[derive(Default)]
pub struct FileCounts {
    pub linked: usize,
    pub changes: usize,
    pub blocked: usize,
    pub plan_blocked: bool,
}
#[derive(Default)]
pub struct Data {
    pub overview: Option<Overview>,
    pub repository: Option<PathBuf>,
    pub known_roots: Vec<PathBuf>,
    pub profiles: Vec<String>,
    pub files: Vec<(String, String)>,
    pub managed: Vec<ManagedRow>,
    pub files_error: Option<String>,
    pub history: Vec<journal::Diagnosis>,
    pub history_error: Option<String>,
}

// TOML parser Display includes source lines. Ordinary TUI errors are metadata only.
pub fn diagnostic(error: &Error) -> String {
    match error {
        Error::Parse(_) => "Invalid TOML; manifest source text is not displayed.".into(),
        _ => error.to_string(),
    }
}

/// Deferred quit returns through CLI error presentation after terminal restoration.
pub fn exit_error(error: Error) -> Error {
    if matches!(error, Error::Parse(_)) {
        Error::Invalid(diagnostic(&error))
    } else {
        error
    }
}

#[cfg(test)]
pub fn load(host: &HostContext, repository: Option<&Path>) -> Result<Data> {
    load_scoped(host, repository, &[])
}
pub fn load_scoped(
    host: &HostContext,
    repository: Option<&Path>,
    requested: &[String],
) -> Result<Data> {
    let (history, history_error) = match journal::diagnose(host) {
        Ok(rows) => (rows, None),
        Err(error) => (vec![], Some(diagnostic(&error))),
    };
    let mut overview = Overview {
        host: host.clone(),
        registered: None,
        registry_count: None,
        configuration_error: None,
        files: None,
    };
    let local = LocalConfig::load(host);
    let mut files = vec![];
    let mut managed = vec![];
    let mut files_error = None;
    let mut known_roots = vec![];
    let mut profiles = vec![];
    let mut selected = None;
    match local {
        Err(error) => {
            let error = diagnostic(&error);
            files_error = Some(format!("Configuration unavailable: {error}"));
            overview.configuration_error = Some(error);
        }
        Ok(local) => {
            overview.registry_count = Some(local.repositories.len());
            known_roots = local
                .repositories
                .values()
                .map(|record| record.root.clone())
                .collect();
            match local.select_repository(repository) {
                Err(error) => {
                    let error = diagnostic(&error);
                    files_error = Some(format!(
                        "{error}\nChoose repository or Create/attach in Actions."
                    ));
                }
                Ok(root) => {
                    let registered = known_roots.contains(&root);
                    overview.registered = Some(registered);
                    selected = Some(root.clone());
                    match crate::services::observe(
                        host,
                        &local,
                        Some(&root),
                        requested,
                        Request::Apply,
                    ) {
                        Err(error) => {
                            let error = diagnostic(&error);
                            files_error = Some(format!("File observation failed: {error}"));
                        }
                        Ok(snapshot) => {
                            profiles = snapshot.active_profiles.iter().cloned().collect();
                            let plan = planner::plan(snapshot);
                            let mut counts = FileCounts {
                                plan_blocked: plan.has_blockers(),
                                ..Default::default()
                            };
                            for file in &plan.files {
                                match file.outcome {
                                    planner::Outcome::NoOp => counts.linked += 1,
                                    planner::Outcome::Change => counts.changes += 1,
                                    planner::Outcome::Blocked => counts.blocked += 1,
                                }
                            }
                            overview.files = Some(counts);
                            for (file, input) in plan.files.iter().zip(&plan.inputs.files) {
                                managed.push(ManagedRow {
                                    id: file.id.clone(),
                                    source: input.source_path.clone(),
                                    target: input.target_path.clone(),
                                    source_kind: entry_kind(input.source.as_ref()),
                                    target_kind: entry_kind(input.destination.as_ref()),
                                    state: match file.outcome {
                                        planner::Outcome::NoOp => "Linked",
                                        planner::Outcome::Change => "Needs apply",
                                        planner::Outcome::Blocked => "Blocked",
                                    },
                                    blockers: file.blockers.clone(),
                                });
                                files.push((
                                    file.id.clone(),
                                    format!(
                                        "{} [{:?}]\nSource: {:?} [{:?}]\nTarget: {:?} [{:?}]\n{}",
                                        file.id,
                                        file.outcome,
                                        input.source_path,
                                        input.source.as_ref().map(|e| &e.kind),
                                        input.target_path,
                                        input.destination.as_ref().map(|e| &e.kind),
                                        file.blockers.join("\n")
                                    ),
                                ));
                            }
                        }
                    }
                }
            }
        }
    }
    Ok(Data {
        overview: Some(overview),
        repository: selected,
        known_roots,
        profiles,
        files,
        managed,
        files_error,
        history,
        history_error,
    })
}

pub enum Pending {
    Ignore(dort_core::discovery_ignore::Preview),
    Files(Box<Plan>),
    Batch(Box<dort_core::batch::Plan>),
    Init(Box<BootstrapPreview>),
    Rollback(recovery::Preview),
    Bootstrap(bootstrap::RecoveryPreview),
}
impl Pending {
    pub fn report(&self) -> Result<String> {
        Ok(match self {
            Self::Ignore(preview) => preview.human(),
            Self::Batch(plan) => plan.human(),
            Self::Files(plan) => format!(
                "Repository: {:?}\nEffective profiles: {:?}\nScope: all mappings selected by this request; the preview defines execution scope.\n{}",
                plan.inputs.repository,
                plan.inputs.active_profiles,
                plan.human()
            ),
            Self::Init(preview) => format!(
                "{} local repository\nResolved path: {:?}\nRepository ID: {}\n\nEffects:\n- {}\n\nRegistration and active selection are persistent only after approval.\nPrivate artifacts are retained on failure; inspect Recovery.\nExisting live dotfiles remain in place.",
                if preview.report.create {
                    "Create"
                } else {
                    "Attach"
                },
                preview.report.repository,
                preview.report.repository_id,
                preview.report.effects.join("\n- ")
            ),
            Self::Rollback(preview) => format!(
                "Rollback schema {}\nRepository ID: {}\nTransaction ID: {}\nJournal head: {}\nInverse paths:\n{}\nLater edits can block execution. Schema-1 rollback withdraws its new source into private transaction storage; schema-2 leaves repository sources unchanged. Private backups and artifacts are retained.",
                preview.journal_schema,
                preview.repository_id,
                preview.transaction_id,
                preview.journal_head_sha256,
                preview
                    .effects
                    .iter()
                    .map(|p| format!("- {p:?}"))
                    .collect::<Vec<_>>()
                    .join("\n")
            ),
            Self::Bootstrap(preview) => format!(
                "{} bootstrap\nRepository: {:?}\nRepository ID: {}\nTransaction ID: {}\nJournal head: {}\nRepository published: {}\nRegistration published: {}\nEffects:\n- {}\nAbandon retains published repositories, registration and private artifacts. Published state remains available.\nResume publishes only the exact retained preparation; later changes can block execution. Preparing transactions must be abandoned before retrying Create/attach with a new transaction. Existing live dotfiles remain in place.",
                match preview.action {
                    bootstrap::RecoveryAction::Resume => "Resume",
                    bootstrap::RecoveryAction::Abandon => "Abandon",
                },
                preview.repository,
                preview.repository_id,
                preview.transaction_id,
                preview.journal_head_sha256,
                preview.repository_published,
                preview.registration_published,
                preview.effects.join("\n- ")
            ),
        })
    }
    pub fn adoption(&self) -> bool {
        match self {
            Self::Files(p) => matches!(p.inputs.request, Request::Adopt { .. }),
            Self::Batch(p) => p.inputs.action == dort_core::batch::Action::Adopt,
            _ => false,
        }
    }
    pub fn review_len(&self) -> Option<usize> {
        match self {
            Self::Files(p) => Some(p.files.len()),
            Self::Batch(p) => Some(p.items.iter().map(|i| i.files.len()).sum()),
            _ => None,
        }
    }
    pub fn removal_id(&self) -> Option<&str> {
        match self {
            Self::Files(plan) => match &plan.inputs.request {
                Request::Unmanage {
                    id,
                    mode: UnmanageMode::Remove,
                } => Some(id),
                _ => None,
            },
            _ => None,
        }
    }
    pub fn blocked(&self) -> bool {
        match self {
            Self::Files(plan) => plan.has_blockers(),
            Self::Batch(plan) => plan.has_blockers(),
            _ => false,
        }
    }
    pub fn approve(self, removal: Option<&str>) -> Result<Approved> {
        match self {
            Self::Ignore(preview) => Ok(Approved::Ignore(preview.approve())),
            Self::Batch(plan) => {
                dort_core::batch::Approval::from_plan(*plan).map(|a| Approved::Batch(Box::new(a)))
            }
            Self::Files(plan) => FileApproval::from_plan(*plan, removal)
                .map(|approval| Approved::Files(Box::new(approval))),
            Self::Init(preview) => {
                let root = preview.report.repository.clone();
                Ok(Approved::Init(Box::new((*preview).approve()?), root))
            }
            Self::Rollback(p) => {
                let tid = p.transaction_id.clone();
                recovery::Approval::from_preview(p)
                    .map(|approval| Approved::Rollback(approval, tid))
            }
            Self::Bootstrap(p) => {
                let tid = p.transaction_id.clone();
                bootstrap::RecoveryApproval::from_preview(p)
                    .map(|approval| Approved::Bootstrap(approval, tid))
            }
        }
    }
}

pub enum Approved {
    Ignore(dort_core::discovery_ignore::Approval),
    Files(Box<FileApproval>),
    Batch(Box<dort_core::batch::Approval>),
    Init(Box<BootstrapApproval>, PathBuf),
    Rollback(recovery::Approval, String),
    Bootstrap(bootstrap::RecoveryApproval, String),
}
pub struct Completion {
    pub operation: &'static str,
    pub transaction_id: Option<String>,
    pub repository: Option<PathBuf>,
}
impl Approved {
    pub fn execute(
        self,
        host: &HostContext,
        observer: impl FnMut(&Event) -> Result<()>,
    ) -> Result<Completion> {
        let (operation, transaction_id, repository) = match self {
            Self::Ignore(approval) => {
                approval.execute(host, false)?;
                ("Discovery preferences", None, None)
            }
            Self::Batch(approval) => {
                let lock = WriterLock::acquire(host)?;
                (
                    "Batch file operation",
                    dort_core::batch::execute(host, &lock, *approval, observer)?,
                    None,
                )
            }
            Self::Files(approval) => ("File operation", (*approval).execute(host, observer)?, None),
            Self::Init(approval, root) => (
                "Create/attach",
                Some((*approval).execute(host, observer)?),
                Some(root),
            ),
            Self::Rollback(approval, tid) => {
                let lock = WriterLock::acquire(host)?;
                recovery::execute_with_observer(host, &lock, approval, observer)?;
                ("Rollback", Some(tid), None)
            }
            Self::Bootstrap(approval, tid) => {
                let lock = WriterLock::acquire(host)?;
                bootstrap::recover(host, &lock, approval, observer)?;
                ("Bootstrap recovery", Some(tid), None)
            }
        };
        Ok(Completion {
            operation,
            transaction_id,
            repository,
        })
    }
}

pub struct Diagnostics {
    pub host: HostContext,
    pub registry: std::result::Result<crate::services::DoctorReport, String>,
    pub history: std::result::Result<(usize, usize), String>,
}

/// Retain intent only, never an approval or an executable preview.
#[derive(Clone)]
pub enum Retry {
    Check(Option<PathBuf>, Vec<String>),
    Profiles(Option<PathBuf>, Vec<String>, bool),
    Discover,
    Select(Option<PathBuf>),
    History,
    Diagnostics,
    Refresh,
    Files(Request),
    Batch(dort_core::batch::Request),
    Init(PathBuf, PathBuf),
    Rollback(String, String),
    Bootstrap(String, String, bootstrap::RecoveryAction),
}
impl Retry {
    pub fn task(self) -> Task {
        match self {
            Self::Check(manifest, requested) => Task::Check {
                manifest,
                requested,
            },
            Self::Profiles(manifest, requested, apply) => Task::Profiles {
                manifest,
                requested,
                apply,
            },
            Self::Discover => Task::Discover,
            Self::Select(root) => Task::Select(root),
            Self::History => Task::History,
            Self::Diagnostics => Task::Diagnostics,
            Self::Refresh => Task::Refresh,
            Self::Files(request) => Task::Files(request),
            Self::Batch(request) => Task::Batch(request),
            Self::Init(root, git) => Task::Init { root, git },
            Self::Rollback(r, t) => Task::Rollback(r, t),
            Self::Bootstrap(r, t, action) => Task::Bootstrap(r, t, action),
        }
    }
}
impl Task {
    pub fn retry_intent(&self) -> Option<Retry> {
        match self {
            Self::Check {
                manifest,
                requested,
            } => Some(Retry::Check(manifest.clone(), requested.clone())),
            Self::Profiles {
                manifest,
                requested,
                apply,
            } => Some(Retry::Profiles(manifest.clone(), requested.clone(), *apply)),
            Self::Discover => Some(Retry::Discover),
            Self::Select(root) => Some(Retry::Select(root.clone())),
            Self::History => Some(Retry::History),
            Self::Diagnostics => Some(Retry::Diagnostics),
            Self::Refresh => Some(Retry::Refresh),
            Self::Files(request) => Some(Retry::Files(request.clone())),
            Self::Batch(request) => Some(Retry::Batch(request.clone())),
            Self::Init { root, git } => Some(Retry::Init(root.clone(), git.clone())),
            Self::Rollback(r, t) => Some(Retry::Rollback(r.clone(), t.clone())),
            Self::Bootstrap(r, t, action) => Some(Retry::Bootstrap(r.clone(), t.clone(), *action)),
            _ => None,
        }
    }
}
pub enum Task {
    IgnoredPaths,
    Ignore(PathBuf, bool),
    DiscoveryTree(super::discovery_tree::Read),
    DiscoverContent(super::discover_content::Read),
    History,
    Diagnostics,
    Git(super::git::Read),
    Refresh,
    Discover,
    Check {
        manifest: Option<PathBuf>,
        requested: Vec<String>,
    },
    Profiles {
        manifest: Option<PathBuf>,
        requested: Vec<String>,
        apply: bool,
    },
    Select(Option<PathBuf>),
    Init {
        root: PathBuf,
        git: PathBuf,
    },
    Files(Request),
    Batch(dort_core::batch::Request),
    Rollback(String, String),
    Bootstrap(String, String, bootstrap::RecoveryAction),
    Execute(Approved),
}
pub enum Output {
    IgnoredPaths(Vec<PathBuf>),
    DiscoveryTree(super::discovery_tree::Report),
    DiscoverContent(super::discover_content::Report),
    History {
        rows: Vec<journal::Diagnosis>,
        error: Option<String>,
    },
    Diagnostics(Diagnostics),
    Git(super::git::Report),
    Data(Data),
    Discovery(crate::services::Discovery),
    Checked {
        report: Box<crate::services::CheckReport>,
        standalone: bool,
    },
    Profiles {
        report: Box<crate::services::CheckReport>,
        requested: Vec<String>,
        standalone: bool,
        apply: bool,
    },
    Selected(Option<PathBuf>, Data),
    Preview(Pending),
    Completed(Completion),
}
#[cfg(test)]
pub fn perform(
    task: Task,
    host: &HostContext,
    repository: Option<PathBuf>,
    observer: impl FnMut(&Event) -> Result<()>,
) -> Result<Output> {
    perform_scoped(task, host, repository, &[], observer)
}
pub fn perform_scoped(
    task: Task,
    host: &HostContext,
    repository: Option<PathBuf>,
    requested: &[String],
    observer: impl FnMut(&Event) -> Result<()>,
) -> Result<Output> {
    match task {
        Task::IgnoredPaths => Ok(Output::IgnoredPaths(
            dort_core::discovery_ignore::Rules::load(host)?
                .paths()
                .cloned()
                .collect(),
        )),
        Task::Ignore(path, ignored) => {
            let relative = if ignored {
                path.strip_prefix(&host.home)
                    .map_err(|_| Error::Invalid("ignore selection must be under HOME".into()))?
            } else {
                &path
            };
            dort_core::discovery_ignore::Preview::prepare(host, relative, ignored)
                .map(|p| Output::Preview(Pending::Ignore(p)))
        }
        Task::DiscoveryTree(read) => Ok(Output::DiscoveryTree(read.perform())),
        Task::DiscoverContent(read) => Ok(Output::DiscoverContent(read.perform(host))),
        Task::History => Ok(match journal::diagnose(host) {
            Ok(rows) => Output::History { rows, error: None },
            Err(error) => Output::History {
                rows: vec![],
                error: Some(diagnostic(&error)),
            },
        }),
        Task::Diagnostics => Ok(Output::Diagnostics(Diagnostics {
            host: host.clone(),
            registry: LocalConfig::load(host)
                .map(|local| crate::services::doctor(host, &local))
                .map_err(|e| diagnostic(&e)),
            history: journal::diagnose(host)
                .map(|rows| {
                    (
                        rows.len(),
                        rows.iter().filter(|r| r.blocks_writes()).count(),
                    )
                })
                .map_err(|e| diagnostic(&e)),
        })),
        Task::Git(read) => read.perform().map(Output::Git),
        Task::Refresh => load_scoped(host, repository.as_deref(), requested).map(Output::Data),
        Task::Check {
            manifest,
            requested,
        } => {
            let local = LocalConfig::load(host)?;
            let standalone = manifest.is_some();
            let path = match manifest {
                Some(path) => path,
                None => local
                    .select_repository(repository.as_deref())?
                    .join("dort.toml"),
            };
            let report = Box::new(crate::services::check_manifest(
                host, &local, path, &requested,
            )?);
            Ok(Output::Checked { report, standalone })
        }
        Task::Profiles {
            manifest,
            requested,
            apply,
        } => {
            let local = LocalConfig::load(host)?;
            let standalone = manifest.is_some();
            let path = match manifest {
                Some(path) => path,
                None => local
                    .select_repository(repository.as_deref())?
                    .join("dort.toml"),
            };
            let report = Box::new(crate::services::check_manifest(
                host, &local, path, &requested,
            )?);
            Ok(Output::Profiles {
                report,
                requested,
                standalone,
                apply,
            })
        }
        Task::Discover => {
            let local = LocalConfig::load(host)?;
            crate::services::discover(host, &local, repository.as_deref()).map(Output::Discovery)
        }
        Task::Select(explicit) => {
            let local = LocalConfig::load(host)?;
            let root = local.select_repository(explicit.as_deref())?;
            dort_core::observation::validate_output_path(&root)?;
            if !root.is_dir() {
                return Err(Error::Invalid(
                    "repository selection must be an existing directory".into(),
                ));
            }
            let data = load_scoped(host, Some(&root), &[])?;
            Ok(Output::Selected(explicit.map(|_| root), data))
        }
        Task::Init { root, git } => BootstrapPreview::prepare(host, &root, &git)
            .map(|p| Output::Preview(Pending::Init(Box::new(p)))),
        Task::Batch(request) => {
            let local = LocalConfig::load(host)?;
            crate::services::batch_plan(host, &local, repository.as_deref(), requested, request)
                .map(|p| Output::Preview(Pending::Batch(Box::new(p))))
        }
        Task::Files(request) => {
            let local = LocalConfig::load(host)?;
            let snapshot =
                crate::services::observe(host, &local, repository.as_deref(), requested, request)?;
            Ok(Output::Preview(Pending::Files(Box::new(planner::plan(
                snapshot,
            )))))
        }
        Task::Rollback(r, t) => {
            recovery::preview(host, &r, &t).map(|p| Output::Preview(Pending::Rollback(p)))
        }
        Task::Bootstrap(r, t, action) => bootstrap::recovery_preview(host, &r, &t, action)
            .map(|p| Output::Preview(Pending::Bootstrap(p))),
        Task::Execute(approval) => approval.execute(host, observer).map(Output::Completed),
    }
}