codewhale-tui 0.9.8

Terminal UI for open-source and open-weight coding models
Documentation
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
//! Single source of truth for skill root enumeration, ownership, scope, and
//! runtime precedence.
//!
//! Runtime discovery and (later) audit/mutation share this catalog so
//! precedence cannot drift between modules. Discovery directories are not
//! write targets: only explicitly owned CodeWhale roots are writable.

use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};

/// Stable identifier for a skill root within a catalog snapshot.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SkillRootId(String);

impl SkillRootId {
    #[must_use]
    #[allow(dead_code)] // consumed by audit/mutation in later #4651 stages
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for SkillRootId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// External harness layouts that CodeWhale can discover/audit but never owns.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CompatibleHarness {
    Agents,
    Claude,
    Cursor,
    OpenCode,
    Codex,
    DeepSeekLegacy,
    /// Flat `<workspace>/skills` layout.
    FlatProjectSkills,
}

impl CompatibleHarness {
    #[must_use]
    #[allow(dead_code)] // consumed by audit UI labels in later #4651 stages
    pub fn label(self) -> &'static str {
        match self {
            Self::Agents => "agents",
            Self::Claude => "claude",
            Self::Cursor => "cursor",
            Self::OpenCode => "opencode",
            Self::Codex => "codex",
            Self::DeepSeekLegacy => "deepseek",
            Self::FlatProjectSkills => "flat-skills",
        }
    }
}

/// Kind of skill root on disk (or logical source).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(dead_code)] // BuiltIn / ReviewedPluginSnapshot used by later #4651 stages
pub enum SkillRootKind {
    CodeWhaleProject,
    CodeWhaleGlobal,
    CompatibleProject(CompatibleHarness),
    CompatibleGlobal(CompatibleHarness),
    /// Explicitly configured `skills_dir` that is not one of the owned roots.
    Configured,
    BuiltIn,
    ReviewedPluginSnapshot,
    RegistryCache,
}

/// Whether CodeWhale may mutate files under this root.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(dead_code)] // Immutable used by later #4651 stages
pub enum SkillRootAccess {
    /// CodeWhale-owned project/global install targets.
    WritableOwned,
    /// Compatible harness roots and unclassified configured dirs — read only.
    ReadOnlyExternal,
    /// Built-in / reviewed plugin snapshot content.
    Immutable,
    /// Registry download cache — not an active install target.
    CacheOnly,
}

/// Project vs global scope for owned and compatible roots.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SkillScope {
    Project,
    Global,
    /// Logical / non-filesystem sources (built-in, plugin snapshot, cache).
    Logical,
}

/// One enumerated skill root with ownership and precedence metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkillRootDescriptor {
    pub id: SkillRootId,
    pub kind: SkillRootKind,
    pub access: SkillRootAccess,
    pub scope: SkillScope,
    pub path: PathBuf,
    pub canonical_path: Option<PathBuf>,
    /// Lower value = higher precedence for first-wins runtime merge.
    pub precedence: Option<usize>,
    /// When true, runtime skill discovery includes this root.
    pub active_for_runtime: bool,
    /// When true, owned-only / compatible audit may include this root.
    pub active_for_audit: bool,
}

impl SkillRootDescriptor {
    #[must_use]
    pub fn is_writable_owned(&self) -> bool {
        self.access == SkillRootAccess::WritableOwned
    }

    /// Home-relative or workspace-relative path for UI / receipts.
    #[must_use]
    #[allow(dead_code)] // consumed by manager receipts in later #4651 stages
    pub fn safe_display_path(&self, workspace: Option<&Path>, home: Option<&Path>) -> String {
        safe_display_path(&self.path, workspace, home)
    }
}

/// Catalog of skill roots for a workspace (+ optional HOME override for tests).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkillRootCatalog {
    roots: Vec<SkillRootDescriptor>,
}

impl SkillRootCatalog {
    /// Build the full catalog: owned + compatible (including Codex audit-only)
    /// plus optional configured dir and logical sources.
    #[must_use]
    pub fn build(
        workspace: &Path,
        home_dir: Option<&Path>,
        configured_skills_dir: Option<&Path>,
    ) -> Self {
        let mut roots = Vec::new();
        let mut precedence = 0usize;

        // Runtime-compatible workspace roots (existing order — do not reorder).
        push_existing(
            &mut roots,
            &mut precedence,
            SkillRootKind::CompatibleProject(CompatibleHarness::Agents),
            SkillRootAccess::ReadOnlyExternal,
            SkillScope::Project,
            workspace.join(".agents").join("skills"),
            true,
            true,
            "project-agents",
        );
        push_existing(
            &mut roots,
            &mut precedence,
            SkillRootKind::CompatibleProject(CompatibleHarness::FlatProjectSkills),
            SkillRootAccess::ReadOnlyExternal,
            SkillScope::Project,
            workspace.join("skills"),
            true,
            true,
            "project-flat-skills",
        );
        push_existing(
            &mut roots,
            &mut precedence,
            SkillRootKind::CompatibleProject(CompatibleHarness::OpenCode),
            SkillRootAccess::ReadOnlyExternal,
            SkillScope::Project,
            workspace.join(".opencode").join("skills"),
            true,
            true,
            "project-opencode",
        );
        push_existing(
            &mut roots,
            &mut precedence,
            SkillRootKind::CompatibleProject(CompatibleHarness::Claude),
            SkillRootAccess::ReadOnlyExternal,
            SkillScope::Project,
            workspace.join(".claude").join("skills"),
            true,
            true,
            "project-claude",
        );
        push_existing(
            &mut roots,
            &mut precedence,
            SkillRootKind::CompatibleProject(CompatibleHarness::Cursor),
            SkillRootAccess::ReadOnlyExternal,
            SkillScope::Project,
            workspace.join(".cursor").join("skills"),
            true,
            true,
            "project-cursor",
        );

        // CodeWhale project root — always listed for ownership; runtime
        // CodeWhale-only mode additionally requires the path stay inside the
        // workspace (symlink escape check happens in path selection helpers).
        let project_owned = workspace.join(".codewhale").join("skills");
        push_descriptor(
            &mut roots,
            &mut precedence,
            SkillRootKind::CodeWhaleProject,
            SkillRootAccess::WritableOwned,
            SkillScope::Project,
            project_owned,
            true,
            true,
            "project-codewhale",
            true, // include even if missing — owned target may be created later
        );

        // Codex project: audit-compatible only; never active for runtime in #4651.
        push_existing(
            &mut roots,
            &mut precedence,
            SkillRootKind::CompatibleProject(CompatibleHarness::Codex),
            SkillRootAccess::ReadOnlyExternal,
            SkillScope::Project,
            workspace.join(".codex").join("skills"),
            false,
            true,
            "project-codex",
        );

        if let Some(home) = home_dir {
            push_existing(
                &mut roots,
                &mut precedence,
                SkillRootKind::CompatibleGlobal(CompatibleHarness::Agents),
                SkillRootAccess::ReadOnlyExternal,
                SkillScope::Global,
                home.join(".agents").join("skills"),
                true,
                true,
                "global-agents",
            );
            push_existing(
                &mut roots,
                &mut precedence,
                SkillRootKind::CompatibleGlobal(CompatibleHarness::Claude),
                SkillRootAccess::ReadOnlyExternal,
                SkillScope::Global,
                home.join(".claude").join("skills"),
                true,
                true,
                "global-claude",
            );

            let global_owned = home.join(".codewhale").join("skills");
            push_descriptor(
                &mut roots,
                &mut precedence,
                SkillRootKind::CodeWhaleGlobal,
                SkillRootAccess::WritableOwned,
                SkillScope::Global,
                global_owned,
                true,
                true,
                "global-codewhale",
                true,
            );

            push_existing(
                &mut roots,
                &mut precedence,
                SkillRootKind::CompatibleGlobal(CompatibleHarness::DeepSeekLegacy),
                SkillRootAccess::ReadOnlyExternal,
                SkillScope::Global,
                home.join(".deepseek").join("skills"),
                true,
                true,
                "global-deepseek",
            );

            // Codex global: audit-compatible only.
            push_existing(
                &mut roots,
                &mut precedence,
                SkillRootKind::CompatibleGlobal(CompatibleHarness::Codex),
                SkillRootAccess::ReadOnlyExternal,
                SkillScope::Global,
                home.join(".codex").join("skills"),
                false,
                true,
                "global-codex",
            );

            // Registry cache is never an active skill root.
            let cache = home.join(".codewhale").join("cache").join("skills");
            push_descriptor(
                &mut roots,
                &mut precedence,
                SkillRootKind::RegistryCache,
                SkillRootAccess::CacheOnly,
                SkillScope::Logical,
                cache,
                false,
                false,
                "registry-cache",
                false,
            );
        } else {
            // Match legacy fallback when HOME is unavailable.
            push_descriptor(
                &mut roots,
                &mut precedence,
                SkillRootKind::CodeWhaleGlobal,
                SkillRootAccess::WritableOwned,
                SkillScope::Global,
                PathBuf::from("/tmp/codewhale/skills"),
                true,
                true,
                "global-codewhale-fallback",
                true,
            );
        }

        if let Some(configured) = configured_skills_dir {
            insert_configured_root(&mut roots, workspace, home_dir, configured, &mut precedence);
        }

        Self { roots }
    }

    #[must_use]
    #[allow(dead_code)] // consumed by audit scanners in later #4651 stages
    pub fn roots(&self) -> &[SkillRootDescriptor] {
        &self.roots
    }

    /// Paths used by runtime discovery for the given mode (existing dirs only,
    /// first-wins order preserved). CodeWhale-only applies the workspace
    /// containment check for the project owned root.
    #[must_use]
    pub fn runtime_directories(
        &self,
        workspace: &Path,
        mode: super::SkillDiscoveryMode,
    ) -> Vec<PathBuf> {
        let mut out = Vec::new();
        let mut seen = HashSet::new();

        for root in &self.roots {
            if !root.active_for_runtime {
                continue;
            }
            match mode {
                super::SkillDiscoveryMode::Compatible => {}
                super::SkillDiscoveryMode::CodeWhaleOnly => {
                    if !matches!(
                        root.kind,
                        SkillRootKind::CodeWhaleProject
                            | SkillRootKind::CodeWhaleGlobal
                            | SkillRootKind::Configured
                    ) {
                        continue;
                    }
                    if root.kind == SkillRootKind::CodeWhaleProject
                        && !codewhale_project_root_is_inside_workspace(workspace, &root.path)
                    {
                        continue;
                    }
                }
            }

            if !path_is_existing_dir(&root.path) {
                continue;
            }
            let Ok(canonical) = fs::canonicalize(&root.path) else {
                continue;
            };
            if !canonical.is_dir() || !seen.insert(canonical) {
                continue;
            }
            out.push(root.path.clone());
        }
        out
    }

    /// Owned CodeWhale project + global roots (may not exist yet).
    #[must_use]
    pub fn owned_writable_roots(&self) -> Vec<&SkillRootDescriptor> {
        self.roots
            .iter()
            .filter(|r| r.is_writable_owned())
            .collect()
    }

    /// Roots eligible for owned-only audit (writable owned roots that exist).
    #[must_use]
    #[allow(dead_code)] // consumed by owned audit mode in later #4651 stages
    pub fn audit_owned_directories(&self) -> Vec<&SkillRootDescriptor> {
        self.roots
            .iter()
            .filter(|r| {
                r.is_writable_owned() && r.active_for_audit && path_is_existing_dir(&r.path)
            })
            .collect()
    }

    /// Owned + compatible roots for explicit `--compatible` audit, including
    /// Codex. Does not change runtime activation.
    #[must_use]
    pub fn audit_compatible_directories(&self) -> Vec<&SkillRootDescriptor> {
        self.roots
            .iter()
            .filter(|r| {
                r.active_for_audit
                    && !matches!(
                        r.kind,
                        SkillRootKind::RegistryCache
                            | SkillRootKind::BuiltIn
                            | SkillRootKind::ReviewedPluginSnapshot
                    )
                    && path_is_existing_dir(&r.path)
            })
            .collect()
    }
}

/// Resolve candidate skill directories for runtime discovery (existing paths
/// only), preserving historical precedence.
#[must_use]
pub fn skills_directories_with_home_and_mode(
    workspace: &Path,
    home_dir: Option<&Path>,
    mode: super::SkillDiscoveryMode,
) -> Vec<PathBuf> {
    SkillRootCatalog::build(workspace, home_dir, None).runtime_directories(workspace, mode)
}

/// CodeWhale project skills dir when it exists and stays inside the workspace.
#[must_use]
pub fn codewhale_workspace_skills_dir(workspace: &Path) -> Option<PathBuf> {
    let skills_dir = workspace.join(".codewhale").join("skills");
    codewhale_project_root_is_inside_workspace(workspace, &skills_dir).then_some(skills_dir)
}

/// Filter candidate paths to existing directories, preserving order and
/// de-duplicating by canonical path.
#[cfg(test)]
#[must_use]
pub fn existing_skill_dirs(candidates: impl IntoIterator<Item = PathBuf>) -> Vec<PathBuf> {
    let mut out = Vec::new();
    let mut seen = HashSet::new();
    for path in candidates {
        let Ok(canonical_path) = fs::canonicalize(&path) else {
            continue;
        };
        if canonical_path.is_dir() && seen.insert(canonical_path) {
            out.push(path);
        }
    }
    out
}

/// Classify a configured `skills_dir`: owned only when it is exactly a
/// CodeWhale project/global root; compatible harness paths stay read-only.
#[must_use]
pub fn classify_configured_skills_dir(
    workspace: &Path,
    home_dir: Option<&Path>,
    skills_dir: &Path,
) -> (SkillRootKind, SkillRootAccess, SkillScope) {
    let project_owned = workspace.join(".codewhale").join("skills");
    if paths_refer_to_same_dir(&project_owned, skills_dir) {
        return (
            SkillRootKind::CodeWhaleProject,
            SkillRootAccess::WritableOwned,
            SkillScope::Project,
        );
    }
    if let Some(home) = home_dir {
        let global_owned = home.join(".codewhale").join("skills");
        if paths_refer_to_same_dir(&global_owned, skills_dir) {
            return (
                SkillRootKind::CodeWhaleGlobal,
                SkillRootAccess::WritableOwned,
                SkillScope::Global,
            );
        }
    }

    if let Some(harness) = match_compatible_project(workspace, skills_dir) {
        return (
            SkillRootKind::CompatibleProject(harness),
            SkillRootAccess::ReadOnlyExternal,
            SkillScope::Project,
        );
    }
    if let Some(home) = home_dir
        && let Some(harness) = match_compatible_global(home, skills_dir)
    {
        return (
            SkillRootKind::CompatibleGlobal(harness),
            SkillRootAccess::ReadOnlyExternal,
            SkillScope::Global,
        );
    }

    // Unknown configured path: treat as external until an explicit owned-root
    // marker exists (Issue #4651 first cut — do not guess writability).
    let scope = fs::canonicalize(workspace)
        .ok()
        .map_or(SkillScope::Global, |root| {
            fs::canonicalize(skills_dir)
                .ok()
                .filter(|p| p.starts_with(&root))
                .map_or(SkillScope::Global, |_| SkillScope::Project)
        });
    (
        SkillRootKind::Configured,
        SkillRootAccess::ReadOnlyExternal,
        scope,
    )
}

#[must_use]
pub fn safe_display_path(path: &Path, workspace: Option<&Path>, home: Option<&Path>) -> String {
    // Prefer workspace when both apply so project roots stay distinct from
    // `~/...` global paths that happen to live under the same home tree.
    if let Some(workspace) = workspace
        && let Ok(stripped) = path.strip_prefix(workspace)
    {
        return format!("<workspace>/{}", stripped.display()).replace('\\', "/");
    }
    if let Some(home) = home
        && let Ok(stripped) = path.strip_prefix(home)
    {
        return format!("~/{}", stripped.display()).replace('\\', "/");
    }
    // Last resort: basename chain without expanding unrelated absolute parents.
    path.file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_else(|| path.display().to_string())
}

#[must_use]
pub fn paths_refer_to_same_dir(left: &Path, right: &Path) -> bool {
    if left == right {
        return true;
    }
    match (fs::canonicalize(left), fs::canonicalize(right)) {
        (Ok(left), Ok(right)) => left == right,
        _ => false,
    }
}

fn codewhale_project_root_is_inside_workspace(workspace: &Path, skills_dir: &Path) -> bool {
    let Ok(canonical_workspace) = fs::canonicalize(workspace) else {
        return false;
    };
    let Ok(canonical_skills) = fs::canonicalize(skills_dir) else {
        return false;
    };
    canonical_skills.is_dir() && canonical_skills.starts_with(canonical_workspace)
}

fn path_is_existing_dir(path: &Path) -> bool {
    match fs::symlink_metadata(path) {
        Ok(meta) if meta.file_type().is_symlink() => {
            fs::canonicalize(path).ok().is_some_and(|p| p.is_dir())
        }
        Ok(meta) => meta.is_dir(),
        Err(_) => false,
    }
}

fn match_compatible_project(workspace: &Path, skills_dir: &Path) -> Option<CompatibleHarness> {
    let candidates = [
        (
            CompatibleHarness::Agents,
            workspace.join(".agents").join("skills"),
        ),
        (
            CompatibleHarness::FlatProjectSkills,
            workspace.join("skills"),
        ),
        (
            CompatibleHarness::OpenCode,
            workspace.join(".opencode").join("skills"),
        ),
        (
            CompatibleHarness::Claude,
            workspace.join(".claude").join("skills"),
        ),
        (
            CompatibleHarness::Cursor,
            workspace.join(".cursor").join("skills"),
        ),
        (
            CompatibleHarness::Codex,
            workspace.join(".codex").join("skills"),
        ),
    ];
    for (harness, candidate) in candidates {
        if paths_refer_to_same_dir(&candidate, skills_dir) {
            return Some(harness);
        }
    }
    None
}

fn match_compatible_global(home: &Path, skills_dir: &Path) -> Option<CompatibleHarness> {
    let candidates = [
        (
            CompatibleHarness::Agents,
            home.join(".agents").join("skills"),
        ),
        (
            CompatibleHarness::Claude,
            home.join(".claude").join("skills"),
        ),
        (
            CompatibleHarness::DeepSeekLegacy,
            home.join(".deepseek").join("skills"),
        ),
        (CompatibleHarness::Codex, home.join(".codex").join("skills")),
    ];
    for (harness, candidate) in candidates {
        if paths_refer_to_same_dir(&candidate, skills_dir) {
            return Some(harness);
        }
    }
    None
}

#[allow(clippy::too_many_arguments)] // catalog rows keep ownership flags explicit at call sites
fn push_existing(
    roots: &mut Vec<SkillRootDescriptor>,
    precedence: &mut usize,
    kind: SkillRootKind,
    access: SkillRootAccess,
    scope: SkillScope,
    path: PathBuf,
    active_for_runtime: bool,
    active_for_audit: bool,
    id: &str,
) {
    push_descriptor(
        roots,
        precedence,
        kind,
        access,
        scope,
        path,
        active_for_runtime,
        active_for_audit,
        id,
        false,
    );
}

#[allow(clippy::too_many_arguments)] // shared constructor for the explicit catalog table above
fn push_descriptor(
    roots: &mut Vec<SkillRootDescriptor>,
    precedence: &mut usize,
    kind: SkillRootKind,
    access: SkillRootAccess,
    scope: SkillScope,
    path: PathBuf,
    active_for_runtime: bool,
    active_for_audit: bool,
    id: &str,
    include_missing: bool,
) {
    let exists = path_is_existing_dir(&path);
    if !include_missing && !exists {
        return;
    }
    let canonical_path = fs::canonicalize(&path).ok();
    let slot = *precedence;
    *precedence += 1;
    roots.push(SkillRootDescriptor {
        id: SkillRootId(id.to_string()),
        kind,
        access,
        scope,
        path,
        canonical_path,
        precedence: Some(slot),
        active_for_runtime,
        active_for_audit,
    });
}

fn insert_configured_root(
    roots: &mut Vec<SkillRootDescriptor>,
    workspace: &Path,
    home_dir: Option<&Path>,
    skills_dir: &Path,
    precedence: &mut usize,
) {
    if !path_is_existing_dir(skills_dir) {
        return;
    }
    if roots
        .iter()
        .any(|root| paths_refer_to_same_dir(&root.path, skills_dir))
    {
        return;
    }

    let (kind, access, scope) = classify_configured_skills_dir(workspace, home_dir, skills_dir);
    let workspace_root = fs::canonicalize(workspace).ok();
    let insert_at = workspace_root
        .as_ref()
        .and_then(|root| {
            roots.iter().position(|dir| {
                fs::canonicalize(&dir.path).map_or(true, |dir| !dir.starts_with(root))
            })
        })
        .unwrap_or(roots.len());

    let canonical_path = fs::canonicalize(skills_dir).ok();
    let slot = *precedence;
    *precedence += 1;
    let descriptor = SkillRootDescriptor {
        id: SkillRootId(format!("configured-{slot}")),
        kind,
        access,
        scope,
        path: skills_dir.to_path_buf(),
        canonical_path,
        precedence: Some(slot),
        active_for_runtime: true,
        active_for_audit: true,
    };
    roots.insert(insert_at, descriptor);
    // Re-number precedence after insertion so catalog order stays consistent.
    for (idx, root) in roots.iter_mut().enumerate() {
        root.precedence = Some(idx);
    }
    *precedence = roots.len();
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::skills::SkillDiscoveryMode;
    use tempfile::TempDir;

    fn write_dir(path: &Path) {
        std::fs::create_dir_all(path).unwrap();
    }

    #[test]
    fn runtime_compatible_preserves_historical_workspace_order() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path().join("ws");
        let home = tmp.path().join("home");
        write_dir(&workspace.join(".agents").join("skills"));
        write_dir(&workspace.join("skills"));
        write_dir(&workspace.join(".claude").join("skills"));
        write_dir(&workspace.join(".cursor").join("skills"));
        write_dir(&workspace.join(".codewhale").join("skills"));
        write_dir(&workspace.join(".codex").join("skills"));
        write_dir(&home.join(".codewhale").join("skills"));

        let catalog = SkillRootCatalog::build(&workspace, Some(&home), None);
        let dirs = catalog.runtime_directories(&workspace, SkillDiscoveryMode::Compatible);

        assert_eq!(
            dirs,
            vec![
                workspace.join(".agents").join("skills"),
                workspace.join("skills"),
                workspace.join(".claude").join("skills"),
                workspace.join(".cursor").join("skills"),
                workspace.join(".codewhale").join("skills"),
                home.join(".codewhale").join("skills"),
            ]
        );
        assert!(
            !dirs
                .iter()
                .any(|p| p == &workspace.join(".codex").join("skills")),
            "codex must not activate for runtime"
        );
    }

    #[test]
    fn audit_compatible_includes_codex_without_runtime_activation() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path().join("ws");
        let home = tmp.path().join("home");
        write_dir(&workspace.join(".codewhale").join("skills"));
        write_dir(&workspace.join(".codex").join("skills"));
        write_dir(&home.join(".codewhale").join("skills"));
        write_dir(&home.join(".codex").join("skills"));

        let catalog = SkillRootCatalog::build(&workspace, Some(&home), None);
        let audit: Vec<_> = catalog
            .audit_compatible_directories()
            .into_iter()
            .map(|r| r.path.clone())
            .collect();
        assert!(audit.contains(&workspace.join(".codex").join("skills")));
        assert!(audit.contains(&home.join(".codex").join("skills")));

        let runtime = catalog.runtime_directories(&workspace, SkillDiscoveryMode::Compatible);
        assert!(!runtime.contains(&workspace.join(".codex").join("skills")));
        assert!(!runtime.contains(&home.join(".codex").join("skills")));
    }

    #[test]
    fn owned_roots_are_writable_and_codewhale_only() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path().join("ws");
        let home = tmp.path().join("home");
        write_dir(&workspace.join(".agents").join("skills"));
        write_dir(&workspace.join(".codewhale").join("skills"));
        write_dir(&home.join(".codewhale").join("skills"));
        write_dir(&home.join(".agents").join("skills"));

        let catalog = SkillRootCatalog::build(&workspace, Some(&home), None);
        let owned = catalog.owned_writable_roots();
        assert_eq!(owned.len(), 2);
        assert!(owned.iter().all(|r| r.is_writable_owned()));

        let runtime = catalog.runtime_directories(&workspace, SkillDiscoveryMode::CodeWhaleOnly);
        assert_eq!(
            runtime,
            vec![
                workspace.join(".codewhale").join("skills"),
                home.join(".codewhale").join("skills"),
            ]
        );
    }

    #[test]
    fn configured_compatible_path_stays_read_only() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path().join("ws");
        let home = tmp.path().join("home");
        let agents = workspace.join(".agents").join("skills");
        write_dir(&workspace);
        write_dir(&agents);

        let (kind, access, scope) =
            classify_configured_skills_dir(&workspace, Some(&home), &agents);
        assert_eq!(
            kind,
            SkillRootKind::CompatibleProject(CompatibleHarness::Agents)
        );
        assert_eq!(access, SkillRootAccess::ReadOnlyExternal);
        assert_eq!(scope, SkillScope::Project);
    }

    #[test]
    fn safe_display_path_prefers_home_then_workspace() {
        let home = PathBuf::from("/home/user");
        let workspace = home.join("proj");
        let path = home.join(".codewhale").join("skills");
        assert_eq!(
            safe_display_path(&path, Some(&workspace), Some(&home)),
            "~/.codewhale/skills"
        );
        let project = workspace.join(".codewhale").join("skills");
        assert_eq!(
            safe_display_path(&project, Some(&workspace), Some(&home)),
            "<workspace>/.codewhale/skills"
        );
    }
}