tirith 0.4.1

Terminal security - catches homograph attacks, pipe-to-shell, ANSI injection
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
//! `tirith setup <tool>` — automated tool integration.
//!
//! Configures tirith protection for AI coding tools (Claude Code, Codex,
//! Cursor, VS Code, Windsurf) by writing hook scripts, merging JSON configs,
//! and registering MCP servers.

// Unix fs_helpers uses PermissionsExt for chmod; Windows uses no-op shims.
#[cfg_attr(unix, path = "fs_helpers.rs")]
#[cfg_attr(not(unix), path = "fs_helpers_windows.rs")]
mod fs_helpers;

mod fs_transaction;

// Compile Windows containment/ACL policy tests on Unix CI as pure tests.
#[cfg(all(test, unix))]
#[path = "fs_helpers_windows_path.rs"]
mod fs_helpers_windows_path;

mod merge;
mod shell_profile;
mod tools;
pub(crate) use shell_profile::shell_quote;
pub(crate) use tools::{
    cline_hooks_dir, omp_user_guard_path, pi_cli_user_guard_path, prime_agent_user_guard_path,
};

#[cfg(unix)]
mod zshenv;

pub use self::run_impl::run;

mod run_impl {
    use super::fs_helpers;
    use etcetera::BaseStrategy;
    use sha2::{Digest, Sha256};
    use std::fmt::Write as _;
    use std::path::{Path, PathBuf};

    /// All tools recognized by `tirith setup`.
    /// Which scopes a host accepts and which one an omitted `--scope` selects.
    #[derive(Clone, Copy)]
    enum ScopeSupport {
        /// Both scopes; the payload is the default.
        Both(Scope),
        /// Project only; the payload explains why `--scope user` is refused.
        ProjectOnly(&'static str),
        /// User only; the payload explains why `--scope project` is refused.
        UserOnly(&'static str),
    }

    /// Everything `tirith setup <tool>` needs to know about a host BEFORE it
    /// calls the host's installer. Scope rules, the python3 requirement, the
    /// `--install-zshenv` applicability, and the installer itself live in one
    /// row per host, so they cannot drift apart again. They did: OpenHands grew
    /// a project-scope hook installer while `resolve_scope` still refused
    /// `--scope project`, and the hook was unreachable from the command line.
    struct HostSpec {
        name: &'static str,
        scopes: ScopeSupport,
        /// The integration runs a Python hook, so setup checks for python3.
        needs_python: bool,
        /// `--install-zshenv` is part of this integration.
        shell_guard: bool,
        setup: fn(&SetupOpts) -> Result<(), String>,
    }

    const HOSTS: &[HostSpec] = &[
        HostSpec { name: "claude-code", scopes: ScopeSupport::Both(Scope::Project), needs_python: true, shell_guard: true, setup: setup_claude_code },
        HostSpec { name: "cline", scopes: ScopeSupport::UserOnly("Cline's documented MCP registry and global hooks directory are user-global — omit --scope or use --scope user"), needs_python: true, shell_guard: false, setup: setup_cline },
        HostSpec { name: "codex", scopes: ScopeSupport::UserOnly("Codex is always user-global — omit --scope or use --scope user"), needs_python: false, shell_guard: true, setup: setup_codex },
        HostSpec { name: "copilot-cli", scopes: ScopeSupport::ProjectOnly("Copilot CLI loads hooks from the repo root — project-only. Omit --scope or use --scope project"), needs_python: true, shell_guard: true, setup: setup_copilot_cli },
        HostSpec { name: "continue", scopes: ScopeSupport::ProjectOnly("Continue user config is shared YAML; Tirith safely owns only a workspace .continue/mcpServers block — omit --scope or use --scope project"), needs_python: false, shell_guard: false, setup: setup_continue },
        HostSpec { name: "cursor", scopes: ScopeSupport::Both(Scope::Project), needs_python: true, shell_guard: true, setup: setup_cursor },
        HostSpec { name: "fx", scopes: ScopeSupport::UserOnly("Vercel Labs fx loads native MCP servers from its trusted user profile only — omit --scope or use --scope user"), needs_python: false, shell_guard: false, setup: setup_fx },
        HostSpec { name: "gemini-cli", scopes: ScopeSupport::Both(Scope::Project), needs_python: true, shell_guard: true, setup: setup_gemini_cli },
        HostSpec { name: "grok-build", scopes: ScopeSupport::Both(Scope::Project), needs_python: cfg!(unix), shell_guard: false, setup: setup_grok_build },
        HostSpec { name: "kiro", scopes: ScopeSupport::Both(Scope::Project), needs_python: true, shell_guard: true, setup: setup_kiro },
        HostSpec { name: "omp", scopes: ScopeSupport::UserOnly("OMP project MCP setup is deferred because OMP merges settings from multiple project providers that can suppress it — omit --scope or use --scope user"), needs_python: false, shell_guard: false, setup: setup_omp },
        HostSpec { name: "openclaw", scopes: ScopeSupport::Both(Scope::Project), needs_python: false, shell_guard: true, setup: setup_openclaw },
        HostSpec { name: "opencode", scopes: ScopeSupport::Both(Scope::Project), needs_python: false, shell_guard: false, setup: setup_opencode },
        // Both scopes are real: OpenHands searches `<work dir>/.openhands/hooks.json`
        // and then `~/.openhands/hooks.json`, while its MCP registry is user-level.
        HostSpec { name: "openhands", scopes: ScopeSupport::Both(Scope::User), needs_python: cfg!(unix), shell_guard: false, setup: setup_openhands },
        HostSpec { name: "pi-cli", scopes: ScopeSupport::Both(Scope::Project), needs_python: false, shell_guard: true, setup: setup_pi_cli },
        HostSpec { name: "prime-agent", scopes: ScopeSupport::UserOnly("Prime Agent executes generic MCP servers from user settings only — omit --scope or use --scope user"), needs_python: false, shell_guard: false, setup: setup_prime_agent },
        HostSpec { name: "roo-code", scopes: ScopeSupport::ProjectOnly("Roo Code's global MCP path is editor-managed; Tirith safely writes the documented project .roo/mcp.json — omit --scope or use --scope project"), needs_python: false, shell_guard: false, setup: setup_roo_code },
        HostSpec { name: "vscode", scopes: ScopeSupport::ProjectOnly("VS Code user settings use JSONC — run tirith setup vscode in your project directory instead, or configure manually"), needs_python: true, shell_guard: true, setup: setup_vscode },
        HostSpec { name: "windsurf", scopes: ScopeSupport::UserOnly("Windsurf is always user-global — omit --scope or use --scope user"), needs_python: true, shell_guard: true, setup: setup_windsurf },
    ];

    fn host_spec(tool: &str) -> Option<&'static HostSpec> {
        HOSTS.iter().find(|spec| spec.name == tool)
    }

    /// Kept as a plain list for the error text and the closest-match
    /// suggestion; pinned to `HOSTS` by a test so it cannot drift either.
    const KNOWN_TOOLS: &[&str] = &[
        "claude-code",
        "cline",
        "codex",
        "copilot-cli",
        "continue",
        "cursor",
        "fx",
        "gemini-cli",
        "grok-build",
        "kiro",
        "omp",
        "openclaw",
        "opencode",
        "openhands",
        "pi-cli",
        "prime-agent",
        "roo-code",
        "vscode",
        "windsurf",
    ];

    /// Build an error message for an unrecognized tool name, with a
    /// Levenshtein-based "did you mean" suggestion when close enough.
    fn unknown_tool_error(tool: &str) -> String {
        let mut msg = format!(
            "unknown tool '{tool}' — expected one of: {}",
            KNOWN_TOOLS.join(", ")
        );
        if let Some(suggestion) = crate::cli::suggest_closest(tool, KNOWN_TOOLS, 3) {
            msg.push_str(&format!("\n  did you mean: tirith setup {suggestion}?"));
        }
        msg
    }

    /// Scope of the setup operation.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum Scope {
        Project,
        User,
    }

    /// Options threaded through all setup helpers.
    pub struct SetupOpts {
        pub scope: Scope,
        pub with_mcp: bool,
        pub install_zshenv: bool,
        pub dry_run: bool,
        pub force: bool,
        /// A validated absolute invocation path for the current executable:
        /// preferably its stable package-manager alias, otherwise its canonical
        /// target. Setup never persists a bare command name.
        pub tirith_bin: String,
        /// Validated absolute Python invocation persisted by Python-backed
        /// hooks. A repository-prepended PATH must never choose this value.
        pub python_bin: Option<String>,
        /// When true, only refresh embedded hook scripts and gateway config.
        /// Skips MCP registration, shell profile installation, and zshenv setup.
        pub update_configs: bool,
    }

    /// Entry point for `tirith setup <tool>`.
    pub fn run(
        tool: &str,
        scope: Option<&str>,
        with_mcp: bool,
        install_zshenv: bool,
        dry_run: bool,
        force: bool,
        update_configs: bool,
    ) -> i32 {
        match run_inner(
            tool,
            scope,
            with_mcp,
            install_zshenv,
            dry_run,
            force,
            update_configs,
        ) {
            Ok(()) => {
                if tirith_core::threatdb::ThreatDb::cached().is_none() {
                    eprintln!();
                    eprintln!(
                        "Optional: Run 'tirith threat-db update' to enable malicious package detection."
                    );
                }
                0
            }
            Err(msg) => {
                eprintln!("tirith: {msg}");
                1
            }
        }
    }

    fn run_inner(
        tool: &str,
        scope: Option<&str>,
        with_mcp: bool,
        install_zshenv: bool,
        dry_run: bool,
        force: bool,
        update_configs: bool,
    ) -> Result<(), String> {
        // --with-mcp only applies to claude-code and gemini-cli.
        if with_mcp && tool != "claude-code" && tool != "gemini-cli" {
            return Err(
                "--with-mcp is only supported for claude-code and gemini-cli (other tools register MCP automatically or don't support it)"
                    .into(),
            );
        }

        let spec = host_spec(tool).ok_or_else(|| unknown_tool_error(tool))?;
        let scope = resolve_scope(tool, scope)?;

        let tirith_bin = resolve_tirith_bin(dry_run)?;

        // Persist the exact validated interpreter, never a bare `python3` that
        // the agent would resolve later from a repository-controlled PATH.
        let python_bin = if spec.needs_python {
            let names: &[&str] = if cfg!(windows) && tool == "cline" {
                &["python3", "python"]
            } else {
                &["python3"]
            };
            resolve_hook_dependency(names, "Python", dry_run)?
        } else {
            None
        };

        if install_zshenv && !spec.shell_guard {
            return Err(format!(
                "--install-zshenv is not part of the {tool} integration; use Tirith's shell setup separately when you need a shell-level guard"
            ));
        }

        if tool == "codex" {
            check_binary_on_path("codex", dry_run)?;
        }

        if install_zshenv {
            check_binary_on_path("zsh", dry_run)?;
        }

        // --update-configs implies --force (refreshing overwrites stale files).
        let effective_force = force || update_configs;

        let opts = SetupOpts {
            scope,
            with_mcp,
            install_zshenv,
            dry_run,
            force: effective_force,
            tirith_bin,
            python_bin,
            update_configs,
        };

        (spec.setup)(&opts)
    }

    /// Resolve scope for a given tool, applying defaults and validation.
    pub(super) fn resolve_scope(tool: &str, scope: Option<&str>) -> Result<Scope, String> {
        let spec = host_spec(tool).ok_or_else(|| unknown_tool_error(tool))?;
        let (default, expected) = match spec.scopes {
            ScopeSupport::Both(default) => (default, "'project' or 'user'"),
            ScopeSupport::ProjectOnly(_) => (Scope::Project, "'project'"),
            ScopeSupport::UserOnly(_) => (Scope::User, "'user'"),
        };
        let try_scope = match default {
            Scope::Project => "project",
            Scope::User => "user",
        };
        match (scope, spec.scopes) {
            (None, _) => Ok(default),
            (Some("project"), ScopeSupport::Both(_) | ScopeSupport::ProjectOnly(_)) => {
                Ok(Scope::Project)
            }
            (Some("user"), ScopeSupport::Both(_) | ScopeSupport::UserOnly(_)) => Ok(Scope::User),
            (Some("project"), ScopeSupport::UserOnly(reason))
            | (Some("user"), ScopeSupport::ProjectOnly(reason)) => Err(reason.to_string()),
            (Some(other), _) => Err(format!(
                "invalid scope '{other}' — expected {expected}\n  try: tirith setup {tool} --scope {try_scope}"
            )),
        }
    }

    /// Resolve the tirith binary path for generated configs/hooks. Prefer a
    /// stable absolute PATH alias (for example Homebrew's `bin/tirith`) only
    /// when it currently resolves to the exact executable identity that entered
    /// setup. This lets package-manager upgrades retarget the stable alias
    /// without leaving generated configuration pinned to a removed version.
    fn resolve_tirith_bin(_dry_run: bool) -> Result<String, String> {
        let current = tirith_core::trusted_child::TrustedExecutable::current().map_err(|error| {
            format!(
                "running tirith executable could not be validated for generated security configuration: {error}"
            )
        })?;
        let stable_alias = stable_current_alias_on_path(&current);
        choose_generated_tirith_bin(Some(&current), stable_alias.as_ref())
    }

    fn choose_generated_tirith_bin(
        current: Option<&tirith_core::trusted_child::TrustedExecutable>,
        stable_alias: Option<&tirith_core::trusted_child::TrustedExecutable>,
    ) -> Result<String, String> {
        if let Some(current) = current {
            current.revalidate().map_err(|error| {
                format!("running tirith executable changed during setup validation: {error}")
            })?;

            if let Some(alias) = stable_alias {
                let freshly_resolved_alias =
                    tirith_core::trusted_child::TrustedExecutable::from_absolute(
                        alias.invocation_path(),
                        &[],
                    )
                    .ok();
                let alias_is_current = alias.invocation_path().is_absolute()
                    && alias.path() == current.path()
                    && alias.revalidate().is_ok();
                let freshly_resolves_to_current = freshly_resolved_alias
                    .as_ref()
                    .is_some_and(|fresh| fresh.path() == current.path());
                let current_identity_is_still_valid = current.revalidate().is_ok();
                if alias_is_current
                    && freshly_resolves_to_current
                    && current_identity_is_still_valid
                {
                    // A non-UTF-8 alias cannot be persisted exactly. It is safe
                    // to ignore it and use the canonical target when that target
                    // has a lossless text representation.
                    if let Some(alias) = alias.invocation_path().to_str() {
                        return Ok(alias.to_owned());
                    }
                }
            }
            return path_to_utf8(current.path(), "running tirith executable");
        }

        Err(
            "running tirith executable could not be validated for generated security configuration"
                .into(),
        )
    }

    fn stable_current_alias_on_path(
        current: &tirith_core::trusted_child::TrustedExecutable,
    ) -> Option<tirith_core::trusted_child::TrustedExecutable> {
        let path_value = std::env::var_os("PATH")?;
        let candidate = tirith_core::trusted_child::TrustedExecutable::resolve_on_path(
            "tirith",
            &path_value,
            &tirith_core::trusted_child::ambient_denied_roots(),
        )
        .ok()?;
        let selected_parent = candidate.invocation_path().parent()?;
        let current_dir = std::env::current_dir().ok()?;
        let selected_path_entry = std::env::split_paths(&path_value).find(|directory| {
            let absolute = if directory.is_absolute() {
                directory.clone()
            } else {
                current_dir.join(directory)
            };
            absolute == selected_parent
        })?;
        (selected_path_entry.is_absolute()
            && candidate.invocation_path().is_absolute()
            && candidate.path() == current.path())
        .then_some(candidate)
    }

    /// Convert a native path only at a text-based configuration boundary.
    /// Lossy conversion can change the executable or file identity that setup
    /// validated, so paths that cannot be represented exactly must fail closed.
    pub(super) fn path_to_utf8(path: &Path, role: &str) -> Result<String, String> {
        path.to_str().map(str::to_owned).ok_or_else(|| {
            format!(
                "{role} path is not valid UTF-8 and cannot be persisted without changing its identity: {}",
                path.display()
            )
        })
    }

    /// Resolve a tirith path suitable for `~/.zshenv`. `.zshenv` runs before PATH setup
    /// (`.zprofile`/`.zshrc` haven't run in a non-interactive `zsh -lc`), so resolve a
    /// stable executable path rather than relying on PATH state.
    #[cfg(unix)]
    pub(super) fn resolve_tirith_bin_for_zshenv(
        tirith_bin: &str,
        _dry_run: bool,
    ) -> Result<String, String> {
        let current = tirith_core::trusted_child::TrustedExecutable::current().map_err(|error| {
            format!("running tirith executable could not be validated for zshenv enforcement: {error}")
        })?;
        let stable_alias = if Path::new(tirith_bin).is_absolute() {
            tirith_core::trusted_child::TrustedExecutable::from_absolute(
                Path::new(tirith_bin),
                &tirith_core::trusted_child::ambient_denied_roots(),
            )
            .ok()
        } else {
            None
        };
        choose_generated_tirith_bin(Some(&current), stable_alias.as_ref())
    }

    /// Test seam for the fail-closed zshenv fallback behavior when no validated
    /// executable identity is available.
    #[cfg(all(test, unix))]
    fn choose_zshenv_tirith_bin(
        _path_candidate: Option<PathBuf>,
        current_exe: Option<PathBuf>,
        _tirith_bin: &str,
        _dry_run: bool,
    ) -> Result<String, String> {
        // The running executable is the only candidate whose identity was
        // established by the invocation that entered setup. Never let a
        // repository-prepended PATH replace it with an unrelated native binary
        // that would then be baked into every non-interactive zsh invocation.
        if let Some(exe) = current_exe {
            return path_to_utf8(&exe, "running tirith executable for zshenv");
        }
        Err("running tirith executable could not be validated for zshenv enforcement".into())
    }

    #[cfg(unix)]
    fn find_executable_on_path(name: &str) -> Option<PathBuf> {
        let path_var = std::env::var_os("PATH")?;
        for dir in std::env::split_paths(&path_var) {
            let candidate = dir.join(name);
            if !is_executable_file(&candidate) {
                continue;
            }
            // Canonicalize so a symlink on PATH resolves to its real path before the
            // caller compares against `current_exe()` (npm-shadow equality-bug class).
            return candidate.canonicalize().ok().or(Some(candidate));
        }
        None
    }

    #[cfg(unix)]
    fn is_executable_file(path: &Path) -> bool {
        use std::os::unix::fs::PermissionsExt;
        let Ok(metadata) = std::fs::metadata(path) else {
            return false;
        };
        metadata.is_file() && metadata.permissions().mode() & 0o111 != 0
    }

    /// Check that a binary is available on PATH.
    /// In dry-run mode, warn but don't fail.
    fn check_binary_on_path(name: &str, dry_run: bool) -> Result<(), String> {
        let found = is_on_path(name);

        if !found {
            if dry_run {
                eprintln!("tirith: WARNING: {name} not found on PATH");
                Ok(())
            } else {
                Err(format!("{name} is required — install {name} and retry"))
            }
        } else {
            Ok(())
        }
    }

    /// Resolve a dependency that generated security configuration will execute
    /// later. The first PATH hit is authoritative: a project/temp shadow is an
    /// error, not a reason to skip ahead to a more convenient interpreter.
    fn resolve_hook_dependency(
        names: &[&str],
        label: &str,
        dry_run: bool,
    ) -> Result<Option<String>, String> {
        for name in names {
            match tirith_core::trusted_child::resolve_ambient(name) {
                Ok(executable) => {
                    executable.revalidate().map_err(|error| {
                        format!("validated {label} executable changed during setup: {error}")
                    })?;
                    return path_to_utf8(executable.invocation_path(), label).map(Some);
                }
                Err(tirith_core::trusted_child::TrustedExecutableError::NotFound(_)) => {}
                Err(error) => {
                    return Err(format!(
                        "refusing untrusted {label} executable selected from PATH: {error}"
                    ));
                }
            }
        }
        if dry_run {
            eprintln!("tirith: WARNING: {label} not found on PATH");
            Ok(None)
        } else {
            Err(format!("{label} is required — install {label} and retry"))
        }
    }

    /// Check if a binary is on PATH (cross-platform).
    fn is_on_path(name: &str) -> bool {
        #[cfg(unix)]
        {
            if name == "zsh" {
                return super::zshenv::trusted_zsh_executable().is_ok();
            }
            // Inspect PATH entries directly. Invoking a PATH-resolved shell to
            // ask it about another executable would run attacker-controlled
            // code before setup establishes the requested guard.
            find_executable_on_path(name).is_some()
        }
        #[cfg(not(unix))]
        {
            // Resolve the requested executable itself through the trusted-path
            // policy. Invoking ambient `where.exe` would execute a second,
            // repository-searchable program before setup installs any guard.
            tirith_core::trusted_child::resolve_ambient(name).is_ok()
        }
    }

    fn gateway_config_location() -> Result<(PathBuf, PathBuf), String> {
        let base = etcetera::choose_base_strategy()
            .map_err(|e| format!("could not determine config directory: {e}"))?;
        let config_root = base.config_dir();
        let gateway_path = config_root.join("tirith").join("gateway.yaml");
        Ok((config_root, gateway_path))
    }

    /// Return the immutable, content-addressed gateway path used by Codex.
    /// A registration never points at the legacy mutable `gateway.yaml`, so a
    /// future setup can publish and validate a new generation before making it
    /// live.
    pub(crate) fn codex_gateway_config_location() -> Result<(PathBuf, PathBuf), String> {
        let (config_root, legacy_path) = gateway_config_location()?;
        let digest = Sha256::digest(crate::assets::GATEWAY_YAML.as_bytes());
        let mut digest_hex = String::with_capacity(digest.len() * 2);
        for byte in digest {
            let _ = write!(&mut digest_hex, "{byte:02x}");
        }
        let gateway_path = legacy_path
            .parent()
            .ok_or_else(|| "gateway config path has no parent".to_string())?
            .join(format!("gateway-sha256-{digest_hex}.yaml"));
        Ok((config_root, gateway_path))
    }

    /// Publish and then re-read Codex's content-addressed gateway generation.
    /// Existing content at the same digest-derived name is never overwritten:
    /// different bytes indicate tampering or a hash collision and fail closed.
    pub(crate) fn publish_codex_gateway_config(dry_run: bool) -> Result<PathBuf, String> {
        let (config_root, gateway_path) = codex_gateway_config_location()?;
        publish_codex_gateway_config_at(&config_root, &gateway_path, dry_run)
    }

    pub(super) fn publish_codex_gateway_config_at(
        config_root: &Path,
        gateway_path: &Path,
        dry_run: bool,
    ) -> Result<PathBuf, String> {
        // Codex persists this path as text in its registration. Reject an
        // unrepresentable identity before transactional_update can create any
        // parent or generation file.
        path_to_utf8(gateway_path, "Codex gateway")?;
        let content = crate::assets::GATEWAY_YAML;
        let outcome = fs_helpers::transactional_update(
            gateway_path,
            config_root,
            dry_run,
            |snapshot| {
                match snapshot.text(gateway_path)? {
                    Some(existing) if existing == content => {
                        Ok(fs_helpers::FileUpdate::unchanged())
                    }
                    Some(_) => Err(format!(
                        "content-addressed gateway generation {} exists with different bytes; refusing to overwrite it",
                        gateway_path.display()
                    )),
                    None => {
                        if dry_run {
                            eprintln!(
                                "[dry-run] would publish immutable gateway config {} ({} bytes)",
                                gateway_path.display(),
                                content.len()
                            );
                        }
                        Ok(fs_helpers::FileUpdate::write_text(content.to_string(), 0o644))
                    }
                }
            },
        )?;
        if !dry_run {
            let published = fs_helpers::read_to_string_scoped(gateway_path, config_root)?;
            if published.as_deref() != Some(content) {
                return Err(format!(
                    "published gateway generation {} could not be verified byte-for-byte",
                    gateway_path.display()
                ));
            }
        }
        if let Some(annotation) = outcome.completion_annotation() {
            eprintln!(
                "tirith: published immutable gateway config {}{annotation}",
                gateway_path.display()
            );
        }
        Ok(gateway_path.to_path_buf())
    }

    /// Retire only a prior Tirith-managed content-addressed generation. Legacy
    /// `gateway.yaml` remains shared by other integrations and is deliberately
    /// not removed here.
    pub(crate) fn retire_codex_gateway_config(
        previous: &Path,
        current: &Path,
    ) -> Result<(), String> {
        if previous == current {
            return Ok(());
        }
        let (config_root, managed_current) = codex_gateway_config_location()?;
        let managed_parent = managed_current
            .parent()
            .ok_or_else(|| "Codex gateway path has no parent".to_string())?;
        if previous.parent() != Some(managed_parent) {
            return Ok(());
        }
        fs_helpers::retire_codex_gateway_generation(previous, &config_root)
    }

    /// Copy the embedded gateway config to `~/.config/tirith/gateway.yaml`.
    /// Returns the absolute path to the written file.
    pub(crate) fn copy_gateway_config(force: bool, dry_run: bool) -> Result<PathBuf, String> {
        let (config_root, gateway_path) = gateway_config_location()?;

        let content = crate::assets::GATEWAY_YAML;

        let outcome = fs_helpers::transactional_update(
            &gateway_path,
            &config_root,
            dry_run,
            |snapshot| {
                if let Some(existing) = snapshot.text(&gateway_path)? {
                    if existing == content {
                        eprintln!(
                            "tirith: {} already configured, up to date",
                            gateway_path.display()
                        );
                        return Ok(fs_helpers::FileUpdate::unchanged());
                    }
                    if !force {
                        if dry_run {
                            eprintln!(
                                "[dry-run] would error: {} exists but content differs — use --force to update",
                                gateway_path.display()
                            );
                            return Ok(fs_helpers::FileUpdate::unchanged());
                        }
                        return Err(format!(
                            "{} exists but content differs — use --force to update",
                            gateway_path.display()
                        ));
                    }
                }
                if dry_run {
                    eprintln!(
                        "[dry-run] would write {} ({} bytes)",
                        gateway_path.display(),
                        content.len()
                    );
                }
                Ok(fs_helpers::FileUpdate::write_text(
                    content.to_string(),
                    0o644,
                ))
            },
        )?;
        if let Some(annotation) = outcome.completion_annotation() {
            eprintln!("tirith: wrote {}{annotation}", gateway_path.display());
        }
        Ok(gateway_path)
    }

    pub(crate) fn setup_claude_code(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_claude_code(opts)
    }

    fn setup_codex(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_codex(opts)
    }

    fn setup_copilot_cli(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_copilot_cli(opts)
    }

    fn setup_cursor(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_cursor(opts)
    }

    fn setup_vscode(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_vscode(opts)
    }

    fn setup_gemini_cli(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_gemini_cli(opts)
    }

    fn setup_kiro(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_kiro(opts)
    }

    fn setup_openclaw(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_openclaw(opts)
    }

    fn setup_pi_cli(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_pi_cli(opts)
    }

    fn setup_prime_agent(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_prime_agent(opts)
    }

    fn setup_cline(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_cline(opts)
    }

    fn setup_continue(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_continue(opts)
    }

    fn setup_grok_build(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_grok_build(opts)
    }

    fn setup_omp(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_omp(opts)
    }

    fn setup_opencode(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_opencode(opts)
    }

    fn setup_fx(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_fx(opts)
    }

    fn setup_openhands(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_openhands(opts)
    }

    fn setup_roo_code(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_roo_code(opts)
    }

    fn setup_windsurf(opts: &SetupOpts) -> Result<(), String> {
        super::tools::setup_windsurf(opts)
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        #[test]
        fn known_tools_is_exactly_the_host_table() {
            let from_table: Vec<&str> = HOSTS.iter().map(|spec| spec.name).collect();
            assert_eq!(
                KNOWN_TOOLS,
                &from_table[..],
                "KNOWN_TOOLS must list the HOSTS rows in order; add new hosts to HOSTS"
            );
        }

        #[test]
        fn every_host_accepts_its_own_default_and_refuses_the_rest() {
            for spec in HOSTS {
                let default = resolve_scope(spec.name, None).unwrap();
                match spec.scopes {
                    ScopeSupport::Both(expected) => {
                        assert_eq!(default, expected, "{}", spec.name);
                        assert_eq!(
                            resolve_scope(spec.name, Some("project")).unwrap(),
                            Scope::Project,
                            "{}",
                            spec.name
                        );
                        assert_eq!(
                            resolve_scope(spec.name, Some("user")).unwrap(),
                            Scope::User,
                            "{}",
                            spec.name
                        );
                    }
                    ScopeSupport::ProjectOnly(reason) => {
                        assert_eq!(default, Scope::Project, "{}", spec.name);
                        assert_eq!(
                            resolve_scope(spec.name, Some("user")).unwrap_err(),
                            reason,
                            "{}",
                            spec.name
                        );
                    }
                    ScopeSupport::UserOnly(reason) => {
                        assert_eq!(default, Scope::User, "{}", spec.name);
                        assert_eq!(
                            resolve_scope(spec.name, Some("project")).unwrap_err(),
                            reason,
                            "{}",
                            spec.name
                        );
                    }
                }
                let bogus = resolve_scope(spec.name, Some("global")).unwrap_err();
                assert!(
                    bogus.contains("invalid scope 'global'"),
                    "{}: {bogus}",
                    spec.name
                );
            }
        }

        #[test]
        fn openhands_accepts_both_scopes_with_a_user_default() {
            // The hook installer exists at both scopes. A dispatcher that still
            // refused `--scope project` left the project hook unreachable from
            // the command line while the installer, its tests, and the docs all
            // assumed it could be run.
            assert_eq!(resolve_scope("openhands", None).unwrap(), Scope::User);
            assert_eq!(
                resolve_scope("openhands", Some("project")).unwrap(),
                Scope::Project
            );
            assert_eq!(
                resolve_scope("openhands", Some("user")).unwrap(),
                Scope::User
            );
        }

        #[test]
        fn wrapper_hosts_require_python() {
            // Cline and OpenHands exec the Python adapter through a wrapper.
            for name in ["cline", "openhands"] {
                let expected = name == "cline" || cfg!(unix);
                assert_eq!(host_spec(name).unwrap().needs_python, expected, "{name}");
            }
        }

        #[cfg(unix)]
        #[test]
        fn gateway_up_to_date_and_dry_run_refuse_symlinked_config_dir() {
            use crate::cli::test_harness::{with_fake_env, EnvGuard};

            with_fake_env(false, |home, _cwd| {
                let config_root = home.join(".config");
                std::fs::create_dir_all(&config_root).unwrap();
                let outside = tempfile::tempdir().unwrap();
                std::fs::write(
                    outside.path().join("gateway.yaml"),
                    crate::assets::GATEWAY_YAML,
                )
                .unwrap();
                std::os::unix::fs::symlink(outside.path(), config_root.join("tirith")).unwrap();
                let _xdg = EnvGuard::set("XDG_CONFIG_HOME", &config_root);

                for dry_run in [false, true] {
                    let result = copy_gateway_config(false, dry_run);
                    assert!(
                        result.is_err(),
                        "dry_run={dry_run} bypassed parent validation"
                    );
                }
            });
        }

        #[cfg(unix)]
        fn write_executable(path: &Path, content: &str) {
            use std::os::unix::fs::PermissionsExt;
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent).unwrap();
            }
            std::fs::write(path, content).unwrap();
            let mut perms = std::fs::metadata(path).unwrap().permissions();
            perms.set_mode(0o755);
            std::fs::set_permissions(path, perms).unwrap();
        }

        #[cfg(unix)]
        #[test]
        fn hook_dependency_refuses_the_first_repository_or_temp_path_hit() {
            use crate::cli::test_harness::{with_fake_env, EnvGuard};

            with_fake_env(true, |_home, cwd| {
                let cwd = cwd.expect("isolated cwd");
                let bin = cwd.join("bin");
                let marker = cwd.join("python-was-executed");
                let fake = bin.join("python3");
                write_executable(&fake, &format!("#!/bin/sh\ntouch '{}'\n", marker.display()));
                let _path = EnvGuard::set("PATH", &bin);

                let error = resolve_hook_dependency(&["python3"], "Python", false)
                    .expect_err("a repository-selected interpreter must fail closed");
                assert!(
                    error.contains("refusing untrusted Python executable"),
                    "{error}"
                );
                assert!(
                    !marker.exists(),
                    "dependency validation must never execute a PATH shadow"
                );
            });
        }

        #[cfg(unix)]
        #[test]
        fn generated_tirith_bin_is_canonical_absolute_current_identity() {
            let dir = tempfile::tempdir().unwrap();
            let current_path = dir.path().join("installed").join("tirith");
            write_executable(&current_path, "trusted current executable");
            let current =
                tirith_core::trusted_child::TrustedExecutable::from_absolute(&current_path, &[])
                    .unwrap();

            let resolved = choose_generated_tirith_bin(Some(&current), None).unwrap();
            assert_eq!(resolved, current.path().display().to_string());
            assert!(Path::new(&resolved).is_absolute());
            assert_ne!(resolved, "tirith");
        }

        #[cfg(target_os = "linux")]
        #[test]
        fn generated_tirith_bin_rejects_non_utf8_executable_identity() {
            use std::os::unix::ffi::OsStringExt;

            let dir = tempfile::tempdir().unwrap();
            let name = std::ffi::OsString::from_vec(b"tirith-\xff".to_vec());
            let current_path = dir.path().join(name);
            write_executable(&current_path, "trusted current executable");
            let current =
                tirith_core::trusted_child::TrustedExecutable::from_absolute(&current_path, &[])
                    .unwrap();

            let error = choose_generated_tirith_bin(Some(&current), None).unwrap_err();
            assert!(error.contains("not valid UTF-8"), "{error}");
            assert!(error.contains("cannot be persisted"), "{error}");
        }

        #[cfg(unix)]
        #[test]
        fn generated_config_path_rejects_non_utf8_identity_without_filesystem_fixture() {
            use std::os::unix::ffi::OsStringExt;

            // APFS rejects invalid UTF-8 names before a real-file fixture can
            // reach the persistence boundary. A synthetic native path tests
            // that boundary portably across Unix hosts.
            let path = PathBuf::from(std::ffi::OsString::from_vec(
                b"/tmp/tirith-generated-\xff".to_vec(),
            ));
            let error = path_to_utf8(&path, "running tirith executable").unwrap_err();
            assert!(error.contains("not valid UTF-8"), "{error}");
            assert!(error.contains("cannot be persisted"), "{error}");
        }

        #[cfg(unix)]
        #[test]
        fn generated_tirith_bin_prefers_validated_stable_alias() {
            use std::os::unix::fs::symlink;

            let dir = tempfile::tempdir().unwrap();
            let current_path = dir.path().join("installed").join("tirith");
            let path_spelling = dir.path().join("path-bin").join("tirith");
            write_executable(&current_path, "trusted current executable");
            std::fs::create_dir_all(path_spelling.parent().unwrap()).unwrap();
            symlink(&current_path, &path_spelling).unwrap();
            let current =
                tirith_core::trusted_child::TrustedExecutable::from_absolute(&current_path, &[])
                    .unwrap();
            let candidate =
                tirith_core::trusted_child::TrustedExecutable::from_absolute(&path_spelling, &[])
                    .unwrap();

            assert_eq!(candidate.path(), current.path());
            let resolved = choose_generated_tirith_bin(Some(&current), Some(&candidate)).unwrap();
            assert_eq!(resolved, path_spelling.display().to_string());
            assert!(Path::new(&resolved).is_absolute());
            assert_ne!(resolved, "tirith");
        }

        #[cfg(unix)]
        #[test]
        fn generated_tirith_bin_stable_alias_survives_upgrade_retarget() {
            use std::os::unix::fs::symlink;

            let dir = tempfile::tempdir().unwrap();
            let v1 = dir.path().join("versions/v1/tirith");
            let v2 = dir.path().join("versions/v2/tirith");
            let stable = dir.path().join("bin/tirith");
            write_executable(&v1, "trusted current executable v1");
            write_executable(&v2, "trusted current executable v2");
            std::fs::create_dir_all(stable.parent().unwrap()).unwrap();
            symlink(&v1, &stable).unwrap();

            let current_v1 =
                tirith_core::trusted_child::TrustedExecutable::from_absolute(&v1, &[]).unwrap();
            let alias_v1 =
                tirith_core::trusted_child::TrustedExecutable::from_absolute(&stable, &[]).unwrap();
            let persisted_v1 =
                choose_generated_tirith_bin(Some(&current_v1), Some(&alias_v1)).unwrap();
            assert_eq!(persisted_v1, stable.display().to_string());

            std::fs::remove_file(&stable).unwrap();
            symlink(&v2, &stable).unwrap();
            let current_v2 =
                tirith_core::trusted_child::TrustedExecutable::from_absolute(&v2, &[]).unwrap();
            let alias_v2 =
                tirith_core::trusted_child::TrustedExecutable::from_absolute(&stable, &[]).unwrap();
            let persisted_v2 =
                choose_generated_tirith_bin(Some(&current_v2), Some(&alias_v2)).unwrap();

            assert_eq!(persisted_v2, persisted_v1);
            assert_ne!(persisted_v2, current_v2.path().display().to_string());
        }

        #[cfg(target_os = "linux")]
        #[test]
        fn generated_tirith_bin_ignores_non_utf8_alias_when_canonical_is_utf8() {
            use std::os::unix::ffi::OsStringExt;
            use std::os::unix::fs::symlink;

            let dir = tempfile::tempdir().unwrap();
            let current_path = dir.path().join("installed/tirith");
            write_executable(&current_path, "trusted current executable");
            let alias_name = std::ffi::OsString::from_vec(b"tirith-\xff".to_vec());
            let alias_path = dir.path().join("bin").join(alias_name);
            std::fs::create_dir_all(alias_path.parent().unwrap()).unwrap();
            symlink(&current_path, &alias_path).unwrap();
            let current =
                tirith_core::trusted_child::TrustedExecutable::from_absolute(&current_path, &[])
                    .unwrap();
            let alias =
                tirith_core::trusted_child::TrustedExecutable::from_absolute(&alias_path, &[])
                    .unwrap();

            let resolved = choose_generated_tirith_bin(Some(&current), Some(&alias)).unwrap();
            assert_eq!(resolved, current.path().display().to_string());
        }

        #[test]
        fn generated_tirith_bin_never_falls_back_to_bare_name() {
            assert!(choose_generated_tirith_bin(None, None).is_err());
            // Whether the RUNNING binary validates depends on the host: CI
            // runners execute tests from checkout/build directories owned by a
            // different principal, which the ancestor-ownership validation
            // rightly refuses. Either outcome upholds the contract: a valid
            // current exe resolves to an absolute path, and an invalid one
            // surfaces the validation refusal — never a bare name on PATH.
            match resolve_tirith_bin(true) {
                Ok(resolved) => assert!(
                    Path::new(&resolved).is_absolute(),
                    "resolved bin must be an absolute path: {resolved}"
                ),
                Err(error) => assert!(
                    error.contains("could not be validated"),
                    "resolution may fail only by refusing validation: {error}"
                ),
            }
        }

        #[cfg(windows)]
        #[test]
        fn binary_check_never_executes_current_directory_where_exe() {
            use crate::cli::test_harness::{with_fake_env, EnvGuard};

            with_fake_env(true, |_home, cwd| {
                let cwd = cwd.unwrap();
                std::fs::copy(std::env::current_exe().unwrap(), cwd.join("where.exe")).unwrap();
                let _path = EnvGuard::set("PATH", Path::new(""));

                assert!(!is_on_path("tirith-definitely-missing-tool.exe"));
            });
        }

        #[cfg(unix)]
        #[test]
        fn zshenv_resolver_rejects_path_only_candidate_without_current_identity() {
            let dir = tempfile::tempdir().unwrap();
            let tirith = dir.path().join("tirith");
            write_executable(&tirith, "");
            assert!(choose_zshenv_tirith_bin(Some(tirith), None, "tirith", false).is_err());
        }

        #[cfg(unix)]
        #[test]
        fn zshenv_resolver_uses_current_exe_when_path_entry_is_script_wrapper() {
            let dir = tempfile::tempdir().unwrap();
            let wrapper = dir.path().join("tirith");
            let native = dir.path().join("native").join("tirith");
            write_executable(&wrapper, "#!/usr/bin/env node\n");
            write_executable(&native, "");
            let resolved =
                choose_zshenv_tirith_bin(Some(wrapper), Some(native.clone()), "tirith", false)
                    .unwrap();
            assert_eq!(resolved, native.display().to_string());
        }

        #[cfg(unix)]
        #[test]
        fn zshenv_resolver_rejects_non_utf8_executable_identity() {
            use std::os::unix::ffi::OsStringExt;

            let path = PathBuf::from(std::ffi::OsString::from_vec(
                b"/tmp/tirith-zshenv-\xff".to_vec(),
            ));
            let error = choose_zshenv_tirith_bin(None, Some(path), "tirith", false).unwrap_err();
            assert!(error.contains("not valid UTF-8"), "{error}");
            assert!(error.contains("cannot be persisted"), "{error}");
        }

        #[cfg(unix)]
        #[test]
        fn zshenv_resolver_ignores_poisoned_native_path_when_current_exe_is_known() {
            let dir = tempfile::tempdir().unwrap();
            let attacker = dir.path().join("repo-bin").join("tirith");
            let current = dir.path().join("installed").join("tirith");
            write_executable(&attacker, "native attacker placeholder");
            write_executable(&current, "trusted current executable placeholder");

            let resolved = choose_zshenv_tirith_bin(
                Some(attacker.clone()),
                Some(current.clone()),
                "tirith",
                false,
            )
            .unwrap();

            assert_eq!(resolved, current.display().to_string());
            assert_ne!(resolved, attacker.display().to_string());
        }

        #[cfg(unix)]
        #[test]
        fn zshenv_resolver_rejects_unvalidated_absolute_fallback() {
            assert!(choose_zshenv_tirith_bin(None, None, "/opt/custom/bin/tirith", false).is_err());
            assert!(choose_zshenv_tirith_bin(None, None, "tirith", true).is_err());
        }

        #[cfg(unix)]
        #[test]
        fn find_executable_on_path_canonicalizes_symlink() {
            use crate::cli::test_harness::{with_fake_env, EnvGuard};
            use std::os::unix;
            with_fake_env(false, |_home, _cwd| {
                let target_dir = tempfile::tempdir().unwrap();
                let link_dir = tempfile::tempdir().unwrap();
                let real_tirith = target_dir.path().join("tirith");
                write_executable(&real_tirith, "");

                let symlink_tirith = link_dir.path().join("tirith");
                unix::fs::symlink(&real_tirith, &symlink_tirith).unwrap();

                let _path = EnvGuard::set("PATH", link_dir.path());
                let found = find_executable_on_path("tirith")
                    .expect("symlink on PATH should be discoverable");
                let expected = real_tirith
                    .canonicalize()
                    .expect("real tirith path canonicalizes");
                assert_eq!(
                    found, expected,
                    "symlink must resolve to canonical real path"
                );
            });
        }

        #[test]
        fn resolve_scope_rejects_user_for_copilot_cli() {
            let result = resolve_scope("copilot-cli", Some("user"));
            assert!(result.is_err(), "expected Err");
            let msg = result.unwrap_err();
            assert!(
                msg.contains("project") && msg.contains("repo root"),
                "expected project-only/repo-root message, got: {msg}"
            );
        }

        #[test]
        fn resolve_scope_accepts_project_for_copilot_cli() {
            assert_eq!(
                resolve_scope("copilot-cli", Some("project")).unwrap(),
                Scope::Project
            );
            assert_eq!(resolve_scope("copilot-cli", None).unwrap(), Scope::Project);
        }

        #[test]
        fn resolve_scope_accepts_both_for_kiro() {
            assert_eq!(resolve_scope("kiro", None).unwrap(), Scope::Project);
            assert_eq!(
                resolve_scope("kiro", Some("project")).unwrap(),
                Scope::Project
            );
            assert_eq!(resolve_scope("kiro", Some("user")).unwrap(), Scope::User);
        }

        #[test]
        fn resolve_scope_pins_mcp_only_clients_to_documented_trust_scope() {
            for tool in ["prime-agent", "fx", "cline", "omp"] {
                assert_eq!(resolve_scope(tool, None).unwrap(), Scope::User, "{tool}");
                assert!(resolve_scope(tool, Some("project")).is_err(), "{tool}");
            }
            // OpenHands keeps the user default for its MCP registry but accepts
            // project scope for the per-repository hook.
            assert_eq!(resolve_scope("openhands", None).unwrap(), Scope::User);
            assert_eq!(
                resolve_scope("openhands", Some("project")).unwrap(),
                Scope::Project
            );
            for tool in ["continue", "roo-code"] {
                assert_eq!(resolve_scope(tool, None).unwrap(), Scope::Project, "{tool}");
                assert!(resolve_scope(tool, Some("user")).is_err(), "{tool}");
            }
            for tool in ["grok-build", "opencode"] {
                assert_eq!(resolve_scope(tool, None).unwrap(), Scope::Project, "{tool}");
                assert_eq!(
                    resolve_scope(tool, Some("user")).unwrap(),
                    Scope::User,
                    "{tool}"
                );
            }
        }
    }
}