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
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
//! The saved named Fleet — the single configuration concept for the whole
//! Fleet surface (v2, `schema = "fleet"`).
//!
//! A Fleet is one self-contained TOML file. It owns:
//!
//! - its **operator** route (provider + exact model + reasoning), or the
//!   explicit absence of one ("inherit the session route");
//! - its **roster**: each member's role, exact model pin or inherit policy,
//!   provider (pins only — never inferred from a model string), reasoning
//!   level, optional instructions, and capability requirements;
//! - its **save scope and source**: personal (`$CODEWHALE_HOME/fleets/`) or
//!   workspace (`.codewhale/fleets/`), with the exact file path surfaced.
//!
//! There is exactly one store. The legacy per-role profile files
//! (`~/.codewhale/agents/*.toml`, `.codewhale/agents/*.toml`,
//! `[fleet.profiles]`) and the workflow crate's `exact`/legacy named-fleet
//! files are migration/compat input only — read here, never shadowed, never
//! the runtime winner alongside a v2 Fleet.
//!
//! Selection is a scope-explicit file: `fleets/selected` under the personal
//! root is the user-global default; the same file under the workspace root is
//! an intentional workspace selection. Workspace selection wins; both are
//! labeled in the UI. A workspace selection can never hide or rewrite a
//! personal Fleet.

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

use serde::{Deserialize, Serialize};
use thiserror::Error;

use super::roster::FleetRoster;

pub const FLEET_SCHEMA_KIND: &str = "fleet";
pub const FLEET_SCHEMA_REVISION: u32 = 2;

/// The directory name used by both roots (next to `agents/` for legacy
/// profiles). Also used by the workflow crate for its own legacy/exact files;
/// v2 files in the same directory are simply a newer schema.
pub const FLEET_DIR: &str = "fleets";
pub const SELECTED_FILE: &str = "selected";

/// Where a Fleet was saved. This is the pin target: personal = user-global,
/// workspace = folder-scoped.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FleetScope {
    Personal,
    Workspace,
}

impl FleetScope {
    /// Short label for UI and receipts: "user" / "folder".
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Personal => "user",
            Self::Workspace => "folder",
        }
    }

    #[must_use]
    pub const fn long_label(self) -> &'static str {
        match self {
            Self::Personal => "user-global",
            Self::Workspace => "folder (this workspace)",
        }
    }

    #[must_use]
    pub const fn toggled(self) -> Self {
        match self {
            Self::Personal => Self::Workspace,
            Self::Workspace => Self::Personal,
        }
    }
}

/// A Fleet's own operator route. Absent = inherit the live session route.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FleetOperator {
    /// Exact provider id (a `[providers.<id>]` key or a built-in id).
    pub provider: String,
    /// Exact model id on that provider's route.
    pub model: String,
    /// Reasoning level, only when the resolved route genuinely supports it.
    /// Absent = inherit the session tier.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning: Option<String>,
}

/// Capability requirements a member must satisfy. The vocabulary is closed so
/// an unknown requirement is a specific error, never a silent reinterpretation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemberCapability {
    /// Image input: the member must run on a route that accepts images.
    Vision,
}

impl MemberCapability {
    pub const VOCABULARY: [&'static str; 1] = ["vision"];

    pub fn parse(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "vision" | "image" | "image-input" => Some(Self::Vision),
            _ => None,
        }
    }

    #[must_use]
    pub const fn wire_name(self) -> &'static str {
        match self {
            Self::Vision => "vision",
        }
    }
}

/// One roster member of a Fleet.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FleetMember {
    /// Stable member id — the role identity (e.g. `scout`, `builder`).
    pub id: String,
    /// Role label; defaults to `id` when absent.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub role: String,
    /// Exact model pin. Absent with `provider` absent = inherit the session
    /// route (the operator route when the Fleet has one).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// Exact provider id for `model`. Pins only: a member must never carry
    /// `provider` without `model` (rejected at parse), and the provider is
    /// never inferred from the model string.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    /// Reasoning level for this member, only when the resolved route
    /// supports it. Absent = inherit.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning: Option<String>,
    /// Optional instruction overlay for the role.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub instructions: Option<String>,
    /// Capability requirements, e.g. `["vision"]`. Validated against
    /// [`MemberCapability::VOCABULARY`] at parse.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires: Vec<String>,
}

/// The saved named Fleet document (`schema = "fleet"`, revision 2).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FleetFile {
    pub schema: String,
    pub schema_revision: u32,
    /// Editable display name. Unique per scope (the file slug is derived
    /// from it); the same name may exist in both scopes, distinguished by
    /// origin, never silently shadowed.
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// The Fleet's own operator route. Absent = inherit the session route.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub operator: Option<FleetOperator>,
    #[serde(default)]
    pub members: Vec<FleetMember>,
}

/// Why a Fleet file could not be used.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum FleetStoreError {
    #[error("invalid fleet: {0}")]
    Invalid(String),
    #[error(
        "fleet `{0}` is defined in both {1} and {2}; name one explicitly as {1}/{0} or {2}/{0}"
    )]
    Ambiguous(String, String, String),
    #[error("fleet file not found: {0}")]
    NotFound(String),
    #[error("failed to read {path}: {message}")]
    Io { path: String, message: String },
    #[error("failed to parse {path}: {message}")]
    Parse { path: String, message: String },
    #[error("a fleet named `{name}` already exists at {path}; rename it or choose another name")]
    NameTaken { name: String, path: String },
}

impl FleetFile {
    /// Create a validated v2 Fleet file.
    pub fn new(name: String, description: Option<String>) -> Result<Self, FleetStoreError> {
        let fleet = Self {
            schema: FLEET_SCHEMA_KIND.to_string(),
            schema_revision: FLEET_SCHEMA_REVISION,
            name,
            description,
            operator: None,
            members: Vec::new(),
        };
        fleet.validate()?;
        Ok(fleet)
    }

    /// Validate the document: name, member ids, pin symmetry, capability
    /// vocabulary. Invalid input is rejected with a specific error — never
    /// silently reinterpreted.
    pub fn validate(&self) -> Result<(), FleetStoreError> {
        if self.schema != FLEET_SCHEMA_KIND {
            return Err(FleetStoreError::Invalid(format!(
                "unknown schema `{}`; expected `{FLEET_SCHEMA_KIND}`",
                self.schema
            )));
        }
        if self.schema_revision != FLEET_SCHEMA_REVISION {
            return Err(FleetStoreError::Invalid(format!(
                "unsupported schema revision {}; this build reads revision {FLEET_SCHEMA_REVISION}",
                self.schema_revision
            )));
        }
        let name = self.name.trim();
        if name.is_empty() {
            return Err(FleetStoreError::Invalid(
                "fleet name must not be empty".to_string(),
            ));
        }
        let mut seen: BTreeMap<&str, ()> = BTreeMap::new();
        for member in &self.members {
            if member.id.trim().is_empty() {
                return Err(FleetStoreError::Invalid(
                    "member id must not be empty".to_string(),
                ));
            }
            if seen.insert(member.id.as_str(), ()).is_some() {
                return Err(FleetStoreError::Invalid(format!(
                    "duplicate member id `{}`",
                    member.id
                )));
            }
            match (&member.provider, &member.model) {
                (Some(_), None) | (None, Some(_)) => {
                    return Err(FleetStoreError::Invalid(format!(
                        "member `{}` must pin both provider and model, or neither (inherit); a lone {} is rejected",
                        member.id,
                        if member.provider.is_some() {
                            "provider"
                        } else {
                            "model"
                        }
                    )));
                }
                _ => {}
            }
            for requirement in &member.requires {
                if MemberCapability::parse(requirement).is_none() {
                    return Err(FleetStoreError::Invalid(format!(
                        "member `{}` requires unknown capability `{requirement}`; valid values: {}",
                        member.id,
                        MemberCapability::VOCABULARY.join(", ")
                    )));
                }
            }
        }
        Ok(())
    }

    /// Render the canonical TOML document.
    pub fn render_toml(&self) -> Result<String, FleetStoreError> {
        self.validate()?;
        let rendered = toml::to_string_pretty(self)
            .map_err(|e| FleetStoreError::Invalid(format!("failed to serialize fleet: {e}")))?;
        Ok(rendered)
    }

    /// Parse a v2 fleet document from TOML text.
    pub fn parse(text: &str) -> Result<Self, FleetStoreError> {
        let fleet: Self = toml::from_str(text)
            .map_err(|e| FleetStoreError::Invalid(format!("invalid fleet TOML: {e}")))?;
        fleet.validate()?;
        Ok(fleet)
    }

    /// A stable file slug derived from the display name. Safe across the
    /// filesystems Codewhale supports; collisions are detected at save.
    #[must_use]
    pub fn file_slug(&self) -> String {
        slugify(&self.name)
    }

    /// Look up a member by role id.
    #[must_use]
    pub fn member(&self, id: &str) -> Option<&FleetMember> {
        self.members.iter().find(|m| m.id == id)
    }

    /// Whether the roster contains a scout member (the fast exploratory role).
    #[must_use]
    pub fn has_scout(&self) -> bool {
        self.member("scout").is_some()
    }
}

/// Sanitize a display name into a safe file slug.
fn slugify(name: &str) -> String {
    let mut slug = String::with_capacity(name.len());
    for ch in name.trim().chars() {
        if ch.is_ascii_alphanumeric() {
            slug.push(ch.to_ascii_lowercase());
        } else if (ch.is_whitespace() || ch == '-' || ch == '_') && !slug.ends_with('-') {
            slug.push('-');
        }
    }
    while slug.ends_with('-') {
        slug.pop();
    }
    if slug.is_empty() {
        "fleet".to_string()
    } else {
        slug
    }
}

/// One entry in the Fleet list: name, scope, exact path, and health.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FleetEntry {
    pub name: String,
    pub scope: FleetScope,
    /// Exact path of the saved file.
    pub path: PathBuf,
    /// Parse failure, when the file exists but cannot be read as a v2 Fleet.
    pub parse_error: Option<String>,
    /// Whether the file is a legacy (pre-v2) named-fleet file (exact or
    /// roles map) that is read for compatibility but not editable as v2.
    pub legacy: bool,
}

/// The resolved selection: which Fleet a session should start on, and which
/// scope made the choice.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SelectedFleet {
    pub name: String,
    pub scope: FleetScope,
    pub path: PathBuf,
}

fn personal_fleets_dir() -> Result<PathBuf, FleetStoreError> {
    codewhale_config::codewhale_home()
        .map(|home| home.join(FLEET_DIR))
        .map_err(|e| FleetStoreError::Io {
            path: "$CODEWHALE_HOME/fleets".to_string(),
            message: e.to_string(),
        })
}

fn workspace_fleets_dir(workspace: &Path) -> PathBuf {
    workspace.join(".codewhale").join(FLEET_DIR)
}

/// The fleet directory for a scope, creating it if needed.
fn ensure_fleets_dir(scope: FleetScope, workspace: &Path) -> Result<PathBuf, FleetStoreError> {
    let dir = match scope {
        FleetScope::Personal => personal_fleets_dir()?,
        FleetScope::Workspace => workspace_fleets_dir(workspace),
    };
    fs::create_dir_all(&dir).map_err(|e| FleetStoreError::Io {
        path: dir.display().to_string(),
        message: e.to_string(),
    })?;
    Ok(dir)
}

/// List every named Fleet across both scopes, personal first. A file that is
/// not a v2 Fleet is listed as `legacy` with its parse error, so an old exact
/// fleet is visible — never silently absent — while the user decides whether
/// to migrate it.
pub fn list_fleets(workspace: &Path) -> Vec<FleetEntry> {
    let mut entries = Vec::new();
    if let Ok(dir) = personal_fleets_dir() {
        collect_entries(&dir, FleetScope::Personal, &mut entries);
    }
    collect_entries(
        &workspace_fleets_dir(workspace),
        FleetScope::Workspace,
        &mut entries,
    );
    entries.sort_by(|a, b| {
        a.scope
            .label()
            .cmp(b.scope.label())
            .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
    });
    entries
}

fn collect_entries(dir: &Path, scope: FleetScope, out: &mut Vec<FleetEntry>) {
    let Ok(read) = fs::read_dir(dir) else {
        return;
    };
    let mut files: Vec<PathBuf> = read
        .filter_map(|entry| entry.ok())
        .map(|entry| entry.path())
        .filter(|path| path.extension().is_some_and(|ext| ext == "toml"))
        .collect();
    files.sort();
    for path in files {
        let stem = path
            .file_stem()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_default();
        let text = fs::read_to_string(&path).ok();
        let parse_error = text
            .as_deref()
            .and_then(|text| FleetFile::parse(text).err())
            .map(|e| e.to_string());
        let legacy = parse_error.as_deref().is_some_and(|err| {
            err.contains("unknown schema") || err.contains("invalid fleet TOML")
        });
        // The row shows the Fleet's own display name, never the file slug —
        // a file saved as `Temp Fleet` must not appear as `temp-fleet`.
        let name = text
            .as_deref()
            .and_then(|text| toml::from_str::<toml::Value>(text).ok())
            .and_then(|value| {
                value
                    .get("name")
                    .and_then(|n| n.as_str())
                    .map(str::trim)
                    .filter(|n| !n.is_empty())
                    .map(str::to_string)
            })
            .unwrap_or(stem);
        out.push(FleetEntry {
            name,
            scope,
            path,
            parse_error,
            legacy,
        });
    }
}

/// Load a v2 Fleet by name. Ambiguity between the two scopes is an error that
/// names both origins — the caller (UI) resolves it by asking for a scope.
/// (Kept for the qualified-name flow and the ambiguity tests; the list/detail
/// UI resolves by scope via load_fleet_in_scope.)
#[allow(dead_code)]
pub fn load_fleet(
    name: &str,
    workspace: &Path,
) -> Result<(FleetFile, FleetScope, PathBuf), FleetStoreError> {
    let name = name.trim();
    if name.is_empty() {
        return Err(FleetStoreError::NotFound("<empty name>".to_string()));
    }
    let mut found: Vec<(FleetScope, PathBuf)> = Vec::new();
    if let Ok(dir) = personal_fleets_dir() {
        let path = dir.join(format!("{}.toml", slugify(name)));
        if path.is_file() {
            found.push((FleetScope::Personal, path));
        }
    }
    let ws_path = workspace_fleets_dir(workspace).join(format!("{}.toml", slugify(name)));
    if ws_path.is_file() {
        found.push((FleetScope::Workspace, ws_path));
    }
    if found.len() > 1 {
        return Err(FleetStoreError::Ambiguous(
            name.to_string(),
            FleetScope::Personal.label().to_string(),
            FleetScope::Workspace.label().to_string(),
        ));
    }
    let Some((scope, path)) = found.pop() else {
        return Err(FleetStoreError::NotFound(name.to_string()));
    };
    let text = fs::read_to_string(&path).map_err(|e| FleetStoreError::Io {
        path: path.display().to_string(),
        message: e.to_string(),
    })?;
    let fleet = FleetFile::parse(&text).map_err(|e| FleetStoreError::Parse {
        path: path.display().to_string(),
        message: e.to_string(),
    })?;
    Ok((fleet, scope, path))
}

/// Load a v2 Fleet by name in one explicit scope. Unlike [`load_fleet`],
/// this never resolves ambiguity — the caller already knows where the Fleet
/// lives (e.g. the row the user just picked).
pub fn load_fleet_in_scope(
    name: &str,
    scope: FleetScope,
    workspace: &Path,
) -> Result<(FleetFile, PathBuf), FleetStoreError> {
    let dir = match scope {
        FleetScope::Personal => personal_fleets_dir()?,
        FleetScope::Workspace => workspace_fleets_dir(workspace),
    };
    let path = dir.join(format!("{}.toml", slugify(name)));
    if !path.is_file() {
        return Err(FleetStoreError::NotFound(format!(
            "{} ({})",
            name,
            scope.label()
        )));
    }
    let text = fs::read_to_string(&path).map_err(|e| FleetStoreError::Io {
        path: path.display().to_string(),
        message: e.to_string(),
    })?;
    let fleet = FleetFile::parse(&text).map_err(|e| FleetStoreError::Parse {
        path: path.display().to_string(),
        message: e.to_string(),
    })?;
    Ok((fleet, path))
}

/// Load a v2 Fleet from a specific path (used by the editor on the currently
/// open entry, so the saved scope is exact). API surface for the path-based
/// editor flows; currently exercised by tests.
#[allow(dead_code)]
pub fn load_fleet_at(path: &Path) -> Result<(FleetFile, FleetScope), FleetStoreError> {
    let text = fs::read_to_string(path).map_err(|e| FleetStoreError::Io {
        path: path.display().to_string(),
        message: e.to_string(),
    })?;
    let fleet = FleetFile::parse(&text).map_err(|e| FleetStoreError::Parse {
        path: path.display().to_string(),
        message: e.to_string(),
    })?;
    let scope = if path.starts_with(personal_fleets_dir().unwrap_or_default()) {
        FleetScope::Personal
    } else {
        FleetScope::Workspace
    };
    Ok((fleet, scope))
}

/// Save a Fleet to a scope with an atomic write. Refuses to clobber a
/// different Fleet of the same slug (the name is the identity).
pub fn save_fleet(
    fleet: &FleetFile,
    scope: FleetScope,
    workspace: &Path,
) -> Result<PathBuf, FleetStoreError> {
    fleet.validate()?;
    let dir = ensure_fleets_dir(scope, workspace)?;
    let path = dir.join(format!("{}.toml", fleet.file_slug()));
    if path.is_file()
        && let Ok(text) = fs::read_to_string(&path)
        && let Ok(existing) = FleetFile::parse(&text)
        && existing.name != fleet.name
    {
        return Err(FleetStoreError::NameTaken {
            name: fleet.name.clone(),
            path: path.display().to_string(),
        });
    }
    let rendered = fleet.render_toml()?;
    atomic_write(&path, rendered.as_bytes())?;
    Ok(path)
}

/// Delete a saved Fleet (UI confirms first). Returns the removed path.
pub fn delete_fleet(
    name: &str,
    scope: FleetScope,
    workspace: &Path,
) -> Result<PathBuf, FleetStoreError> {
    let dir = match scope {
        FleetScope::Personal => personal_fleets_dir()?,
        FleetScope::Workspace => workspace_fleets_dir(workspace),
    };
    let path = dir.join(format!("{}.toml", slugify(name)));
    if !path.is_file() {
        return Err(FleetStoreError::NotFound(name.to_string()));
    }
    fs::remove_file(&path).map_err(|e| FleetStoreError::Io {
        path: path.display().to_string(),
        message: e.to_string(),
    })?;
    // A selection that pointed at the deleted Fleet must not linger: it would
    // render as a phantom selection. The write is best-effort; a leftover
    // selection is reported by the reader as missing, never as valid.
    clear_selection_if_matching(scope, workspace, name);
    Ok(path)
}

/// The active selection: workspace selection wins, then the personal
/// user-global default. Each file is scope-explicit; a workspace selection
/// can never hide the personal Fleet — the personal default is only overridden
/// for this folder, visibly.
pub fn selected_fleet(workspace: &Path) -> Option<SelectedFleet> {
    let ws_dir = workspace_fleets_dir(workspace);
    if let Some(name) = read_selection(&ws_dir) {
        // A workspace selection may name a personal Fleet (selected for this
        // folder only): resolve workspace first, then personal, and report
        // the scope the Fleet actually lives in.
        let ws_path = ws_dir.join(format!("{}.toml", slugify(&name)));
        if ws_path.is_file() {
            return Some(SelectedFleet {
                name,
                scope: FleetScope::Workspace,
                path: ws_path,
            });
        }
        if let Ok(dir) = personal_fleets_dir() {
            let personal_path = dir.join(format!("{}.toml", slugify(&name)));
            if personal_path.is_file() {
                return Some(SelectedFleet {
                    name,
                    scope: FleetScope::Personal,
                    path: personal_path,
                });
            }
        }
    }
    if let Ok(dir) = personal_fleets_dir()
        && let Some(name) = read_selection(&dir)
    {
        let path = dir.join(format!("{}.toml", slugify(&name)));
        if path.is_file() {
            return Some(SelectedFleet {
                name,
                scope: FleetScope::Personal,
                path,
            });
        }
    }
    None
}

fn read_selection(dir: &Path) -> Option<String> {
    let text = fs::read_to_string(dir.join(SELECTED_FILE)).ok()?;
    let name = text.trim();
    if name.is_empty() {
        None
    } else {
        Some(name.to_string())
    }
}

/// Write the selection for a scope. Returns the exact file written.
///
/// The selection file lives in the scope's `fleets/` directory, but the
/// Fleet it names may live in either scope: a workspace selection may point
/// at a personal Fleet (selecting it for this folder only), and a personal
/// selection always points at a personal Fleet. The validation only refuses
/// a name that exists NOWHERE — a phantom selection would be a lie.
pub fn set_selected(
    name: &str,
    scope: FleetScope,
    workspace: &Path,
) -> Result<PathBuf, FleetStoreError> {
    let dir = ensure_fleets_dir(scope, workspace)?;
    let name = name.trim();
    let exists_in_scope = |target: FleetScope| {
        let target_dir = match target {
            FleetScope::Personal => personal_fleets_dir().ok(),
            FleetScope::Workspace => Some(workspace_fleets_dir(workspace)),
        };
        target_dir
            .map(|d| d.join(format!("{}.toml", slugify(name))).is_file())
            .unwrap_or(false)
    };
    let exists = exists_in_scope(scope) || exists_in_scope(FleetScope::Personal);
    if !exists {
        return Err(FleetStoreError::NotFound(format!(
            "{} ({})",
            name,
            scope.label()
        )));
    }
    let selected = dir.join(SELECTED_FILE);
    atomic_write(&selected, name.as_bytes())?;
    Ok(selected)
}

fn clear_selection_if_matching(scope: FleetScope, workspace: &Path, name: &str) {
    let dir = match scope {
        FleetScope::Personal => personal_fleets_dir().ok(),
        FleetScope::Workspace => Some(workspace_fleets_dir(workspace)),
    };
    let Some(dir) = dir else { return };
    let selected = dir.join(SELECTED_FILE);
    if read_selection(&dir).as_deref() == Some(name.trim()) {
        let _ = fs::remove_file(selected);
    }
}

/// Atomic write: temp file in the same directory, then rename. A failed write
/// never leaves a half-written Fleet or selection.
fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), FleetStoreError> {
    let tmp = path.with_extension("tmp");
    fs::write(&tmp, bytes).map_err(|e| FleetStoreError::Io {
        path: tmp.display().to_string(),
        message: e.to_string(),
    })?;
    if let Err(e) = fs::rename(&tmp, path) {
        let _ = fs::remove_file(&tmp);
        return Err(FleetStoreError::Io {
            path: path.display().to_string(),
            message: e.to_string(),
        });
    }
    Ok(())
}

/// One row of the migration receipt: how a legacy role profile maps into the
/// new Fleet.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MigrationRow {
    /// Role id, e.g. `scout`.
    pub id: String,
    /// The pin that will be saved (model + provider, or "inherit").
    pub pin: Option<(String, String)>,
    /// The winning origin under the legacy precedence.
    pub winner: String,
    /// A lower-precedence copy with identical content — not a conflict.
    pub identical_shadow: Option<String>,
    /// A lower-precedence copy that differed and was NOT carried over.
    pub conflicting_shadow: Option<String>,
}

/// The result of migrating the legacy per-role roster into a v2 Fleet.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MigrationReceipt {
    /// The Fleet that was (or would be) saved.
    pub fleet: FleetFile,
    /// Per-role mapping, including every conflict that was resolved.
    pub rows: Vec<MigrationRow>,
    /// Path the Fleet was saved to.
    pub saved_to: PathBuf,
}

/// Build (and optionally save) a v2 Fleet from the legacy per-role roster:
/// built-ins + `[fleet.profiles]` + personal + workspace profile files.
///
/// Nothing is discarded: every role becomes a member, every pin survives, and
/// each lower-precedence copy that differed is named in the receipt. The
/// legacy files themselves are left untouched — they become migration input,
/// not live config, once a Fleet is selected.
pub fn migrate_legacy_roster(
    fleet_config: &codewhale_config::FleetConfigToml,
    workspace: &Path,
    save: bool,
    save_scope: FleetScope,
) -> Result<MigrationReceipt, FleetStoreError> {
    let roster = FleetRoster::load(fleet_config, workspace);
    let mut fleet = FleetFile::new(
        "Default".to_string(),
        Some("Migrated from the legacy per-role profile configuration.".to_string()),
    )?;
    let mut rows = Vec::new();
    for member in roster.members() {
        let profile = &member.profile;
        let (model, provider) = match (&profile.model, &profile.provider) {
            (Some(model), Some(provider)) => (Some(model.clone()), Some(provider.clone())),
            _ => (None, None),
        };
        // Legacy profiles carry no capability requirements; a migration
        // never invents one. Requirements start empty in the v2 Fleet.
        let requires: Vec<String> = Vec::new();
        let row = MigrationRow {
            id: member.id.clone(),
            pin: model
                .as_ref()
                .map(|m| (m.clone(), provider.clone().unwrap_or_default())),
            winner: member.origin.to_string(),
            identical_shadow: None,
            conflicting_shadow: None,
        };
        // Record shadowed copies (the roster already resolved them; here we
        // name them so the conflict is visible before anyone accepts it).
        let shadows: Vec<String> = roster
            .shadowed()
            .iter()
            .filter(|s| s.id == member.id)
            .map(|s| {
                format!(
                    "{} copy at {} ignored in favor of {}",
                    s.shadowed_origin,
                    s.shadowed_source.display(),
                    s.winner_origin
                )
            })
            .collect();
        let mut row = row;
        if let Some(first) = shadows.first() {
            if shadows.len() == 1 && first.contains("built-in") {
                row.identical_shadow = Some(first.clone());
            } else {
                row.conflicting_shadow = Some(shadows.join("; "));
            }
        }
        rows.push(row);
        fleet.members.push(FleetMember {
            id: member.id.clone(),
            role: profile.role.name.clone(),
            model,
            provider,
            reasoning: profile.reasoning_effort.clone(),
            instructions: profile.role.instructions.clone(),
            requires,
        });
    }
    fleet.validate()?;
    let saved_to = if save {
        save_fleet(&fleet, save_scope, workspace)?
    } else {
        match save_scope {
            FleetScope::Personal => {
                personal_fleets_dir()?.join(format!("{}.toml", fleet.file_slug()))
            }
            FleetScope::Workspace => {
                workspace_fleets_dir(workspace).join(format!("{}.toml", fleet.file_slug()))
            }
        }
    };
    Ok(MigrationReceipt {
        fleet,
        rows,
        saved_to,
    })
}

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

    /// A sealed CODEWHALE_HOME for personal-scope tests, created once per
    /// process. Tests must still hold `lock_test_env` before touching it.
    fn sealed_home() -> &'static Path {
        static HOME: OnceLock<PathBuf> = OnceLock::new();
        HOME.get_or_init(|| {
            let dir = tempfile::TempDir::new()
                .expect("temp dir for sealed home")
                .keep();
            std::fs::create_dir_all(dir.join("fleets")).expect("fleets dir");
            dir
        })
    }

    struct EnvGuard {
        prev: Option<std::ffi::OsString>,
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            // SAFETY: serialised by lock_test_env held by the caller.
            unsafe {
                match &self.prev {
                    Some(v) => std::env::set_var("CODEWHALE_HOME", v),
                    None => std::env::remove_var("CODEWHALE_HOME"),
                }
            }
        }
    }

    /// Point CODEWHALE_HOME at a sealed temp dir. Caller must hold
    /// `lock_test_env`.
    fn set_sealed_home() -> EnvGuard {
        let prev = std::env::var_os("CODEWHALE_HOME");
        // SAFETY: serialised by lock_test_env held by the caller.
        unsafe {
            std::env::set_var("CODEWHALE_HOME", sealed_home());
        }
        EnvGuard { prev }
    }

    fn sample_fleet() -> FleetFile {
        FleetFile::new("DeepSeek Flash".to_string(), None)
            .expect("valid fleet")
            .with_operator(FleetOperator {
                provider: "deepseek".to_string(),
                model: "deepseek-v4-flash".to_string(),
                reasoning: Some("low".to_string()),
            })
            .with_member(FleetMember {
                id: "scout".to_string(),
                role: "scout".to_string(),
                provider: None,
                model: None,
                reasoning: None,
                instructions: None,
                requires: Vec::new(),
            })
            .with_member(FleetMember {
                id: "builder".to_string(),
                role: "builder".to_string(),
                provider: Some("deepseek".to_string()),
                model: Some("deepseek-v4-pro".to_string()),
                reasoning: Some("high".to_string()),
                instructions: Some("Implement exactly the task slice.".to_string()),
                requires: vec!["vision".to_string()],
            })
    }

    trait FleetBuilder {
        fn with_operator(self, operator: FleetOperator) -> Self;
        fn with_member(self, member: FleetMember) -> Self;
    }

    impl FleetBuilder for FleetFile {
        fn with_operator(mut self, operator: FleetOperator) -> Self {
            self.operator = Some(operator);
            self
        }
        fn with_member(mut self, member: FleetMember) -> Self {
            self.members.push(member);
            self
        }
    }

    #[test]
    fn validation_rejects_bad_documents_with_specific_errors() {
        let _lock = crate::test_support::lock_test_env();

        // Empty name.
        let err = FleetFile::new("   ".to_string(), None).unwrap_err();
        assert!(err.to_string().contains("name must not be empty"), "{err}");

        // Duplicate member ids.
        let mut fleet = sample_fleet();
        fleet.members.push(fleet.members[0].clone());
        let err = fleet.validate().unwrap_err();
        assert!(
            err.to_string().contains("duplicate member id `scout`"),
            "{err}"
        );

        // Lone provider / lone model: never silently reinterpreted.
        let mut fleet = sample_fleet();
        fleet.members[0].provider = Some("deepseek".to_string());
        let err = fleet.validate().unwrap_err();
        assert!(
            err.to_string().contains("must pin both provider and model"),
            "{err}"
        );
        let mut fleet = sample_fleet();
        fleet.members[0].model = Some("deepseek-v4-pro".to_string());
        let err = fleet.validate().unwrap_err();
        assert!(
            err.to_string().contains("must pin both provider and model"),
            "{err}"
        );

        // Unknown capability requirement.
        let mut fleet = sample_fleet();
        fleet.members[0].requires = vec!["telepathy".to_string()];
        let err = fleet.validate().unwrap_err();
        assert!(
            err.to_string().contains("unknown capability `telepathy`"),
            "{err}"
        );
        assert!(err.to_string().contains("vision"), "{err}");
    }

    #[test]
    fn render_parse_round_trip_preserves_every_field() {
        let fleet = sample_fleet();
        let text = fleet.render_toml().expect("render");
        let parsed = FleetFile::parse(&text).expect("parse");
        assert_eq!(parsed, fleet);
        assert!(text.contains("schema = \"fleet\""));
        assert!(text.contains("schema_revision = 2"));
        assert!(text.contains("deepseek-v4-flash"));
    }

    #[test]
    fn save_load_round_trips_in_workspace_scope() {
        let _lock = crate::test_support::lock_test_env();
        let ws = tempfile::TempDir::new().unwrap();
        let fleet = sample_fleet();
        let path = save_fleet(&fleet, FleetScope::Workspace, ws.path()).expect("save");
        assert!(
            path.ends_with(".codewhale/fleets/deepseek-flash.toml"),
            "{path:?}"
        );

        let (loaded, scope, path) = load_fleet("DeepSeek Flash", ws.path()).expect("load");
        assert_eq!(loaded, fleet);
        assert_eq!(scope, FleetScope::Workspace);
        assert_eq!(path, load_fleet("DeepSeek Flash", ws.path()).unwrap().2);

        // A same-name Fleet in the personal scope makes the bare name
        // ambiguous — the reader names both origins instead of shadowing.
        let _home = set_sealed_home();
        save_fleet(&fleet, FleetScope::Personal, ws.path()).expect("save personal");
        let err = load_fleet("DeepSeek Flash", ws.path()).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("defined in both"), "{msg}");
        assert!(msg.contains("user") && msg.contains("folder"), "{msg}");
    }

    #[test]
    fn selection_is_scope_explicit_and_workspace_wins() {
        let _lock = crate::test_support::lock_test_env();
        let _home = set_sealed_home();
        let ws = tempfile::TempDir::new().unwrap();
        let fleet = sample_fleet();

        // No selection yet.
        assert!(selected_fleet(ws.path()).is_none());

        // Personal selection: the user-global default.
        save_fleet(&fleet, FleetScope::Personal, ws.path()).unwrap();
        let selected_file =
            set_selected("DeepSeek Flash", FleetScope::Personal, ws.path()).expect("select");
        assert!(
            selected_file.ends_with("fleets/selected"),
            "{selected_file:?}"
        );
        let sel = selected_fleet(ws.path()).expect("selected");
        assert_eq!(sel.scope, FleetScope::Personal);
        assert_eq!(sel.name, "DeepSeek Flash");

        // A selection naming a missing Fleet is refused — a phantom selection
        // would be a lie.
        let err = set_selected("No Such Fleet", FleetScope::Personal, ws.path()).unwrap_err();
        assert!(err.to_string().contains("No Such Fleet"), "{err}");

        // Workspace selection overrides for this folder only.
        save_fleet(&fleet, FleetScope::Workspace, ws.path()).unwrap();
        set_selected("DeepSeek Flash", FleetScope::Workspace, ws.path()).unwrap();
        let sel = selected_fleet(ws.path()).expect("selected");
        assert_eq!(sel.scope, FleetScope::Workspace);

        // Deleting the workspace Fleet clears the workspace selection; the
        // personal default reappears rather than a phantom.
        delete_fleet("DeepSeek Flash", FleetScope::Workspace, ws.path()).unwrap();
        let sel = selected_fleet(ws.path()).expect("personal default returns");
        assert_eq!(sel.scope, FleetScope::Personal);
    }

    #[test]
    fn list_marks_legacy_files_without_hiding_them() {
        let _lock = crate::test_support::lock_test_env();
        let _home = set_sealed_home();
        let ws = tempfile::TempDir::new().unwrap();

        save_fleet(&sample_fleet(), FleetScope::Personal, ws.path()).unwrap();
        // A legacy exact fleet file (workflow schema) in the same directory
        // must be listed as legacy, never silently absent.
        let legacy = r#"schema = "exact"
schema_revision = 1
name = "stopship"
members = []"#;
        std::fs::write(sealed_home().join("fleets/stopship.toml"), legacy).unwrap();

        let entries = list_fleets(ws.path());
        assert_eq!(entries.len(), 2, "{entries:?}");
        let stopship = entries
            .iter()
            .find(|e| e.name == "stopship")
            .expect("legacy fleet listed");
        assert!(stopship.legacy, "{stopship:?}");
        assert!(stopship.parse_error.is_some(), "{stopship:?}");
        let flash = entries.iter().find(|e| e.name == "DeepSeek Flash").unwrap();
        assert!(!flash.legacy && flash.parse_error.is_none(), "{flash:?}");
    }

    #[test]
    fn save_refuses_to_clobber_a_different_fleet_of_the_same_slug() {
        let _lock = crate::test_support::lock_test_env();
        let ws = tempfile::TempDir::new().unwrap();
        let fleet = sample_fleet();
        save_fleet(&fleet, FleetScope::Workspace, ws.path()).unwrap();

        let mut other = FleetFile::new("DeepSeek Flash!".to_string(), None).unwrap();
        other.members = fleet.members.clone();
        let err = save_fleet(&other, FleetScope::Workspace, ws.path()).unwrap_err();
        assert!(err.to_string().contains("already exists"), "{err}");
    }

    #[test]
    fn migration_preserves_pins_and_names_shadowing() {
        let _lock = crate::test_support::lock_test_env();
        let ws = tempfile::TempDir::new().unwrap();

        // A workspace legacy profile file with a pin.
        let agents_dir = ws.path().join(".codewhale/agents");
        std::fs::create_dir_all(&agents_dir).unwrap();
        std::fs::write(
            agents_dir.join("scout.toml"),
            r#"id = "scout"
role_hint = "scout"
model = "deepseek-v4-flash"
provider = "deepseek"
"#,
        )
        .unwrap();

        let receipt = migrate_legacy_roster(
            &codewhale_config::FleetConfigToml::default(),
            ws.path(),
            true,
            FleetScope::Workspace,
        )
        .expect("migration");

        assert_eq!(receipt.fleet.name, "Default");
        let scout = receipt.fleet.member("scout").expect("scout member");
        assert_eq!(scout.model.as_deref(), Some("deepseek-v4-flash"));
        assert_eq!(scout.provider.as_deref(), Some("deepseek"));
        assert!(receipt.saved_to.ends_with("fleets/default.toml"));
        // The legacy profile file itself is untouched.
        assert!(
            std::fs::read_to_string(agents_dir.join("scout.toml"))
                .unwrap()
                .contains("model = \"deepseek-v4-flash\"")
        );
    }
}