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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
use crate::services::adopt_request;
use clap::{Parser, Subcommand, ValueEnum};
use dort_core::{
    Error, bootstrap,
    context::HostContext,
    git, journal,
    local::LocalConfig,
    planner::{self, Request, UnmanageMode},
    recovery,
    state::WriterLock,
};
use serde::Serialize;
use std::{path::PathBuf, process::ExitCode};

#[derive(Parser)]
#[command(
    version,
    about = "Git-native development environment manager for local files, tools and Git"
)]
struct Cli {
    /// Emit structured output; diagnostics remain on stderr.
    #[arg(long, global = true)]
    json: bool,
    /// Override the locally registered active repository.
    #[arg(long, global = true)]
    repo: Option<PathBuf>,
    /// Preview writes or package-manager queries without changes.
    #[arg(long, global = true)]
    dry_run: bool,
    /// Approve writes or package-manager queries without prompting.
    #[arg(long, global = true)]
    yes: bool,
    /// Optional extra ID guard for link deletion; must match the selected mapping.
    #[arg(long, global = true)]
    confirm_remove: Option<String>,
    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Subcommand)]
enum Command {
    /// Open the interactive workbench.
    Tui,
    /// Create a local repository at a new path, or attach an existing one.
    Init { path: PathBuf },
    /// Show active file links and blockers.
    Status {
        #[arg(long = "profile")]
        profiles: Vec<String>,
    },
    /// Preview linking active files.
    Plan {
        #[arg(long = "profile")]
        profiles: Vec<String>,
    },
    /// Read-only operation history across repositories.
    History,
    /// Preview or approve rollback of a completed file or declaration operation.
    Rollback {
        repository_id: String,
        transaction_id: String,
    },
    /// Show host and state paths.
    Doctor,
    /// Discover and manage regular-file links.
    Files {
        #[command(subcommand)]
        command: FilesCommand,
    },
    /// Inspect operation records or recover an unfinished change.
    Recovery {
        #[command(subcommand)]
        command: RecoveryCommand,
    },
    /// Read-only Git status and diff. No network or writes.
    Git {
        #[command(subcommand)]
        command: GitCommand,
    },
    /// Manage declarations, check installed tools and install missing packages.
    Tools {
        #[command(subcommand)]
        command: ToolsCommand,
    },
    /// Check a manifest.
    Manifest {
        #[command(subcommand)]
        command: ManifestCommand,
    },
}

#[derive(Subcommand)]
enum GitCommand {
    /// Working-tree and index status, including untracked names.
    Status,
    /// Tracked diff. Untracked files are excluded.
    Diff {
        /// Compare the index to HEAD (also works before the first commit).
        #[arg(long)]
        staged: bool,
        /// Show patch content, with unsafe bytes escaped.
        #[arg(long)]
        patch: bool,
    },
}

#[derive(Subcommand)]
enum RecoveryCommand {
    /// Preview or approve rollback of a completed file or declaration operation.
    Rollback {
        repository_id: String,
        transaction_id: String,
    },
    /// Resume an intact repository setup. Never automatic.
    Resume {
        repository_id: String,
        transaction_id: String,
    },
    /// Abandon a repository setup. Keeps any published repository and registration.
    Abandon {
        repository_id: String,
        transaction_id: String,
    },
    /// List operation records and write blockers.
    List,
}

#[derive(Subcommand)]
enum ManifestCommand {
    /// Validate a manifest and profiles. Does not check installed tools.
    Check {
        /// Explicit manifest; otherwise use --repo or the active local repository.
        #[arg(long)]
        manifest: Option<PathBuf>,
        /// Add an optional profile for this check only.
        #[arg(long = "profile")]
        profiles: Vec<String>,
    },
}

#[derive(Subcommand)]
enum FilesCommand {
    /// Adopt one owned regular file into a new source and mapping.
    #[command(alias = "adopt")]
    Add {
        target: PathBuf,
        #[arg(long)]
        id: String,
        #[arg(long)]
        source: PathBuf,
        #[arg(long = "profile")]
        profiles: Vec<String>,
    },
    /// Link all changed active files as one recoverable operation.
    Apply {
        #[arg(long = "profile")]
        profiles: Vec<String>,
    },
    /// Remove a mapping, keeping its source. Keep writes a file; remove deletes the link.
    #[command(alias = "unmanage")]
    Remove {
        id: String,
        #[arg(long, value_enum)]
        mode: RemovalMode,
        #[arg(long = "profile")]
        profiles: Vec<String>,
    },
    /// List hidden files and .config entries. Does not read contents.
    Discover,
    /// Show active mappings without running tools.
    List {
        #[arg(long = "profile")]
        profiles: Vec<String>,
    },
    /// Preview only. No writes, approvals, backups or history records.
    Plan {
        #[arg(long = "profile", global = true)]
        profiles: Vec<String>,
        #[command(subcommand)]
        command: PlanCommand,
    },
}

#[derive(Subcommand)]
enum PlanCommand {
    /// Preview active link mappings.
    Apply,
    /// Preview adopting one regular file as a source, mapping and link.
    Adopt {
        /// Absolute or ~/ path; quote ~ when it must be expanded by Dort.
        target: PathBuf,
        #[arg(long)]
        id: String,
        /// New repository-relative source path; must not already exist.
        #[arg(long)]
        source: PathBuf,
    },
    /// Preview removing a mapping. Keeps the source.
    Unmanage {
        id: String,
        /// Keep writes a regular file; remove deletes the link.
        #[arg(long, value_enum)]
        mode: RemovalMode,
    },
}

#[derive(clap::Args)]
struct DeclaredToolsArgs {
    /// Manifest to check; defaults to the selected repository's dort.toml.
    #[arg(long)]
    manifest: Option<PathBuf>,
    #[arg(long = "profile")]
    profiles: Vec<String>,
    /// Package-manager program for a declared tool in a nonstandard layout: TOOL=PATH.
    #[arg(long = "program", value_name = "TOOL=PATH")]
    programs: Vec<String>,
    /// npm CLI script for a declared npm tool: TOOL=PATH.
    #[arg(long = "npm-cli", value_name = "TOOL=PATH")]
    npm_clis: Vec<String>,
    /// Global package destination for a declared npm tool: TOOL=PATH.
    #[arg(long = "npm-prefix", value_name = "TOOL=PATH")]
    npm_prefixes: Vec<String>,
}

#[derive(clap::Args)]
struct InstalledToolsArgs {
    /// Optional manifest for declared Node/npm runtime settings.
    #[arg(long)]
    manifest: Option<PathBuf>,
    #[arg(long = "program", value_name = "TOOL=PATH")]
    programs: Vec<String>,
    #[arg(long = "npm-cli", value_name = "TOOL=PATH")]
    npm_clis: Vec<String>,
    #[arg(long = "npm-prefix", value_name = "TOOL=PATH")]
    npm_prefixes: Vec<String>,
}
#[derive(Subcommand)]
enum ToolsCommand {
    /// List installed packages from detected package managers. Keeps only this result.
    Inspect(InstalledToolsArgs),
    /// Check declared tools using detected package managers.
    Check(DeclaredToolsArgs),
    /// Check declarations and install all eligible missing tools, one at a time.
    InstallMissing(DeclaredToolsArgs),
    /// Add a tool declaration to a registered repository. Does not install packages.
    Declare {
        /// Tool JSON fields: id, binary, profiles, requires, install (provider/package/version/runtime_tool).
        #[arg(long)]
        declaration: String,
        #[arg(long = "profile")]
        profiles: Vec<String>,
    },
    /// Edit one existing tool declaration, keeping its ID and installed packages.
    Edit {
        #[arg(long)]
        declaration: String,
        #[arg(long = "profile")]
        profiles: Vec<String>,
    },
    /// Remove a tool declaration; leave installed packages untouched.
    Remove {
        id: String,
        #[arg(long = "profile")]
        profiles: Vec<String>,
    },
    /// List installation records; show one full record with --id.
    Attempts {
        #[arg(long)]
        id: Option<String>,
    },
    /// Check current package-manager settings and close an unchanged record. Does not retry or roll back.
    CloseAttempt {
        id: String,
        /// Package manager for a damaged record. Known records keep their original settings.
        #[arg(long, value_enum)]
        provider: Option<InstallationProvider>,
        #[arg(long)]
        npm_cli: Option<PathBuf>,
        #[arg(long)]
        prefix: Option<PathBuf>,
        /// Only needed when the original package-manager settings are damaged or missing.
        #[arg(long)]
        executable: Option<PathBuf>,
        #[arg(long = "search-dir")]
        search_dirs: Vec<PathBuf>,
    },
}
#[derive(Clone, Copy, ValueEnum)]
enum InstallationProvider {
    Npm,
    Brew,
}

#[derive(Clone, Copy, ValueEnum)]
enum RemovalMode {
    Keep,
    Remove,
}

pub fn run() -> ExitCode {
    let cli = Cli::parse();
    let filter = tracing_subscriber::EnvFilter::try_from_default_env()
        .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn"));
    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_writer(std::io::stderr)
        .with_target(false)
        .init();
    match execute(&cli) {
        Ok(code) => code,
        Err(error) => {
            let (code, kind) = match &error {
                Error::Io { .. } => (1, "io"),
                Error::Locked => (3, "locked"),
                Error::Parse(_)
                | Error::Validation(_)
                | Error::Invalid(_)
                | Error::RecoveryRequired(_)
                | Error::NoRepository => (2, "validation"),
            };
            if cli.json {
                eprintln!(
                    "{}",
                    serde_json::json!({"error": error.to_string(), "kind": kind})
                );
            } else {
                eprintln!("error: {error}");
            }
            ExitCode::from(code)
        }
    }
}

fn declared_tools(
    cli: &Cli,
    host: &HostContext,
    args: &DeclaredToolsArgs,
    install_missing: bool,
) -> dort_core::Result<ExitCode> {
    use crate::services::declared_tools::{Input, Status};
    if cli.confirm_remove.is_some() {
        return Err(Error::Invalid(
            "Tool checks and installation do not use --confirm-remove".into(),
        ));
    }
    let launch = crate::environment::launch_directory()?;
    let manifest = match &args.manifest {
        Some(path) => crate::services::resolve_root(path, &launch),
        None => {
            let local = LocalConfig::load(host)?;
            let explicit = cli
                .repo
                .as_ref()
                .map(|p| crate::services::resolve_root(p, &launch));
            crate::services::declared_tools::manifest(
                &local.select_repository(explicit.as_deref())?,
            )
        }
    };
    let detection = crate::environment::inspection_inputs().with_settings(
        host,
        &manifest,
        &args.programs,
        &args.npm_clis,
        &args.npm_prefixes,
    )?;
    let preview = Input {
        manifest,
        profiles: args.profiles.clone(),
        detection,
    }
    .prepare(host)?;
    if cli.dry_run {
        if cli.json {
            print_git_json(
                &serde_json::json!({"check_review":preview.review(), "install_missing":install_missing, "preview_only":true}),
            )?;
        } else {
            print!(
                "{}",
                crate::services::presentation::check_review(&preview.review())
            );
        }
        return Ok(ExitCode::SUCCESS);
    }
    if !cli.yes && !interactive(cli) {
        return Err(Error::Invalid("Tool checks require terminal confirmation or --yes; use --dry-run for a process-free review.".into()));
    }
    if !cli.json {
        print!(
            "{}",
            crate::services::presentation::check_review(&preview.review())
        );
    }
    if !cli.yes
        && !confirmed(
            "Check declared tools? Package-manager configuration and plugins may run. [y/N] ",
        )?
    {
        return Err(Error::Invalid("Tool checks were not approved.".into()));
    }
    let checked = preview.approve().check(host)?;
    let statuses: Vec<_> = checked.reconciliation.plan.rows.iter().map(|r|
        serde_json::json!({"tool":r.id, "status":crate::services::declared_tools::status(r)})
    ).collect();
    if !cli.json {
        for row in &checked.reconciliation.plan.rows {
            println!(
                "{}: {}",
                crate::services::presentation::inline(&row.id),
                crate::services::declared_tools::status(row).label()
            );
        }
    }
    let complete = checked
        .reconciliation
        .plan
        .rows
        .iter()
        .all(|r| crate::services::declared_tools::status(r) == Status::Installed);
    let mut exit = if !checked.available() {
        1
    } else if complete {
        0
    } else {
        4
    };
    if install_missing {
        let preview = checked.prepare_missing(host)?;
        if !cli.json {
            print!(
                "{}",
                crate::services::presentation::install_review(&preview.review())
            );
        }
        if preview.is_empty() {
            if cli.json {
                print_git_json(
                    &serde_json::json!({"check":checked, "statuses":statuses, "installation_review":preview.review(), "installation":null}),
                )?;
            }
        } else {
            if !cli.yes
                && !confirmed(
                    "Install the displayed missing tools? Partial effects are possible; no rollback. [y/N] ",
                )?
            {
                return Err(Error::Invalid("Installation was not approved. Approved checks may already have changed package-manager caches.".into()));
            }
            let deferred = preview.deferred.len();
            let approval = preview.approve()?;
            let lock = WriterLock::acquire(host)?;
            let installed = approval.execute(host, &lock, |_| {});
            exit = if !installed.succeeded() {
                1
            } else if deferred > 0
                || checked.reconciliation.plan.rows.iter().any(|r| {
                    !matches!(
                        crate::services::declared_tools::status(r),
                        Status::Installed | Status::Missing
                    )
                })
            {
                4
            } else {
                0
            };
            if cli.json {
                print_git_json(
                    &serde_json::json!({"before_installation":{"check":checked, "statuses":statuses}, "installation":installed}),
                )?;
            } else {
                print!(
                    "{}",
                    crate::services::presentation::installed_result(&installed)
                );
            }
        }
    } else if cli.json {
        print_git_json(&serde_json::json!({"check":checked, "statuses":statuses}))?;
    }
    Ok(ExitCode::from(exit))
}

fn installed_tools(
    cli: &Cli,
    host: &HostContext,
    args: &InstalledToolsArgs,
) -> dort_core::Result<ExitCode> {
    use crate::services::{installed_tools, presentation};
    if cli.confirm_remove.is_some() {
        return Err(Error::Invalid(
            "Inspection does not use --confirm-remove.".into(),
        ));
    }
    let launch = crate::environment::launch_directory()?;
    let explicit = cli
        .repo
        .as_ref()
        .map(|p| crate::services::resolve_root(p, &launch));
    let manifest = args
        .manifest
        .as_ref()
        .map(|p| crate::services::resolve_root(p, &launch))
        .or_else(|| {
            LocalConfig::load(host)
                .ok()?
                .select_repository(explicit.as_deref())
                .ok()
                .map(|r| r.join("dort.toml"))
        });
    let mut input = crate::environment::inspection_inputs();
    if !args.programs.is_empty() || !args.npm_clis.is_empty() || !args.npm_prefixes.is_empty() {
        let manifest = manifest.as_ref().ok_or_else(|| {
            Error::Invalid("Select a repository before supplying tool settings.".into())
        })?;
        input = input.with_settings(
            host,
            manifest,
            &args.programs,
            &args.npm_clis,
            &args.npm_prefixes,
        )?;
    }
    let preview = installed_tools::prepare(host, manifest, input)?;
    if cli.dry_run {
        if cli.json {
            print_git_json(
                &serde_json::json!({"inspection_review":preview.review(), "preview_only":true}),
            )?;
        } else {
            print!("{}", presentation::installed_review(&preview.review()));
        }
        return Ok(ExitCode::SUCCESS);
    }
    if !preview.is_empty() {
        if !cli.yes && !interactive(cli) {
            return Err(Error::Invalid("Inspection requires terminal confirmation or --yes; use --dry-run for a process-free review.".into()));
        }
        if !cli.json {
            print!("{}", presentation::installed_review(&preview.review()));
        }
        if !cli.yes
            && !confirmed(
                "Inspect installed tools? Package-manager configuration/plugins may run. [y/N] ",
            )?
        {
            return Err(Error::Invalid("Inspection was not approved.".into()));
        }
    }
    let current = preview.approve().inspect()?;
    if cli.json {
        print_git_json(&current)?;
    } else {
        print!("{}", presentation::installed(&current));
    }
    Ok(ExitCode::from(if current.available() { 0 } else { 1 }))
}

fn tools_command(
    cli: &Cli,
    host: &HostContext,
    command: &ToolsCommand,
) -> dort_core::Result<ExitCode> {
    match command {
        ToolsCommand::Inspect(args) => return installed_tools(cli, host, args),
        ToolsCommand::Check(args) => return declared_tools(cli, host, args, false),
        ToolsCommand::InstallMissing(args) => return declared_tools(cli, host, args, true),
        _ => (),
    }
    if matches!(
        command,
        ToolsCommand::Declare { .. } | ToolsCommand::Edit { .. } | ToolsCommand::Remove { .. }
    ) {
        if cli.confirm_remove.is_some() {
            return Err(Error::Invalid(
                "declaration changes use ordinary approval; omit --confirm-remove".into(),
            ));
        }
        let local = LocalConfig::load(host)?;
        let repository = local.select_repository(cli.repo.as_deref())?;
        let preview = match command {
            ToolsCommand::Declare {
                declaration,
                profiles,
            }
            | ToolsCommand::Edit {
                declaration,
                profiles,
            } => {
                let mut request = crate::services::declaration::Request::parse(declaration)?;
                if matches!(command, ToolsCommand::Edit { .. }) {
                    request.change = Some(dort_core::tools::declaration::Change::Edit);
                }
                request.prepare(host, &repository, profiles)?
            }
            ToolsCommand::Remove { id, profiles } => {
                crate::services::declaration::prepare_remove(host, &repository, profiles, id)?
            }
            _ => unreachable!(),
        };
        if cli.dry_run {
            if cli.json {
                print_git_json(&preview)?;
            } else {
                print!(
                    "{}",
                    crate::services::presentation::safe(&crate::services::declaration::report(
                        &preview
                    ))
                );
            }
        } else {
            if !cli.json {
                print!(
                    "{}",
                    crate::services::presentation::safe(&crate::services::declaration::report(
                        &preview
                    ))
                );
            }
            approve(cli)?;
            let approval = dort_core::tools::declaration::Approval::from_preview(preview)?;
            let lock = WriterLock::acquire(host)?;
            let tx = dort_core::tools::declaration::execute(host, &lock, approval, |_| Ok(()))?;
            if cli.json {
                mutation_report(
                    match command {
                        ToolsCommand::Edit { .. } => "edit-tool",
                        ToolsCommand::Remove { .. } => "remove-tool",
                        _ => "declare-tool",
                    },
                    tx,
                )?;
            } else {
                println!(
                    "{}",
                    if tx.is_some() {
                        "Declaration saved."
                    } else {
                        "No changes were needed."
                    }
                );
            }
        }
        return Ok(ExitCode::SUCCESS);
    }
    if cli.repo.is_some() || cli.confirm_remove.is_some() {
        return Err(Error::Invalid(
            "Tools uses its explicit scope; omit --repo/--confirm-remove".into(),
        ));
    }
    if let ToolsCommand::Attempts { id } = command {
        let attempts = dort_core::tools::install::diagnose(host)?;
        if let Some(id) = id {
            let attempt = attempts
                .iter()
                .find(|a| &a.id == id)
                .ok_or_else(|| Error::Invalid("installation record not found".into()))?;
            if cli.json {
                print_git_json(attempt)?;
            } else {
                print!("{}", crate::services::presentation::attempt(attempt));
            }
        } else {
            if cli.json {
                print_git_json(&attempts)?;
            } else if attempts.is_empty() {
                println!("No installation history.");
            } else {
                for attempt in &attempts {
                    print!("{}", crate::services::presentation::attempt(attempt));
                }
            }
        }
        return Ok(ExitCode::SUCCESS);
    }
    if let ToolsCommand::CloseAttempt {
        id,
        executable,
        search_dirs,
        provider,
        npm_cli,
        prefix,
    } = command
    {
        let npm_binding = if matches!(provider, Some(InstallationProvider::Npm)) {
            Some(dort_core::tools::inspection::NpmBinding {
                runtime_tool: "historical-runtime".into(),
                node: executable.clone().ok_or_else(|| {
                    Error::Invalid("npm fallback requires --executable Node".into())
                })?,
                npm_cli: npm_cli
                    .clone()
                    .ok_or_else(|| Error::Invalid("npm fallback requires --npm-cli".into()))?,
                prefix: prefix
                    .clone()
                    .ok_or_else(|| Error::Invalid("npm fallback requires --prefix".into()))?,
            })
        } else {
            if npm_cli.is_some()
                || (prefix.is_some() && !matches!(provider, Some(InstallationProvider::Brew)))
            {
                return Err(Error::Invalid(
                    "--npm-cli needs --provider npm; --prefix needs npm or brew".into(),
                ));
            }
            None
        };
        let preview = dort_core::tools::install::prepare_close(
            host,
            dort_core::tools::install::CloseRequest {
                id: id.clone(),
                executable: executable.clone(),
                search_dirs: search_dirs.clone(),
                npm_binding,
                brew_prefix: if matches!(provider, Some(InstallationProvider::Brew)) {
                    Some(prefix.clone().ok_or_else(|| {
                        Error::Invalid("Homebrew fallback requires --prefix".into())
                    })?)
                } else {
                    None
                },
            },
        )?;
        if cli.dry_run && cli.json {
            print_git_json(&preview.review())?;
        } else if !cli.json {
            print!(
                "{}",
                crate::services::presentation::close_review(&preview.review())
            );
        }
        if !cli.dry_run {
            approve(cli)?;
            let lock = WriterLock::acquire(host)?;
            let attempt = dort_core::tools::install::close(host, &lock, preview.approve())?;
            if cli.json {
                print_git_json(&attempt)?;
            } else {
                print!("{}", crate::services::presentation::attempt(&attempt));
            }
        }
        return Ok(ExitCode::SUCCESS);
    }
    unreachable!("all Tools commands are handled above")
}

fn execute(cli: &Cli) -> dort_core::Result<ExitCode> {
    let command = cli.command.as_ref().unwrap_or(&Command::Tui);
    if matches!(command, Command::Tui) {
        if cli.json || cli.yes || cli.confirm_remove.is_some() || !interactive(cli) {
            return Err(Error::Invalid("TUI requires terminal stdin/stdout/stderr, without --json/--yes/--confirm-remove; use --help or an explicit CLI command".into()));
        }
        crate::tui::run(
            HostContext::from_env()?,
            cli.repo.clone(),
            cli.dry_run,
            crate::environment::launch_directory()?,
            crate::environment::resolve_git().map_err(|error| error.to_string()),
            crate::environment::terminal_appearance(),
            crate::environment::reduced_motion(),
        )?;
        return Ok(ExitCode::SUCCESS);
    }
    let host = HostContext::from_env()?;
    if let Command::Tools { command } = command {
        return tools_command(cli, &host, command);
    }
    // Read only; missing configuration uses defaults without creating directories.
    let local = LocalConfig::load(&host)?;
    if cli.repo.is_some()
        && matches!(
            command,
            Command::Rollback { .. }
                | Command::Recovery {
                    command: RecoveryCommand::Rollback { .. }
                        | RecoveryCommand::Resume { .. }
                        | RecoveryCommand::Abandon { .. }
                }
        )
    {
        return Err(Error::Invalid(
            "recovery uses explicit repository and operation IDs; omit --repo".into(),
        ));
    }
    match command {
        Command::Tui | Command::Tools { .. } => unreachable!(),
        Command::Init { path } => {
            if cli.repo.is_some() {
                return Err(Error::Invalid(
                    "init uses its explicit path; omit --repo".into(),
                ));
            }
            let root = if path.is_absolute() {
                path.clone()
            } else {
                crate::services::resolve_root(path, &crate::environment::launch_directory()?)
            };
            let git = crate::environment::resolve_git()?;
            let preview = crate::services::BootstrapPreview::prepare(&host, &root, &git)?;
            let report = &preview.report;
            if cli.dry_run {
                print_git_json(&report)?;
            } else {
                if !cli.json {
                    print_git_json(&report)?;
                }
                approve(cli)?;
                let tid = preview.approve()?.execute(&host, |_| Ok(()))?;
                print_git_json(
                    &serde_json::json!({"schema":1,"operation":"init","completed":true,"repository":root,"transaction_id":tid}),
                )?;
            }
        }
        Command::Status { profiles } | Command::Plan { profiles } => {
            return file_operation(cli, &host, &local, profiles, Request::Apply, false);
        }
        Command::Rollback {
            repository_id,
            transaction_id,
        }
        | Command::Recovery {
            command:
                RecoveryCommand::Rollback {
                    repository_id,
                    transaction_id,
                },
        } => {
            let report = recovery::preview(&host, repository_id, transaction_id)?;
            if cli.dry_run {
                print_git_json(&report)?;
            } else {
                if !cli.json {
                    print_git_json(&report)?;
                }
                approve(cli)?;
                let approval = recovery::Approval::from_preview(report)?;
                let lock = WriterLock::acquire(&host)?;
                recovery::execute(&host, &lock, approval)?;
                mutation_report("rollback", Some(transaction_id.clone()))?;
            }
        }
        Command::Recovery {
            command:
                RecoveryCommand::Resume {
                    repository_id,
                    transaction_id,
                },
        }
        | Command::Recovery {
            command:
                RecoveryCommand::Abandon {
                    repository_id,
                    transaction_id,
                },
        } => {
            let action = if matches!(
                command,
                Command::Recovery {
                    command: RecoveryCommand::Resume { .. }
                }
            ) {
                bootstrap::RecoveryAction::Resume
            } else {
                bootstrap::RecoveryAction::Abandon
            };
            let report = bootstrap::recovery_preview(&host, repository_id, transaction_id, action)?;
            if cli.dry_run {
                print_git_json(&report)?;
            } else {
                if !cli.json {
                    print_git_json(&report)?;
                }
                approve(cli)?;
                let approval = bootstrap::RecoveryApproval::from_preview(report)?;
                let lock = WriterLock::acquire(&host)?;
                bootstrap::recover(&host, &lock, approval, |_| Ok(()))?;
                mutation_report("bootstrap_recovery", Some(transaction_id.clone()))?;
            }
        }
        Command::Doctor => {
            let report = crate::services::doctor(&host, &local);
            if cli.json {
                print_json(&report)?;
            } else {
                println!("Dort: {}", report.mode);
                println!(
                    "Platform: {:?} / {:?}",
                    report.host.platform, report.host.architecture
                );
                println!("Config: {}", report.host.config_dir.display());
                println!("State: {}", report.host.state_dir.display());
                println!(
                    "Registered repositories: {}",
                    report.registered_repositories
                );
            }
        }
        Command::History
        | Command::Recovery {
            command: RecoveryCommand::List,
        } => {
            if cli.repo.is_some() {
                return Err(Error::Invalid(
                    "recovery list inspects all local repositories; omit --repo".into(),
                ));
            }
            let transactions = journal::diagnose(&host)?;
            let write_blocked = transactions.iter().any(journal::Diagnosis::blocks_writes);
            if cli.json {
                print_json(
                    &serde_json::json!({"schema": 1, "read_only": true, "write_blocked": write_blocked, "transactions": transactions}),
                )?;
            } else {
                for transaction in &transactions {
                    println!(
                        "{} / {}: {:?} ({}; {} saved steps)",
                        transaction.repository_id,
                        transaction.transaction_id,
                        transaction.phase,
                        operation_type(transaction.journal_schema),
                        transaction.valid_checkpoints
                    );
                    if let Some(problem) = &transaction.problem {
                        println!("  BLOCKED: {problem}");
                    }
                }
                println!(
                    "Read-only history. Writes blocked: {write_blocked}. Recovery needs a preview and approval."
                );
            }
            if write_blocked {
                return Ok(ExitCode::from(4));
            }
        }
        Command::Git { command } => {
            let root =
                local
                    .select_repository(cli.repo.as_deref())
                    .map_err(|error| match error {
                        Error::NoRepository => Error::NoRepository,
                        _ => Error::Invalid("could not resolve Git repository root".into()),
                    })?;
            let backend = git::Git::new(crate::environment::resolve_git()?)?;
            match command {
                GitCommand::Status => {
                    let report = backend.status(&root)?;
                    if cli.json {
                        print_git_json(&report)?;
                    } else {
                        for header in &report.branch {
                            println!("Branch: {header:?}");
                        }
                        for entry in &report.entries {
                            println!(
                                "{} {} {:?} (original: {:?})",
                                entry.kind,
                                entry.xy.as_deref().unwrap_or("?"),
                                entry.path,
                                entry.original_path
                            );
                        }
                        println!("Read-only Git status; {} entries.", report.entries.len());
                    }
                }
                GitCommand::Diff { staged, patch } => {
                    let report = backend.diff(&root, *staged, *patch)?;
                    if cli.json {
                        print_git_json(&report)?;
                    } else {
                        for entry in &report.entries {
                            println!(
                                "{} {} -> {} {:?}",
                                entry.change, entry.old_mode, entry.new_mode, entry.path
                            );
                        }
                        println!(
                            "Read-only Git diff; {} entries. Untracked contents excluded.",
                            report.entries.len()
                        );
                        if let Some(patch) = &report.patch {
                            println!("Explicit patch CONTENT (unsafe bytes escaped):\n{patch}");
                        }
                    }
                }
            }
        }
        Command::Files { command } => match command {
            FilesCommand::Add {
                target,
                id,
                source,
                profiles,
            } => {
                return file_operation(
                    cli,
                    &host,
                    &local,
                    profiles,
                    adopt_request(target, id, source),
                    true,
                );
            }
            FilesCommand::Apply { profiles } => {
                return file_operation(cli, &host, &local, profiles, Request::Apply, true);
            }
            FilesCommand::Remove { id, mode, profiles } => {
                return file_operation(
                    cli,
                    &host,
                    &local,
                    profiles,
                    Request::Unmanage {
                        id: id.clone(),
                        mode: match mode {
                            RemovalMode::Keep => UnmanageMode::Keep,
                            RemovalMode::Remove => UnmanageMode::Remove,
                        },
                    },
                    true,
                );
            }
            FilesCommand::Discover => {
                let report = crate::services::discover(&host, &local, cli.repo.as_deref())?.report;
                if cli.json {
                    print_json(&report)?;
                } else {
                    for candidate in &report.candidates {
                        println!(
                            "{}: {:?}, adoption candidate: {}{}",
                            candidate.entry.path.display(),
                            candidate.entry.kind,
                            candidate.supported_for_adoption,
                            candidate
                                .link_state
                                .as_ref()
                                .map_or(String::new(), |state| format!(", link: {state:?}"))
                        );
                    }
                    for warning in &report.warnings {
                        println!("Warning: {warning}");
                    }
                    println!("{}", report.sensitivity_notice);
                }
            }
            FilesCommand::List { profiles } => {
                let snapshot = crate::services::observe(
                    &host,
                    &local,
                    cli.repo.as_deref(),
                    profiles,
                    Request::Apply,
                )?;
                if cli.json {
                    print_json(&snapshot)?;
                } else {
                    for file in &snapshot.files {
                        println!(
                            "{}: {} -> {}",
                            file.mapping.id,
                            file.target_path.display(),
                            file.source_path.display()
                        );
                        println!(
                            "  Source: {:?}; destination: {:?}",
                            file.source.as_ref().map(|f| &f.kind),
                            file.destination.as_ref().map(|f| &f.kind)
                        );
                        for blocker in &file.blockers {
                            println!("  BLOCKED: {blocker}");
                        }
                    }
                    println!(
                        "Read-only inventory; use files plan apply for safety/conflict decisions."
                    );
                }
            }
            FilesCommand::Plan { profiles, command } => {
                let request = match command {
                    PlanCommand::Apply => Request::Apply,
                    PlanCommand::Adopt { target, id, source } => adopt_request(target, id, source),
                    PlanCommand::Unmanage { id, mode } => Request::Unmanage {
                        id: id.clone(),
                        mode: match mode {
                            RemovalMode::Keep => UnmanageMode::Keep,
                            RemovalMode::Remove => UnmanageMode::Remove,
                        },
                    },
                };
                let plan = planner::plan(crate::services::observe(
                    &host,
                    &local,
                    cli.repo.as_deref(),
                    profiles,
                    request,
                )?);
                if cli.json {
                    print_json(&plan)?;
                } else {
                    print!("{}", plan.human());
                }
                if plan.has_blockers() {
                    return Ok(ExitCode::from(4));
                }
            }
        },
        Command::Manifest {
            command: ManifestCommand::Check { manifest, profiles },
        } => {
            if manifest.is_some() && cli.repo.is_some() {
                return Err(Error::Invalid(
                    "choose either --manifest or --repo, not both".into(),
                ));
            }
            let path = if let Some(path) = manifest {
                path.clone()
            } else {
                local
                    .select_repository(cli.repo.as_deref())?
                    .join("dort.toml")
            };
            let report = crate::services::check_manifest(&host, &local, path, profiles)?;
            if cli.json {
                print_json(&report)?;
            } else {
                println!("Valid manifest: {}", report.manifest.display());
                println!(
                    "Profiles: {}",
                    report
                        .active_profiles
                        .iter()
                        .cloned()
                        .collect::<Vec<_>>()
                        .join(", ")
                );
                println!(
                    "Selected: {} tools, {} files",
                    report.selected_tools, report.selected_files
                );
                for capability in &report.unsupported_capabilities {
                    println!("Not implemented: {capability}");
                }
                println!(
                    "Read-only structural check; live files and installed tools were not inspected."
                );
            }
        }
    }
    Ok(ExitCode::SUCCESS)
}

fn operation_type(schema: Option<u32>) -> &'static str {
    match schema {
        Some(1) => "file adoption",
        Some(2) => "file change",
        Some(3) => "repository setup",
        Some(4) => "file batch",
        Some(5 | 6) => "tool declaration",
        _ => "unknown",
    }
}
fn mutation_report(operation: &str, transaction: Option<String>) -> dort_core::Result<()> {
    print_git_json(
        &serde_json::json!({"schema":1,"operation":operation,"completed":true,"transaction_id":transaction}),
    )
}

fn interactive(cli: &Cli) -> bool {
    use std::io::IsTerminal;
    !cli.json
        && std::io::stdin().is_terminal()
        && std::io::stdout().is_terminal()
        && std::io::stderr().is_terminal()
}
fn answer(prompt: &str) -> dort_core::Result<String> {
    use std::io::{BufRead, Read, Write};
    eprint!("{prompt}");
    std::io::stderr()
        .flush()
        .map_err(|_| Error::Invalid("could not present confirmation".into()))?;
    let mut bytes = Vec::new();
    std::io::stdin()
        .lock()
        .take(257)
        .read_until(b'\n', &mut bytes)
        .map_err(|_| Error::Invalid("could not read confirmation".into()))?;
    if bytes.len() > 256 {
        return Err(Error::Invalid("confirmation too long".into()));
    }
    String::from_utf8(bytes)
        .map(|s| s.trim_end_matches(['\r', '\n']).to_owned())
        .map_err(|_| Error::Invalid("invalid confirmation".into()))
}
fn confirmed(prompt: &str) -> dort_core::Result<bool> {
    Ok(matches!(
        answer(prompt)?.to_ascii_lowercase().as_str(),
        "y" | "yes"
    ))
}
fn approve(cli: &Cli) -> dort_core::Result<()> {
    if cli.yes {
        return Ok(());
    }
    if !interactive(cli) {
        return Err(Error::Invalid(
            "write requires --yes in JSON/nonterminal mode; use --dry-run to preview".into(),
        ));
    }
    if !confirmed("Proceed with the reviewed changes? [y/N] ")? {
        return Err(Error::Invalid("write not approved".into()));
    }
    Ok(())
}
fn file_operation(
    cli: &Cli,
    host: &HostContext,
    local: &LocalConfig,
    profiles: &[String],
    request: Request,
    write: bool,
) -> dort_core::Result<ExitCode> {
    let removal = match &request {
        Request::Unmanage {
            id,
            mode: UnmanageMode::Remove,
        } => Some(id.clone()),
        _ => None,
    };
    let plan = planner::plan(crate::services::observe(
        host,
        local,
        cli.repo.as_deref(),
        profiles,
        request,
    )?);
    if !write || cli.dry_run || plan.has_blockers() {
        if cli.json {
            print_git_json(&plan)?;
        } else {
            print!("{}", plan.human());
        }
        return Ok(ExitCode::from(if plan.has_blockers() { 4 } else { 0 }));
    }
    if !cli.json {
        print!("{}", plan.human());
    }
    // A supplied legacy guard must match. Approval binds the preview's ID internally.
    if let Some(id) = &removal {
        if cli.confirm_remove.as_ref().is_some_and(|value| value != id) {
            return Err(Error::Invalid(
                "--confirm-remove does not match the selected mapping ID".into(),
            ));
        }
    } else if cli.confirm_remove.is_some() {
        return Err(Error::Invalid(
            "--confirm-remove is only valid for remove mode".into(),
        ));
    }
    approve(cli)?;
    let approval = crate::services::FileApproval::from_plan(plan, removal.as_deref())?;
    let tid = approval.execute(host, |_| Ok(()))?;
    mutation_report("files", tid)?;
    Ok(ExitCode::SUCCESS)
}

// ASCII-only JSON protects terminals from C1/bidi controls while preserving the
// exact decoded Unicode path identity, including supplementary-plane characters.
fn print_git_json(value: &impl Serialize) -> dort_core::Result<()> {
    use std::fmt::Write;
    let json = serde_json::to_string_pretty(value)
        .map_err(|_| Error::Invalid("could not encode Git output".into()))?;
    let mut escaped = String::new();
    for character in json.chars() {
        if character >= '\u{7f}' {
            for unit in character.encode_utf16(&mut [0; 2]) {
                let _ = write!(escaped, "\\u{unit:04x}");
            }
        } else {
            escaped.push(character);
        }
    }
    println!("{escaped}");
    Ok(())
}

fn print_json(value: &impl Serialize) -> dort_core::Result<()> {
    let json = serde_json::to_string_pretty(value)
        .map_err(|_| Error::Invalid("could not encode output".into()))?;
    println!("{json}");
    Ok(())
}