dort 0.2.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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
//! Prepares and dispatches actions over 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 tools: Option<std::result::Result<Vec<dort_core::model::Tool>, String>>,
    pub tools_source: Option<crate::services::declared_tools::Source>,
    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 text is not shown.".into(),
        _ => error.to_string(),
    }
}

/// Preserve typed write blockers instead of reconstructing them from message text.
pub fn present(result: Result<Output>) -> std::result::Result<Output, String> {
    match result {
        Err(Error::RecoveryRequired(blocker)) => Ok(Output::RecoveryRequired(blocker)),
        other => other.map_err(|error| diagnostic(&error)),
    }
}

/// 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;
    let mut tools = None;
    let mut tools_source = 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());
                    tools = Some(
                        dort_core::observation::read_manifest(&root.join("dort.toml"))
                            .map(|(manifest, entry)| {
                                tools_source =
                                    crate::services::declared_tools::Source::capture(host, &entry)
                                        .ok();
                                manifest.tools
                            })
                            .map_err(|error| diagnostic(&error)),
                    );
                    match crate::services::observe(
                        host,
                        &local,
                        Some(&root),
                        requested,
                        Request::Apply,
                    ) {
                        Err(error) => {
                            let error = diagnostic(&error);
                            files_error = Some(format!("Could not read files: {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,
        tools,
        tools_source,
        files_error,
        history,
        history_error,
    })
}

pub enum Pending {
    ToolDeclaration(Box<dort_core::tools::declaration::Preview>),
    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::ToolDeclaration(p) => crate::services::declaration::report(p),
            Self::Ignore(preview) => preview.human(),
            Self::Batch(plan) => plan.human(),
            Self::Files(plan) => format!(
                "Repository: {:?}\nProfiles: {:?}\nScope: every mapping selected by this request. The preview shows what runs.\n{}",
                plan.inputs.repository,
                plan.inputs.active_profiles,
                plan.human()
            ),
            Self::Init(preview) => format!(
                "{} local repository\nPath: {:?}\nRepository ID: {}\n\nEffects:\n- {}\n\nThe change is saved only after approval.\nA failure keeps private records; open Recovery.\nExisting dotfiles stay 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!(
                "Roll back operation\nRepository ID: {}\nOperation ID: {}\nHistory head: {}\nPaths:\n{}\n\nThis reverses the recorded changes if they still match. Later edits can block it. Private backups stay.",
                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!(
                "{} repository setup\nRepository: {:?}\nRepository ID: {}\nOperation ID: {}\nHistory head: {}\nRepository published: {}\nRegistration published: {}\nEffects:\n- {}\n\nAbandon keeps the published repository, registration and private files.\nResume continues the saved setup; later changes can block it. Finish or abandon it before another create or attach. Existing dotfiles stay 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::ToolDeclaration(p) => dort_core::tools::declaration::Approval::from_preview(*p)
                .map(|a| Approved::ToolDeclaration(Box::new(a))),
            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 {
    ToolDeclaration(Box<dort_core::tools::declaration::Approval>),
    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::ToolDeclaration(a) => {
                let lock = WriterLock::acquire(host)?;
                (
                    "Tool declaration",
                    dort_core::tools::declaration::execute(host, &lock, *a, observer)?,
                    None,
                )
            }
            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)?;
                ("Repository setup 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 {
    ToolsCheckPrepare(crate::services::inspection_defaults::Inputs),
    ToolsInstalledPrepare(crate::services::inspection_defaults::Inputs),
    ToolsInstallMissingPrepare(std::sync::Arc<crate::services::declared_tools::Checked>),
    ToolDeclaration(crate::services::declaration::Request),
    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::ToolsCheckPrepare(inputs) => Task::ToolsCheckPrepare(inputs),
            Self::ToolsInstalledPrepare(inputs) => Task::ToolsInstalledPrepare(inputs),
            Self::ToolsInstallMissingPrepare(checked) => Task::ToolsInstallMissingPrepare(checked),
            Self::ToolDeclaration(r) => Task::ToolDeclaration(r),
            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::ToolsCheckPrepare(inputs) => Some(Retry::ToolsCheckPrepare(inputs.clone())),
            Self::ToolsInstalledPrepare(inputs) => {
                Some(Retry::ToolsInstalledPrepare(inputs.clone()))
            }
            Self::ToolsInstallMissingPrepare(checked) => {
                Some(Retry::ToolsInstallMissingPrepare(checked.clone()))
            }
            Self::ToolDeclaration(r) => Some(Retry::ToolDeclaration(r.clone())),
            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 {
    ToolsInstalledPrepare(crate::services::inspection_defaults::Inputs),
    ToolsInstalledInspect(crate::services::installed_tools::Approval),
    ToolsCheckPrepare(crate::services::inspection_defaults::Inputs),
    ToolsCheck(Box<crate::services::declared_tools::CheckApproval>),
    ToolsInstallMissingPrepare(std::sync::Arc<crate::services::declared_tools::Checked>),
    ToolsInstallMissing(crate::services::declared_tools::InstallApproval),

    ToolAttempts,
    ToolClosePrepare(dort_core::tools::install::CloseRequest),
    ToolClose(Box<dort_core::tools::install::CloseApproval>),
    ToolDeclaration(crate::services::declaration::Request),
    IgnoredPaths,
    Ignore(PathBuf, bool),
    DiscoveryTree(super::discovery_tree::Read),
    DiscoverContent(super::discover_content::Read),
    History,
    Diagnostics,
    Git(super::git::Read),
    GitPreview(super::git::PreviewRead),
    ToolsSettingsDetect {
        tool: dort_core::model::Tool,
        inputs: crate::services::inspection_defaults::Inputs,
    },
    ToolsSettingsValidate(crate::services::tools::Request),
    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 {
    RecoveryRequired(Box<journal::WriteBlocker>),
    ToolsInstalledPreview(crate::services::installed_tools::Preview),
    ToolsInstalled(crate::services::installed_tools::Current),
    ToolsCheckPreview(crate::services::declared_tools::CheckPreview),
    ToolsChecked(crate::services::declared_tools::Checked),
    ToolsMissingPreview(crate::services::declared_tools::InstallPreview),
    ToolsMissingInstalled(crate::services::declared_tools::Installed),

    ToolAttempts(std::result::Result<Vec<dort_core::tools::install::Attempt>, String>),
    ToolClosePreview(Box<dort_core::tools::install::ClosePreview>),
    ToolClosed(std::result::Result<dort_core::tools::install::Attempt, String>),
    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::Metadata),
    GitPreview(super::git::PreviewReport),
    ToolsSettingsDetected(String, crate::services::tools::Request),
    ToolsSettingsSaved(crate::services::tools::Request),
    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)
}
#[cfg(test)]
pub fn perform_scoped(
    task: Task,
    host: &HostContext,
    repository: Option<PathBuf>,
    requested: &[String],
    observer: impl FnMut(&Event) -> Result<()>,
) -> Result<Output> {
    perform_scoped_with_install_progress(task, host, repository, requested, observer, |_| {})
}
pub fn perform_scoped_with_install_progress(
    task: Task,
    host: &HostContext,
    repository: Option<PathBuf>,
    requested: &[String],
    observer: impl FnMut(&Event) -> Result<()>,
    installation_observer: impl FnMut(dort_core::tools::install::Event),
) -> Result<Output> {
    match task {
        Task::ToolsInstalledPrepare(input) => {
            let manifest = LocalConfig::load(host)?
                .select_repository(repository.as_deref())
                .ok()
                .map(|r| r.join("dort.toml"));
            crate::services::installed_tools::prepare(host, manifest, input)
                .map(Output::ToolsInstalledPreview)
        }
        Task::ToolsInstalledInspect(approval) => approval.inspect().map(Output::ToolsInstalled),
        Task::ToolsCheckPrepare(detection) => {
            let root = LocalConfig::load(host)?.select_repository(repository.as_deref())?;
            crate::services::declared_tools::Input {
                manifest: root.join("dort.toml"),
                profiles: requested.to_vec(),
                detection,
            }
            .prepare(host)
            .map(Output::ToolsCheckPreview)
        }
        Task::ToolsCheck(approval) => approval.check(host).map(Output::ToolsChecked),
        Task::ToolsInstallMissingPrepare(checked) => checked
            .prepare_missing(host)
            .map(Output::ToolsMissingPreview),
        Task::ToolsInstallMissing(approval) => {
            let lock = dort_core::state::WriterLock::acquire(host)?;
            Ok(Output::ToolsMissingInstalled(approval.execute(
                host,
                &lock,
                installation_observer,
            )))
        }

        Task::ToolAttempts => Ok(Output::ToolAttempts(
            dort_core::tools::install::diagnose(host).map_err(|e| diagnostic(&e)),
        )),
        Task::ToolClosePrepare(request) => dort_core::tools::install::prepare_close(host, request)
            .map(|p| Output::ToolClosePreview(Box::new(p))),
        Task::ToolClose(approval) => Ok(Output::ToolClosed(
            (|| {
                let lock = dort_core::state::WriterLock::acquire(host)?;
                dort_core::tools::install::close(host, &lock, *approval)
            })()
            .map_err(|e| diagnostic(&e)),
        )),
        Task::ToolDeclaration(request) => {
            let repository = LocalConfig::load(host)?.select_repository(repository.as_deref())?;
            request
                .prepare(host, &repository, requested)
                .map(|p| Output::Preview(Pending::ToolDeclaration(Box::new(p))))
        }
        Task::ToolsSettingsDetect { tool, inputs } => {
            let root = LocalConfig::load(host)?.select_repository(repository.as_deref())?;
            crate::services::inspection_defaults::for_tool(
                host,
                &root.join("dort.toml"),
                &tool.id,
                inputs,
            )
            .map(|request| Output::ToolsSettingsDetected(tool.id, request))
        }
        Task::ToolsSettingsValidate(request) => {
            request.clone().prepare(host)?;
            Ok(Output::ToolsSettingsSaved(request))
        }
        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::GitPreview(read) => Ok(Output::GitPreview(read.perform())),
        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),
    }
}