shared-context-engineering 0.3.0

Shared Context Engineering CLI
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
use anyhow::{bail, Context, Result};
use serde_json::json;
use std::{
    fs,
    path::{Path, PathBuf},
};

use crate::services::style::{label, success, value};
use crate::services::{default_paths, default_paths::RepoPaths};

pub mod command;

/// Canonical JSON payload for a newly bootstrapped repo-local `.sce/config.json`.
/// Contains only the `$schema` declaration pointing to the SCE config JSON Schema.
fn repo_local_config_bootstrap_payload() -> String {
    format!(
        "{{\n  \"$schema\": \"{}/config.json\"\n}}\n",
        crate::services::agent_trace::SCE_WEB_BASE_URL
    )
}

pub const NAME: &str = "setup";

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SetupTarget {
    OpenCode,
    Claude,
    Both,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EmbeddedAsset {
    pub relative_path: &'static str,
    pub bytes: &'static [u8],
    pub sha256: [u8; 32],
}

#[allow(dead_code)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RequiredHookAsset {
    PreCommit,
    CommitMsg,
    PostCommit,
}

include!(concat!(env!("OUT_DIR"), "/setup_embedded_assets.rs"));

pub fn iter_required_hook_assets() -> std::slice::Iter<'static, EmbeddedAsset> {
    HOOK_EMBEDDED_ASSETS.iter()
}

#[allow(dead_code)]
pub fn get_required_hook_asset(hook: RequiredHookAsset) -> Option<&'static EmbeddedAsset> {
    let hook_name = match hook {
        RequiredHookAsset::PreCommit => default_paths::hook_dir::PRE_COMMIT,
        RequiredHookAsset::CommitMsg => default_paths::hook_dir::COMMIT_MSG,
        RequiredHookAsset::PostCommit => default_paths::hook_dir::POST_COMMIT,
    };

    HOOK_EMBEDDED_ASSETS
        .iter()
        .find(|asset| asset.relative_path == hook_name)
}

pub enum EmbeddedAssetSelectionIter {
    One(std::slice::Iter<'static, EmbeddedAsset>),
    Both(
        std::iter::Chain<
            std::slice::Iter<'static, EmbeddedAsset>,
            std::slice::Iter<'static, EmbeddedAsset>,
        >,
    ),
}

impl Iterator for EmbeddedAssetSelectionIter {
    type Item = &'static EmbeddedAsset;

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            Self::One(iter) => iter.next(),
            Self::Both(iter) => iter.next(),
        }
    }
}

pub fn iter_embedded_assets_for_setup_target(target: SetupTarget) -> EmbeddedAssetSelectionIter {
    match target {
        SetupTarget::OpenCode => EmbeddedAssetSelectionIter::One(OPENCODE_EMBEDDED_ASSETS.iter()),
        SetupTarget::Claude => EmbeddedAssetSelectionIter::One(CLAUDE_EMBEDDED_ASSETS.iter()),
        SetupTarget::Both => EmbeddedAssetSelectionIter::Both(
            OPENCODE_EMBEDDED_ASSETS
                .iter()
                .chain(CLAUDE_EMBEDDED_ASSETS.iter()),
        ),
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SetupMode {
    Interactive,
    NonInteractive(SetupTarget),
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SetupDispatch {
    Proceed(SetupMode),
    Cancelled,
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[allow(clippy::struct_excessive_bools)]
pub struct SetupCliOptions {
    pub help: bool,
    pub non_interactive: bool,
    pub opencode: bool,
    pub claude: bool,
    pub both: bool,
    pub hooks: bool,
    pub repo_path: Option<PathBuf>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SetupRequest {
    pub config_mode: Option<SetupMode>,
    pub install_hooks: bool,
    pub hooks_repo_path: Option<PathBuf>,
}

pub fn resolve_setup_request(options: SetupCliOptions) -> Result<SetupRequest> {
    if options.repo_path.is_some() && !options.hooks {
        bail!(
            "Option '--repo' requires '--hooks'. Try: run 'sce setup --hooks --repo <path>' or remove '--repo'."
        );
    }

    let mut selected_targets = Vec::new();

    if options.opencode {
        selected_targets.push(SetupTarget::OpenCode);
    }
    if options.claude {
        selected_targets.push(SetupTarget::Claude);
    }
    if options.both {
        selected_targets.push(SetupTarget::Both);
    }

    if selected_targets.len() > 1 {
        bail!(
            "Options '--opencode', '--claude', and '--both' are mutually exclusive. Try: choose exactly one target flag (for example 'sce setup --opencode --non-interactive') or omit all target flags for interactive mode."
        );
    }

    if options.non_interactive && selected_targets.is_empty() && !options.hooks {
        bail!(
            "Option '--non-interactive' requires a target flag. Try: 'sce setup --opencode --non-interactive', 'sce setup --claude --non-interactive', or 'sce setup --both --non-interactive'."
        );
    }

    let config_mode = match selected_targets.as_slice() {
        [target] => Some(SetupMode::NonInteractive(*target)),
        [] if options.hooks => None,
        [] => Some(SetupMode::Interactive),
        _ => unreachable!("target count already validated"),
    };

    let install_hooks = options.hooks || (config_mode == Some(SetupMode::Interactive));

    Ok(SetupRequest {
        config_mode,
        install_hooks,
        hooks_repo_path: options.repo_path,
    })
}

pub fn run_setup_for_mode(repository_root: &Path, mode: SetupMode) -> Result<String> {
    let target = match mode {
        SetupMode::Interactive => {
            bail!("Interactive setup mode must be resolved before installation")
        }
        SetupMode::NonInteractive(target) => target,
    };

    let outcome = install_embedded_setup_assets(repository_root, target).with_context(|| {
        format!(
            "Setup installation failed for {}",
            setup_target_label(target)
        )
    })?;

    // Persist selected integration targets in repo-local config.
    persist_integration_targets(repository_root, target).with_context(|| {
        format!(
            "Setup assets were installed for {} but failed to update repo-local config",
            setup_target_label(target)
        )
    })?;

    Ok(format_setup_install_success_message(&outcome))
}

/// Preflight check that verifies the given directory is inside a git repository.
/// Returns the resolved repository root path on success.
/// Returns an actionable error telling the operator to run `git init` on failure.
pub fn ensure_git_repository(directory: &Path) -> Result<PathBuf> {
    install::ensure_git_repository(directory)
}

/// Bootstraps the repo-local `.sce/config.json` file if it does not already exist.
///
/// Creates the `.sce/` parent directory as needed, then writes the canonical
/// schema-only JSON payload. If the file already exists, it is left untouched.
pub fn bootstrap_repo_local_config(repository_root: &Path) -> Result<()> {
    let repo_paths = RepoPaths::new(repository_root);
    let config_file = repo_paths.sce_config_file();

    if config_file.exists() {
        return Ok(());
    }

    let sce_dir = repo_paths.sce_dir();
    fs::create_dir_all(&sce_dir).with_context(|| {
        format!(
            "Failed to create repo-local config directory '{}'",
            sce_dir.display()
        )
    })?;

    fs::write(&config_file, repo_local_config_bootstrap_payload()).with_context(|| {
        format!(
            "Failed to write repo-local config file '{}'",
            config_file.display()
        )
    })?;

    Ok(())
}

fn format_setup_install_success_message(outcome: &SetupInstallOutcome) -> String {
    let selected_targets = outcome
        .target_results
        .iter()
        .map(|result| setup_target_label(result.target))
        .collect::<Vec<_>>()
        .join(", ");

    let mut lines = vec![
        format!("{}", success("Setup completed successfully.")),
        format!(
            "{} {}",
            label("Selected target(s):"),
            value(&selected_targets)
        ),
    ];

    for result in &outcome.target_results {
        lines.push(format!(
            "- {}: {} {} {} '{}'",
            label(&format!("{}:", setup_target_label(result.target))),
            success("installed"),
            value(&format!("{} file(s) to", result.installed_file_count)),
            value("'"),
            value(&format!("{}'", result.destination_root.display()))
        ));
    }

    lines.join("\n")
}

pub fn format_required_hook_install_success_message(
    outcome: &RequiredHooksInstallOutcome,
) -> String {
    let mut lines = vec![
        format!("{}", success("Hook setup completed successfully.")),
        format!(
            "{} {}",
            label("Repository root:"),
            value(&format!("'{}'", outcome.repository_root.display()))
        ),
        format!(
            "{} {}",
            label("Hooks directory:"),
            value(&format!("'{}'", outcome.hooks_directory.display()))
        ),
    ];

    for result in &outcome.hook_results {
        let status_text = required_hook_status_label(result.status);
        let styled_status = match result.status {
            RequiredHookInstallStatus::Installed | RequiredHookInstallStatus::Updated => {
                success(status_text)
            }
            RequiredHookInstallStatus::Skipped => value(status_text),
        };
        lines.push(format!(
            "- {}: {} {} '{}'",
            label(&format!("{}:", result.hook_name)),
            styled_status,
            value("at"),
            value(&format!("'{}'", result.hook_path.display()))
        ));
    }

    lines.join("\n")
}

fn required_hook_status_label(status: RequiredHookInstallStatus) -> &'static str {
    match status {
        RequiredHookInstallStatus::Installed => "installed",
        RequiredHookInstallStatus::Updated => "updated",
        RequiredHookInstallStatus::Skipped => "skipped",
    }
}

fn setup_target_label(target: SetupTarget) -> &'static str {
    match target {
        SetupTarget::OpenCode => "OpenCode",
        SetupTarget::Claude => "Claude",
        SetupTarget::Both => "Both",
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SetupInstallTargetResult {
    pub target: SetupTarget,
    pub destination_root: PathBuf,
    pub installed_file_count: usize,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SetupInstallOutcome {
    pub target_results: Vec<SetupInstallTargetResult>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RequiredHookInstallStatus {
    Installed,
    Updated,
    Skipped,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RequiredHookInstallResult {
    pub hook_name: String,
    pub hook_path: PathBuf,
    pub status: RequiredHookInstallStatus,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RequiredHooksInstallOutcome {
    pub repository_root: PathBuf,
    pub hooks_directory: PathBuf,
    pub hook_results: Vec<RequiredHookInstallResult>,
}

pub fn install_required_git_hooks(repository_root: &Path) -> Result<RequiredHooksInstallOutcome> {
    install::install_required_git_hooks(repository_root)
}

pub fn install_embedded_setup_assets(
    repository_root: &Path,
    target: SetupTarget,
) -> Result<SetupInstallOutcome> {
    install::install_embedded_setup_assets(repository_root, target)
}

pub(crate) fn setup_install_recovery_guidance(
    target: SetupTarget,
    destination_root: &Path,
) -> String {
    format!(
        "Setup for {} does not create backups. Recover '{}' from version control if needed.",
        setup_target_label(target),
        destination_root.display()
    )
}

pub(crate) fn hook_install_recovery_guidance(hook_path: &Path) -> String {
    format!(
        "Hook setup does not create backups. Recover '{}' from version control if needed.",
        hook_path.display()
    )
}

pub(crate) fn cleanup_path_if_exists(path: &Path) {
    let cleanup_result = if path.is_dir() {
        fs::remove_dir_all(path)
    } else {
        fs::remove_file(path)
    };

    // Best-effort cleanup; log errors but don't fail the operation
    if let Err(e) = cleanup_result {
        eprintln!(
            "Warning: Failed to clean up temporary path '{}': {}",
            path.display(),
            e
        );
    }
}

pub(crate) fn concrete_targets_for(target: SetupTarget) -> &'static [SetupTarget] {
    match target {
        SetupTarget::OpenCode => &[SetupTarget::OpenCode],
        SetupTarget::Claude => &[SetupTarget::Claude],
        SetupTarget::Both => &[SetupTarget::OpenCode, SetupTarget::Claude],
    }
}

/// Convert a concrete [`SetupTarget`] (not `Both`) to its canonical
/// `integrations.target` string representation.
fn integration_target_id_str(target: SetupTarget) -> &'static str {
    match target {
        SetupTarget::OpenCode => "opencode",
        SetupTarget::Claude => "claude",
        SetupTarget::Both => {
            unreachable!("integration_target_id_str must not be called with SetupTarget::Both")
        }
    }
}

/// Persist a successfully installed setup target into the repo-local config file.
///
/// Reads the existing `.sce/config.json`, merges the new concrete target(s) into
/// `integrations.target` (deduped, preserving existing unrelated fields),
/// and writes the file back. Creates the file with the bootstrap payload
/// if it does not already exist.
pub fn persist_integration_targets(repository_root: &Path, target: SetupTarget) -> Result<()> {
    let repo_paths = RepoPaths::new(repository_root);
    let config_file = repo_paths.sce_config_file();

    // Read existing config or start with bootstrap payload.
    let raw = if config_file.exists() {
        fs::read_to_string(&config_file)
            .with_context(|| format!("Failed to read config file '{}'", config_file.display()))?
    } else {
        bootstrap_repo_local_config(repository_root)?;
        fs::read_to_string(&config_file)
            .with_context(|| format!("Failed to read config file '{}'", config_file.display()))?
    };

    let mut config: serde_json::Value = serde_json::from_str(&raw).with_context(|| {
        format!(
            "Config file '{}' must contain valid JSON.",
            config_file.display()
        )
    })?;

    let config_obj = config.as_object_mut().with_context(|| {
        format!(
            "Config file '{}' must contain a top-level JSON object.",
            config_file.display()
        )
    })?;

    // Collect existing integration target values, if any.
    let mut existing_targets: Vec<String> = config_obj
        .get("integrations")
        .and_then(|i| i.get("target"))
        .and_then(|t| t.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    // Add new concrete targets (expanding Both), deduping as we go.
    let new_targets = concrete_targets_for(target);
    for concrete in new_targets {
        let id_str = integration_target_id_str(*concrete);
        let id_owned = id_str.to_string();
        if !existing_targets.contains(&id_owned) {
            existing_targets.push(id_owned);
        }
    }

    // Write the merged integrations block back.
    config_obj.insert(
        "integrations".to_string(),
        json!({ "target": existing_targets }),
    );

    let updated = serde_json::to_string_pretty(&config).with_context(|| {
        format!(
            "Failed to serialize updated config for '{}'",
            config_file.display()
        )
    })? + "\n";

    fs::write(&config_file, updated)
        .with_context(|| format!("Failed to write config file '{}'", config_file.display()))?;

    Ok(())
}

mod install {
    use anyhow::{bail, Context, Result};
    use std::{
        fs, io,
        path::{Component, Path, PathBuf},
        process::Command,
        time::{SystemTime, UNIX_EPOCH},
    };

    use crate::services::default_paths::InstallTargetPaths;
    use crate::services::security::{ensure_directory_is_writable, redact_sensitive_text};

    use super::{
        cleanup_path_if_exists, concrete_targets_for, hook_install_recovery_guidance,
        iter_embedded_assets_for_setup_target, iter_required_hook_assets,
        setup_install_recovery_guidance, EmbeddedAsset, RequiredHookInstallResult,
        RequiredHookInstallStatus, RequiredHooksInstallOutcome, SetupInstallOutcome,
        SetupInstallTargetResult, SetupTarget,
    };

    pub(super) fn prepare_setup_hooks_repository(repository_root: &Path) -> Result<PathBuf> {
        let normalized_repository_root = normalize_user_repository_path(repository_root)?;
        resolve_git_repository_root(&normalized_repository_root)
    }

    pub(super) fn ensure_git_repository(directory: &Path) -> Result<PathBuf> {
        resolve_git_repository_root(directory)
    }

    pub(super) fn install_required_git_hooks(
        repository_root: &Path,
    ) -> Result<RequiredHooksInstallOutcome> {
        let resolved_repository_root = prepare_setup_hooks_repository(repository_root)?;
        install_required_git_hooks_in_resolved_repository(&resolved_repository_root, |from, to| {
            fs::rename(from, to)
        })
    }

    pub(super) fn install_embedded_setup_assets(
        repository_root: &Path,
        target: SetupTarget,
    ) -> Result<SetupInstallOutcome> {
        install_embedded_setup_assets_with_rename(repository_root, target, |from, to| {
            fs::rename(from, to)
        })
    }

    fn install_required_git_hooks_in_resolved_repository<F>(
        resolved_repository_root: &Path,
        mut rename_fn: F,
    ) -> Result<RequiredHooksInstallOutcome>
    where
        F: FnMut(&Path, &Path) -> io::Result<()>,
    {
        ensure_directory_is_writable(resolved_repository_root, "repository root")?;
        let hooks_directory = resolve_git_hooks_directory(resolved_repository_root)?;
        fs::create_dir_all(&hooks_directory).with_context(|| {
            format!(
                "Failed to create git hooks directory '{}'",
                hooks_directory.display()
            )
        })?;
        ensure_directory_is_writable(&hooks_directory, "git hooks directory")?;

        let mut hook_results = Vec::new();
        for hook_asset in iter_required_hook_assets() {
            let hook_result = install_single_required_hook_with_rename(
                &hooks_directory,
                hook_asset,
                &mut rename_fn,
            )?;
            hook_results.push(hook_result);
        }

        Ok(RequiredHooksInstallOutcome {
            repository_root: resolved_repository_root.to_path_buf(),
            hooks_directory,
            hook_results,
        })
    }

    fn install_single_required_hook_with_rename<F>(
        hooks_directory: &Path,
        hook_asset: &EmbeddedAsset,
        rename_fn: &mut F,
    ) -> Result<RequiredHookInstallResult>
    where
        F: FnMut(&Path, &Path) -> io::Result<()>,
    {
        validate_embedded_relative_path(hook_asset.relative_path)?;

        let hook_path = hooks_directory.join(hook_asset.relative_path);
        let existing_metadata = fs::metadata(&hook_path).ok();

        if existing_metadata
            .as_ref()
            .is_some_and(std::fs::Metadata::is_file)
        {
            let existing_bytes = fs::read(&hook_path).with_context(|| {
                format!("Failed to read existing hook '{}'", hook_path.display())
            })?;
            let executable = is_executable_file(&hook_path)?;

            if existing_bytes == hook_asset.bytes && executable {
                return Ok(RequiredHookInstallResult {
                    hook_name: hook_asset.relative_path.to_string(),
                    hook_path,
                    status: RequiredHookInstallStatus::Skipped,
                });
            }
        } else if existing_metadata.is_some() {
            bail!(
                "Existing hook target '{}' is not a file",
                hook_path.display()
            );
        }

        let hook_staging_path =
            create_hook_staging_path(hooks_directory, hook_asset.relative_path)?;
        if let Err(error) = write_hook_payload_to_staging(&hook_staging_path, hook_asset.bytes) {
            cleanup_path_if_exists(&hook_staging_path);
            return Err(error);
        }

        if existing_metadata.is_none() {
            if let Err(error) = rename_fn(&hook_staging_path, &hook_path).with_context(|| {
                format!(
                    "Failed to install required hook '{}' at '{}'",
                    hook_asset.relative_path,
                    hook_path.display()
                )
            }) {
                cleanup_path_if_exists(&hook_staging_path);
                return Err(error);
            }

            return Ok(RequiredHookInstallResult {
                hook_name: hook_asset.relative_path.to_string(),
                hook_path,
                status: RequiredHookInstallStatus::Installed,
            });
        }

        remove_existing_install_target(&hook_path).with_context(|| {
            format!(
                "Failed to replace existing hook '{}' without creating a backup",
                hook_path.display()
            )
        })?;

        if let Err(error) = rename_fn(&hook_staging_path, &hook_path).with_context(|| {
            format!(
                "Failed to update required hook '{}' at '{}'",
                hook_asset.relative_path,
                hook_path.display()
            )
        }) {
            cleanup_path_if_exists(&hook_staging_path);
            return Err(error.context(hook_install_recovery_guidance(&hook_path)));
        }

        Ok(RequiredHookInstallResult {
            hook_name: hook_asset.relative_path.to_string(),
            hook_path,
            status: RequiredHookInstallStatus::Updated,
        })
    }

    fn write_hook_payload_to_staging(staging_path: &Path, bytes: &[u8]) -> Result<()> {
        fs::write(staging_path, bytes).with_context(|| {
            format!(
                "Failed to write staged hook payload '{}'",
                staging_path.display()
            )
        })?;
        ensure_executable_permissions(staging_path)?;
        Ok(())
    }

    fn create_hook_staging_path(hooks_directory: &Path, hook_name: &str) -> Result<PathBuf> {
        let epoch_nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .context("System clock is before UNIX_EPOCH")?
            .as_nanos();
        let sanitized_hook_name = hook_name.replace('/', "-");

        for attempt in 0..1000_u16 {
            let candidate = hooks_directory.join(format!(
                ".sce-hook-staging-{sanitized_hook_name}-{epoch_nanos}-{}-{attempt}",
                std::process::id()
            ));

            match fs::OpenOptions::new()
                .create_new(true)
                .write(true)
                .open(&candidate)
            {
                Ok(_) => return Ok(candidate),
                Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
                Err(error) => {
                    return Err(error).with_context(|| {
                        format!(
                            "Failed to allocate hook staging file '{}'",
                            candidate.display()
                        )
                    });
                }
            }
        }

        bail!(
            "Could not allocate a unique hook staging file under '{}'",
            hooks_directory.display()
        )
    }

    fn normalize_user_repository_path(repository_root: &Path) -> Result<PathBuf> {
        if repository_root.as_os_str().is_empty() {
            bail!(
                "Option '--repo' must not be empty. Try: pass a path to an existing git repository."
            );
        }

        let canonical_repository_root = fs::canonicalize(repository_root).with_context(|| {
            format!(
                "Failed to resolve repository path '{}'. Try: pass a path to an existing git repository.",
                repository_root.display()
            )
        })?;

        let metadata = fs::metadata(&canonical_repository_root).with_context(|| {
            format!(
                "Failed to inspect repository path '{}'.",
                canonical_repository_root.display()
            )
        })?;

        if !metadata.is_dir() {
            bail!(
                "Repository path '{}' is not a directory. Try: pass a path to an existing git repository.",
                canonical_repository_root.display()
            );
        }

        Ok(canonical_repository_root)
    }

    fn resolve_git_repository_root(repository_root: &Path) -> Result<PathBuf> {
        let repository_root_output = run_git_command_in_directory(
            repository_root,
            &["rev-parse", "--show-toplevel"],
            "Failed to resolve repository root. Ensure '--repo' points to an accessible git repository.",
        )
        .map_err(|error| map_setup_non_git_repository_error(repository_root, error))?;
        Ok(PathBuf::from(repository_root_output))
    }

    fn map_setup_non_git_repository_error(
        repository_root: &Path,
        error: anyhow::Error,
    ) -> anyhow::Error {
        let message = error.to_string();
        if message.contains("not a git repository") {
            anyhow::anyhow!(
                "Directory '{}' is not a git repository. Try: run 'git init' in '{}', then rerun 'sce setup'.",
                repository_root.display(),
                repository_root.display()
            )
        } else {
            error
        }
    }

    fn resolve_git_hooks_directory(repository_root: &Path) -> Result<PathBuf> {
        let hooks_directory_output = run_git_command_in_directory(
            repository_root,
            &["rev-parse", "--git-path", "hooks"],
            "Failed to resolve effective git hooks path.",
        )?;

        let hooks_directory = PathBuf::from(&hooks_directory_output);
        if hooks_directory.is_absolute() {
            return Ok(hooks_directory);
        }

        Ok(repository_root.join(hooks_directory))
    }

    fn run_git_command_in_directory(
        repository_root: &Path,
        args: &[&str],
        context_message: &str,
    ) -> Result<String> {
        let output = Command::new("git")
            .args(args)
            .current_dir(repository_root)
            .output()
            .with_context(|| {
                format!(
                    "{} (directory: '{}')",
                    context_message,
                    repository_root.display()
                )
            })?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
            let diagnostic = if stderr.is_empty() {
                String::from("git command exited with a non-zero status")
            } else {
                redact_sensitive_text(&stderr)
            };
            bail!("{context_message} {diagnostic}");
        }

        let stdout = String::from_utf8(output.stdout)
            .context("git command output contained invalid UTF-8")?
            .trim()
            .to_string();
        if stdout.is_empty() {
            bail!("{context_message} git command returned empty output");
        }

        Ok(stdout)
    }

    #[cfg(unix)]
    fn ensure_executable_permissions(path: &Path) -> Result<()> {
        use std::os::unix::fs::PermissionsExt;

        let metadata = fs::metadata(path)
            .with_context(|| format!("Failed to read metadata for '{}'", path.display()))?;
        let mut permissions = metadata.permissions();
        permissions.set_mode(permissions.mode() | 0o111);
        fs::set_permissions(path, permissions).with_context(|| {
            format!(
                "Failed to set executable permissions for '{}'",
                path.display()
            )
        })?;
        Ok(())
    }

    #[cfg(not(unix))]
    fn ensure_executable_permissions(_path: &Path) -> Result<()> {
        Ok(())
    }

    #[cfg(unix)]
    fn is_executable_file(path: &Path) -> Result<bool> {
        use std::os::unix::fs::PermissionsExt;

        let metadata = fs::metadata(path)
            .with_context(|| format!("Failed to read metadata for '{}'", path.display()))?;
        Ok(metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
    }

    #[cfg(not(unix))]
    fn is_executable_file(path: &Path) -> Result<bool> {
        let metadata = fs::metadata(path)
            .with_context(|| format!("Failed to read metadata for '{}'", path.display()))?;
        Ok(metadata.is_file())
    }

    fn install_embedded_setup_assets_with_rename<F>(
        repository_root: &Path,
        target: SetupTarget,
        mut rename_fn: F,
    ) -> Result<SetupInstallOutcome>
    where
        F: FnMut(&Path, &Path) -> io::Result<()>,
    {
        ensure_directory_is_writable(repository_root, "setup repository root")?;

        let mut target_results = Vec::new();

        for concrete_target in concrete_targets_for(target) {
            let concrete_target = *concrete_target;
            let assets: Vec<&'static EmbeddedAsset> =
                iter_embedded_assets_for_setup_target(concrete_target).collect();
            let result = install_assets_for_concrete_target_with_rename(
                repository_root,
                concrete_target,
                &assets,
                &mut rename_fn,
            )?;
            target_results.push(result);
        }

        Ok(SetupInstallOutcome { target_results })
    }

    fn install_assets_for_concrete_target_with_rename<F>(
        repository_root: &Path,
        target: SetupTarget,
        assets: &[&'static EmbeddedAsset],
        rename_fn: &mut F,
    ) -> Result<SetupInstallTargetResult>
    where
        F: FnMut(&Path, &Path) -> io::Result<()>,
    {
        let install_targets = InstallTargetPaths::new(repository_root);
        let destination_root = match target {
            SetupTarget::OpenCode => install_targets.opencode_target_dir(),
            SetupTarget::Claude => install_targets.claude_target_dir(),
            SetupTarget::Both => unreachable!("both is expanded into concrete targets"),
        };
        let staging_root = create_staging_root(repository_root, target)?;

        if let Err(error) = write_assets_to_staging(&staging_root, assets) {
            cleanup_path_if_exists(&staging_root);
            return Err(error);
        }

        if destination_root.exists() {
            remove_existing_install_target(&destination_root).with_context(|| {
                format!(
                    "Failed to replace existing setup target '{}' without creating a backup",
                    destination_root.display()
                )
            })?;
        }

        if let Err(error) = rename_fn(&staging_root, &destination_root).with_context(|| {
            format!(
                "Failed to swap staged install '{}' into destination '{}'",
                staging_root.display(),
                destination_root.display()
            )
        }) {
            cleanup_path_if_exists(&staging_root);
            return Err(error.context(setup_install_recovery_guidance(target, &destination_root)));
        }

        Ok(SetupInstallTargetResult {
            target,
            destination_root,
            installed_file_count: assets.len(),
        })
    }

    fn remove_existing_install_target(destination_root: &Path) -> Result<()> {
        let metadata = fs::metadata(destination_root).with_context(|| {
            format!(
                "Failed to inspect existing setup target '{}'",
                destination_root.display()
            )
        })?;

        if metadata.is_dir() {
            fs::remove_dir_all(destination_root).with_context(|| {
                format!(
                    "Failed to remove existing setup target directory '{}'",
                    destination_root.display()
                )
            })?;
        } else {
            fs::remove_file(destination_root).with_context(|| {
                format!(
                    "Failed to remove existing setup target file '{}'",
                    destination_root.display()
                )
            })?;
        }

        Ok(())
    }

    fn write_assets_to_staging(
        staging_root: &Path,
        assets: &[&'static EmbeddedAsset],
    ) -> Result<()> {
        for asset in assets {
            validate_embedded_relative_path(asset.relative_path)?;
            let destination = staging_root.join(asset.relative_path);
            let parent = destination
                .parent()
                .context("Embedded asset destination should have a parent directory")?;

            fs::create_dir_all(parent).with_context(|| {
                format!(
                    "Failed to create staged parent directory '{}'",
                    parent.display()
                )
            })?;

            fs::write(&destination, asset.bytes).with_context(|| {
                format!(
                    "Failed to write staged embedded asset '{}'",
                    destination.display()
                )
            })?;
        }

        Ok(())
    }

    fn validate_embedded_relative_path(relative_path: &str) -> Result<()> {
        let path = Path::new(relative_path);

        if path.is_absolute() {
            bail!("Embedded asset path '{relative_path}' must be relative, not absolute");
        }

        for component in path.components() {
            match component {
                Component::Normal(_) => {}
                _ => {
                    bail!("Embedded asset path '{relative_path}' contains disallowed component");
                }
            }
        }

        Ok(())
    }

    fn create_staging_root(repository_root: &Path, target: SetupTarget) -> Result<PathBuf> {
        let install_targets = InstallTargetPaths::new(repository_root);
        let target_dir = match target {
            SetupTarget::OpenCode => install_targets.opencode_target_dir(),
            SetupTarget::Claude => install_targets.claude_target_dir(),
            SetupTarget::Both => unreachable!("both is expanded into concrete targets"),
        };
        let target_label = target_dir
            .file_name()
            .and_then(|name| name.to_str())
            .context("Setup target directory should have a valid UTF-8 file name")?
            .trim_start_matches('.');
        let epoch_nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .context("System clock is before UNIX_EPOCH")?
            .as_nanos();

        for attempt in 0..1000_u16 {
            let candidate = repository_root.join(format!(
                ".sce-setup-staging-{target_label}-{epoch_nanos}-{}-{attempt}",
                std::process::id()
            ));

            match fs::create_dir(&candidate) {
                Ok(()) => return Ok(candidate),
                Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
                Err(error) => {
                    return Err(error).with_context(|| {
                        format!(
                            "Failed to create staging directory '{}'",
                            candidate.display()
                        )
                    });
                }
            }
        }

        bail!(
            "Could not allocate a unique staging directory under '{}'",
            repository_root.display()
        )
    }
}

pub trait SetupTargetPrompter {
    fn prompt_target(&self) -> Result<SetupDispatch>;
}

#[derive(Clone, Copy, Debug, Default)]
pub struct InquireSetupTargetPrompter;

impl SetupTargetPrompter for InquireSetupTargetPrompter {
    fn prompt_target(&self) -> Result<SetupDispatch> {
        prompt::prompt_target()
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum SetupPromptTarget {
    OpenCode,
    Claude,
    Both,
}

impl std::fmt::Display for SetupPromptTarget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", setup_prompt_target_label(*self))
    }
}

fn setup_prompt_target_label(target: SetupPromptTarget) -> String {
    prompt::setup_prompt_target_label(target)
}

#[allow(dead_code)]
fn setup_prompt_target_label_with_color_policy(
    target: SetupPromptTarget,
    color_enabled: bool,
) -> String {
    prompt::setup_prompt_target_label_with_color_policy(target, color_enabled)
}

#[allow(dead_code)]
fn setup_prompt_title_with_color_policy(color_enabled: bool) -> String {
    prompt::setup_prompt_title_with_color_policy(color_enabled)
}

mod prompt {
    use anyhow::{bail, Result};
    use inquire::{InquireError, Select};

    use crate::services::style::{
        prompt_label, prompt_label_with_color_policy, prompt_value_with_color_policy,
    };

    use super::{SetupDispatch, SetupMode, SetupPromptTarget, SetupTarget};

    pub(super) fn prompt_target() -> Result<SetupDispatch> {
        let options = vec![
            SetupPromptTarget::OpenCode,
            SetupPromptTarget::Claude,
            SetupPromptTarget::Both,
        ];

        let selection = Select::new(&setup_prompt_title(), options).prompt();

        match selection {
            Ok(SetupPromptTarget::OpenCode) => {
                Ok(SetupDispatch::Proceed(SetupMode::NonInteractive(SetupTarget::OpenCode)))
            }
            Ok(SetupPromptTarget::Claude) => {
                Ok(SetupDispatch::Proceed(SetupMode::NonInteractive(SetupTarget::Claude)))
            }
            Ok(SetupPromptTarget::Both) => {
                Ok(SetupDispatch::Proceed(SetupMode::NonInteractive(SetupTarget::Both)))
            }
            Err(InquireError::OperationCanceled | InquireError::OperationInterrupted) => {
                Ok(SetupDispatch::Cancelled)
            }
            Err(InquireError::NotTTY) => bail!(
                "Interactive setup requires a TTY. Re-run with '--non-interactive' and one of '--opencode', '--claude', or '--both'."
            ),
            Err(error) => Err(error.into()),
        }
    }

    pub(super) fn setup_prompt_title() -> String {
        prompt_label("Select setup target")
    }

    pub(super) fn setup_prompt_target_label(target: SetupPromptTarget) -> String {
        setup_prompt_target_label_with_color_policy(
            target,
            crate::services::style::supports_color(),
        )
    }

    pub(super) fn setup_prompt_target_label_with_color_policy(
        target: SetupPromptTarget,
        color_enabled: bool,
    ) -> String {
        let label = match target {
            SetupPromptTarget::OpenCode => "OpenCode",
            SetupPromptTarget::Claude => "Claude",
            SetupPromptTarget::Both => "Both",
        };

        prompt_value_with_color_policy(label, color_enabled)
    }

    #[allow(dead_code)]
    pub(super) fn setup_prompt_title_with_color_policy(color_enabled: bool) -> String {
        prompt_label_with_color_policy("Select setup target", color_enabled)
    }
}

pub fn resolve_setup_dispatch<P>(mode: SetupMode, prompter: &P) -> Result<SetupDispatch>
where
    P: SetupTargetPrompter,
{
    match mode {
        SetupMode::Interactive => prompter.prompt_target(),
        SetupMode::NonInteractive(target) => {
            Ok(SetupDispatch::Proceed(SetupMode::NonInteractive(target)))
        }
    }
}

pub fn setup_cancelled_text() -> String {
    value("Setup cancelled. No files were changed.")
}