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
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
//! Fleet profile vocabulary, local profile discovery, and config-facing aliases.

#![allow(dead_code)]

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, anyhow, bail};
use serde::Deserialize;

use crate::tui::app::ReasoningEffort;

#[allow(unused_imports)]
pub use codewhale_config::{
    FleetDelegationHints, FleetLoadout, FleetProfile, FleetProfilePermissions, FleetRole, FleetSlot,
};

pub use super::roster::ProfileOrigin;

pub const WORKSPACE_AGENT_PROFILE_DIR: &str = ".codewhale/agents";
pub const PERSONAL_AGENT_PROFILE_DIR: &str = "agents";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FleetProfileScope {
    Project,
    Personal,
}

impl FleetProfileScope {
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Project => "project",
            Self::Personal => "personal",
        }
    }

    #[must_use]
    pub fn display_dir(self) -> &'static str {
        match self {
            Self::Project => WORKSPACE_AGENT_PROFILE_DIR,
            Self::Personal => "$CODEWHALE_HOME/agents",
        }
    }

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

pub fn personal_agent_profile_dir() -> Result<PathBuf> {
    Ok(codewhale_config::codewhale_home()?.join(PERSONAL_AGENT_PROFILE_DIR))
}

pub fn agent_profile_dir_for_scope(scope: FleetProfileScope, workspace: &Path) -> Result<PathBuf> {
    match scope {
        FleetProfileScope::Project => Ok(workspace.join(WORKSPACE_AGENT_PROFILE_DIR)),
        FleetProfileScope::Personal => personal_agent_profile_dir(),
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentProfile {
    pub id: String,
    pub display_name: Option<String>,
    pub description: Option<String>,
    pub profile: FleetProfile,
    pub source: PathBuf,
    /// Roster layer this profile came from (#fleet-roster cutover (v0.8.67)).
    /// File-based loading in this module always yields `Workspace`; the
    /// roster stamps `BuiltIn` / `Config` for the other layers.
    pub origin: ProfileOrigin,
}

/// The minimum profile information needed to prevent a save from clobbering
/// another file.  Identity discovery intentionally accepts otherwise legacy
/// profile keys: an old route-policy field must not block authoring an
/// unrelated, current profile, but malformed TOML or an invalid id still fails
/// closed because the collision check cannot be trusted.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentProfileIdentity {
    pub id: String,
    pub source: PathBuf,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct AgentProfileToml {
    #[serde(default)]
    id: Option<String>,
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    display_name: Option<String>,
    #[serde(default)]
    description: Option<String>,
    #[serde(default)]
    role_hint: Option<String>,
    #[serde(default)]
    base_role: Option<String>,
    #[serde(default)]
    persona: Option<String>,
    #[serde(default)]
    loadout: Option<String>,
    #[serde(default, alias = "model_hint", alias = "model_id")]
    model: Option<String>,
    /// Explicit provider id for `model` (#4093), e.g. `"deepseek"` or
    /// `"openrouter"`. Validated against the known `ApiProvider` vocabulary at
    /// load time — never inferred by sniffing `model` for a provider-shaped
    /// substring (EPIC #2608). `deny_unknown_fields` no longer needs to guard
    /// this name: it is now a first-class, validated field instead of a
    /// smuggled one.
    #[serde(default)]
    provider: Option<String>,
    /// Optional saved thinking tier for this profile (#4137). TOML may use
    /// the canonical `reasoning_effort` spelling or the UI-facing `thinking`
    /// / `reasoning` aliases; loading normalizes to a canonical setting label.
    #[serde(default, alias = "thinking", alias = "reasoning")]
    reasoning_effort: Option<String>,
    #[serde(default)]
    instructions: Option<AgentProfileInstructions>,
    #[serde(default)]
    tools: Option<AgentProfileTools>,
    #[serde(default)]
    permissions: Option<AgentProfilePermissionsToml>,
}

#[derive(Debug, Deserialize)]
struct AgentProfileIdentityToml {
    #[serde(default)]
    id: Option<String>,
    #[serde(default)]
    name: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct AgentProfileInstructions {
    #[serde(default)]
    text: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct AgentProfileTools {
    #[serde(default)]
    posture: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct AgentProfilePermissionsToml {
    #[serde(default)]
    allow_shell: Option<bool>,
    #[serde(default)]
    trust: Option<bool>,
    #[serde(default)]
    approval_required: Option<bool>,
}

pub fn load_workspace_agent_profiles(workspace: impl AsRef<Path>) -> Result<Vec<AgentProfile>> {
    load_agent_profiles_from_dir(workspace.as_ref().join(WORKSPACE_AGENT_PROFILE_DIR))
}

/// Load every valid workspace profile while reporting invalid neighbors
/// individually.  The runtime roster uses this path so one stale profile does
/// not hide a newly-authored valid profile (or the rest of the party).
pub fn load_workspace_agent_profiles_tolerant(
    workspace: impl AsRef<Path>,
) -> Result<(Vec<AgentProfile>, Vec<String>)> {
    let dir = workspace.as_ref().join(WORKSPACE_AGENT_PROFILE_DIR);
    load_agent_profiles_from_dir_tolerant(dir, ProfileOrigin::Workspace)
}

pub fn load_personal_agent_profiles_tolerant() -> Result<(Vec<AgentProfile>, Vec<String>)> {
    load_agent_profiles_from_dir_tolerant(personal_agent_profile_dir()?, ProfileOrigin::Personal)
}

pub fn load_agent_profiles_from_dir_tolerant(
    dir: impl AsRef<Path>,
    origin: ProfileOrigin,
) -> Result<(Vec<AgentProfile>, Vec<String>)> {
    let dir = dir.as_ref();
    let paths = agent_profile_paths(dir)?;
    let mut profiles = Vec::new();
    let mut issues = Vec::new();
    let mut seen = BTreeSet::new();
    let mut duplicates = BTreeSet::new();
    let mut identified = Vec::new();

    // Resolve identities first so duplicate ids fail closed as a group rather
    // than allowing whichever filename happens to sort first to win.
    for path in paths {
        match load_agent_profile_identity_file(&path) {
            Ok(identity) => {
                let canonical_id = identity.id.to_ascii_lowercase();
                if !seen.insert(canonical_id.clone()) {
                    duplicates.insert(canonical_id.clone());
                }
                identified.push((path, identity, canonical_id));
            }
            Err(err) => issues.push(format!("{err:#}")),
        }
    }

    for (path, _identity, canonical_id) in identified {
        if duplicates.contains(&canonical_id) {
            issues.push(format!(
                "duplicate agent profile id {} includes {}",
                canonical_id,
                path.display()
            ));
            continue;
        }
        match load_agent_profile_file(&path) {
            Ok(mut profile) => {
                profile.origin = origin;
                profiles.push(profile);
            }
            Err(err) => issues.push(format!("{err:#}")),
        }
    }

    Ok((profiles, issues))
}

/// Read only the identity-bearing fields from workspace profiles for the
/// authoring collision gate.  Unknown legacy fields are harmless here because
/// no profile behavior is loaded or executed from this representation.
pub fn load_workspace_agent_profile_identities(
    workspace: impl AsRef<Path>,
) -> Result<Vec<AgentProfileIdentity>> {
    let dir = workspace.as_ref().join(WORKSPACE_AGENT_PROFILE_DIR);
    load_agent_profile_identities_from_dir(dir)
}

pub fn load_agent_profile_identities_from_dir(
    dir: impl AsRef<Path>,
) -> Result<Vec<AgentProfileIdentity>> {
    let dir = dir.as_ref();
    agent_profile_paths(dir)?
        .into_iter()
        .map(|path| load_agent_profile_identity_file(&path))
        .collect()
}

pub fn load_agent_profiles_from_dir(dir: impl AsRef<Path>) -> Result<Vec<AgentProfile>> {
    let dir = dir.as_ref();
    let mut profiles = Vec::new();
    let mut seen = BTreeSet::new();
    for path in agent_profile_paths(dir)? {
        let profile = load_agent_profile_file(&path)?;
        if !seen.insert(profile.id.to_ascii_lowercase()) {
            bail!("duplicate agent profile id {}", profile.id);
        }
        profiles.push(profile);
    }
    Ok(profiles)
}

fn agent_profile_paths(dir: &Path) -> Result<Vec<PathBuf>> {
    if !dir.exists() {
        return Ok(Vec::new());
    }
    if !dir.is_dir() {
        bail!("agent profile path {} is not a directory", dir.display());
    }

    let mut paths = std::fs::read_dir(dir)
        .with_context(|| format!("reading agent profile dir {}", dir.display()))?
        .collect::<std::io::Result<Vec<_>>>()
        .with_context(|| format!("reading agent profile entries in {}", dir.display()))?
        .into_iter()
        .map(|entry| entry.path())
        .filter(|path| path.extension().and_then(|value| value.to_str()) == Some("toml"))
        .collect::<Vec<_>>();
    paths.sort();
    Ok(paths)
}

fn load_agent_profile_identity_file(path: &Path) -> Result<AgentProfileIdentity> {
    let raw = std::fs::read_to_string(path)
        .with_context(|| format!("reading agent profile identity {}", path.display()))?;
    let parsed: AgentProfileIdentityToml = toml::from_str(&raw)
        .map_err(|err| anyhow!("parsing agent profile identity {}: {err}", path.display()))?;
    let fallback_id = path
        .file_stem()
        .and_then(|value| value.to_str())
        .unwrap_or("profile");
    let id = first_present([parsed.id.as_deref(), parsed.name.as_deref()])
        .unwrap_or(fallback_id)
        .to_string();
    validate_agent_profile_token(path, "id/name", &id)?;
    Ok(AgentProfileIdentity {
        id,
        source: path.to_path_buf(),
    })
}

fn load_agent_profile_file(path: &Path) -> Result<AgentProfile> {
    let raw = std::fs::read_to_string(path)
        .with_context(|| format!("reading agent profile {}", path.display()))?;
    let parsed: AgentProfileToml = toml::from_str(&raw)
        .map_err(|err| anyhow!("parsing agent profile {}: {err}", path.display()))?;
    agent_profile_from_toml(path, parsed)
}

fn agent_profile_from_toml(path: &Path, parsed: AgentProfileToml) -> Result<AgentProfile> {
    reject_permission_expansion(path, parsed.tools.as_ref(), parsed.permissions.as_ref())?;

    let fallback_id = path
        .file_stem()
        .and_then(|value| value.to_str())
        .unwrap_or("profile");
    let id = first_present([parsed.id.as_deref(), parsed.name.as_deref()])
        .unwrap_or(fallback_id)
        .to_string();
    validate_agent_profile_token(path, "id/name", &id)?;

    let role_name = canonical_public_role_name(
        first_present([
            parsed.base_role.as_deref(),
            parsed.role_hint.as_deref(),
            parsed.name.as_deref(),
        ])
        .unwrap_or(&id),
    );
    validate_agent_profile_token(path, "base_role/role_hint", &role_name)?;

    let loadout = first_present([parsed.loadout.as_deref()])
        .map(FleetLoadout::from_name)
        .unwrap_or_default();
    let model = non_empty_trimmed(parsed.model.as_deref()).map(str::to_string);
    validate_agent_profile_model_hint(path, model.as_deref())?;

    let provider = non_empty_trimmed(parsed.provider.as_deref())
        .map(str::to_string)
        .map(|provider| validate_agent_profile_provider(path, &provider).map(|()| provider))
        .transpose()?;
    let reasoning_effort =
        normalize_agent_profile_reasoning_effort(path, parsed.reasoning_effort.as_deref())?;

    let instructions = parsed
        .instructions
        .as_ref()
        .and_then(|instructions| non_empty_trimmed(instructions.text.as_deref()))
        .or_else(|| non_empty_trimmed(parsed.persona.as_deref()))
        .map(str::to_string);

    let description = non_empty_trimmed(parsed.description.as_deref()).map(str::to_string);
    let profile = FleetProfile {
        slot: FleetSlot::from_name(&role_name),
        role: FleetRole {
            name: role_name,
            description: description.clone(),
            instructions,
        },
        loadout,
        model,
        provider,
        reasoning_effort,
        permissions: FleetProfilePermissions::default(),
        delegation: FleetDelegationHints::default(),
    };

    Ok(AgentProfile {
        id,
        display_name: non_empty_trimmed(parsed.display_name.as_deref()).map(str::to_string),
        description,
        profile,
        source: path.to_path_buf(),
        origin: ProfileOrigin::Workspace,
    })
}

/// Canonicalize renamed public Fleet roles at profile load boundaries.
///
/// Profile ids remain untouched so an older file can still be addressed by
/// its saved id. Only the semantic role is migrated; every new receipt and UI
/// label derived from it therefore says `consultant`.
pub(crate) fn canonical_public_role_name(role: &str) -> String {
    match role.trim().to_ascii_lowercase().as_str() {
        "oracle" | "advisor" => "consultant".to_string(),
        _ => role.to_string(),
    }
}

fn reject_permission_expansion(
    path: &Path,
    tools: Option<&AgentProfileTools>,
    permissions: Option<&AgentProfilePermissionsToml>,
) -> Result<()> {
    if let Some(posture) = tools
        .and_then(|tools| tools.posture.as_deref())
        .and_then(trimmed_non_empty)
    {
        match posture {
            "read-only" | "readonly" | "read_only" => {}
            other => bail!(
                "agent profile {} tools.posture={other:?} would widen permissions; use FleetProfile policy for grants",
                path.display()
            ),
        }
    }

    if let Some(permissions) = permissions {
        if permissions.allow_shell.unwrap_or(false) {
            bail!(
                "agent profile {} may not request allow_shell=true",
                path.display()
            );
        }
        if permissions.trust.unwrap_or(false) {
            bail!(
                "agent profile {} may not request trust=true",
                path.display()
            );
        }
        if permissions.approval_required == Some(false) {
            bail!(
                "agent profile {} may not disable approval_required",
                path.display()
            );
        }
    }
    Ok(())
}

fn validate_agent_profile_token(path: &Path, field: &str, value: &str) -> Result<()> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        bail!("agent profile {} {field} cannot be empty", path.display());
    }
    if trimmed != value || !trimmed.chars().all(is_agent_profile_token_char) {
        bail!(
            "agent profile {} {field} must be a simple token",
            path.display()
        );
    }
    Ok(())
}

fn validate_agent_profile_model_hint(path: &Path, value: Option<&str>) -> Result<()> {
    let Some(value) = value else {
        return Ok(());
    };
    if !is_model_hint(value) {
        bail!(
            "agent profile {} model must be a visible model id without whitespace or secrets",
            path.display()
        );
    }
    Ok(())
}

/// Validate an explicit `provider` field as a safe provider id (#4093).
///
/// Built-in providers are accepted by the runtime vocabulary, and user-named
/// OpenAI-compatible custom providers are accepted as simple tokens so the
/// launch path can resolve `[providers.<id>]` from the session config (#3965).
/// This field remains the ONLY place a profile's provider is established:
/// callers never infer it from `model` (EPIC #2608).
fn validate_agent_profile_provider(path: &Path, value: &str) -> Result<()> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        bail!("agent profile {} provider cannot be empty", path.display());
    }
    if trimmed != value || !trimmed.chars().all(is_agent_profile_token_char) {
        bail!(
            "agent profile {} provider must be a simple provider id",
            path.display()
        );
    }
    Ok(())
}

fn normalize_agent_profile_reasoning_effort(
    path: &Path,
    value: Option<&str>,
) -> Result<Option<String>> {
    let Some(value) = non_empty_trimmed(value) else {
        return Ok(None);
    };
    if matches!(
        value.to_ascii_lowercase().as_str(),
        "inherit" | "parent" | "same" | "current" | "default" | "unset"
    ) {
        return Ok(None);
    }
    ReasoningEffort::parse_strict(value)
        .map(|effort| Some(effort.as_setting().to_string()))
        .map_err(|_| {
            anyhow!(
                "agent profile {} reasoning_effort {value:?} must be one of: inherit, auto, off, low, medium, high, max",
                path.display()
            )
        })
}

fn is_agent_profile_token_char(ch: char) -> bool {
    ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.')
}

fn is_model_hint(value: &str) -> bool {
    let trimmed = value.trim();
    !trimmed.is_empty()
        && trimmed == value
        && trimmed
            .chars()
            .all(|ch| ch.is_ascii_graphic() && !matches!(ch, '=' | '\'' | '"'))
}

fn first_present<'a>(values: impl IntoIterator<Item = Option<&'a str>>) -> Option<&'a str> {
    values.into_iter().flatten().find_map(trimmed_non_empty)
}

fn non_empty_trimmed(value: Option<&str>) -> Option<&str> {
    value.and_then(trimmed_non_empty)
}

fn trimmed_non_empty(value: &str) -> Option<&str> {
    let trimmed = value.trim();
    (!trimmed.is_empty()).then_some(trimmed)
}

/// Outcome of parsing untrusted model output into a fleet profile draft.
/// Mirrors `UntrustedDraftParse` from the constitution pipeline: the reply is
/// data, never trusted, and any failure is a reason string for the status
/// line — drafting failures degrade to the manual authoring flow.
#[derive(Debug)]
pub enum UntrustedProfileParse {
    Drafted(Box<FleetProfileDraft>),
    Empty,
    Invalid(String),
}

/// A model-drafted fleet agent profile that has passed the untrusted gate:
/// balanced-JSON extraction, serde parse with `deny_unknown_fields` (so
/// provider/base_url/api_key/permissions/tools cannot ride along), the same
/// escalation rejections the profile loader applies, token and model-hint
/// validation, prose bounds, and control-character stripping. The persisted
/// TOML is rendered deterministically from this struct — model bytes are
/// never written to disk verbatim.
///
/// `provider` (#4093) is set ONLY by the structured Fleet setup picker (a
/// user's explicit, credential-checked selection) — never by
/// [`Self::from_untrusted_json`], whose wire schema
/// ([`FleetProfileDraftJson`]) has no `provider` field and rejects one via
/// `deny_unknown_fields`. A model's untrusted reply can never smuggle a
/// provider; only an interactive pick can set this field.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FleetProfileDraft {
    pub id: String,
    pub display_name: Option<String>,
    pub description: Option<String>,
    pub role_hint: String,
    pub model_class_hint: Option<String>,
    pub model: Option<String>,
    /// Explicit provider id for `model` (e.g. `"deepseek"`), set only by the
    /// structured picker. `None` means "no route pin" (inherit) — matching
    /// `model: None` — or a legacy/untrusted draft that predates this field.
    pub provider: Option<String>,
    /// Explicit saved thinking tier, set only by structured setup controls.
    /// `None` means inherit the operator/session reasoning tier.
    pub reasoning_effort: Option<String>,
    pub instructions: Option<String>,
}

/// Bounds for model-drafted profile prose. Same philosophy as the
/// constitution bounds: roomy enough for a real profile, hard enough that a
/// misbehaving provider cannot bloat the store.
pub const MAX_PROFILE_DESCRIPTION_LEN: usize = 1000;
pub const MAX_PROFILE_INSTRUCTIONS_LEN: usize = 4000;
const MAX_PROFILE_DISPLAY_NAME_LEN: usize = 80;
const MAX_PROFILE_TOKEN_LEN: usize = 64;

/// The JSON shape the drafting prompt asks for. `deny_unknown_fields` is the
/// first escalation gate: a draft that tries to smuggle `permissions`,
/// `tools`, `provider`, `base_url`, or `api_key` fails the parse outright
/// instead of being silently stripped.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct FleetProfileDraftJson {
    #[serde(default)]
    id: Option<String>,
    #[serde(default)]
    display_name: Option<String>,
    #[serde(default)]
    description: Option<String>,
    #[serde(default)]
    role_hint: Option<String>,
    #[serde(default)]
    model_class_hint: Option<String>,
    #[serde(default)]
    model: Option<String>,
    #[serde(default)]
    instructions: Option<String>,
}

impl FleetProfileDraft {
    /// Parse untrusted model output. Any structural problem is `Invalid`
    /// with a short reason; a parse that carries no usable content is
    /// `Empty`.
    #[must_use]
    pub fn from_untrusted_json(raw: &str) -> UntrustedProfileParse {
        let Some(json) = extract_first_json_object(raw) else {
            return UntrustedProfileParse::Invalid("no JSON object found".to_string());
        };
        let parsed: FleetProfileDraftJson = match serde_json::from_str(json) {
            Ok(parsed) => parsed,
            Err(err) => return UntrustedProfileParse::Invalid(err.to_string()),
        };

        let role_hint = match parsed
            .role_hint
            .as_deref()
            .and_then(trimmed_non_empty)
            .map(sanitize_profile_token)
        {
            Some(token) if !token.is_empty() => canonical_public_role_name(&token),
            _ => return UntrustedProfileParse::Invalid("role_hint missing".to_string()),
        };
        let id = parsed
            .id
            .as_deref()
            .and_then(trimmed_non_empty)
            .map(sanitize_profile_token)
            .filter(|token| !token.is_empty())
            .unwrap_or_else(|| role_hint.clone());
        let model_class_hint = parsed
            .model_class_hint
            .as_deref()
            .and_then(trimmed_non_empty)
            .map(sanitize_profile_token)
            .filter(|token| !token.is_empty());
        let model = parsed
            .model
            .as_deref()
            .and_then(trimmed_non_empty)
            .map(str::to_string);
        if let Some(ref model) = model
            && !is_model_hint(model)
        {
            return UntrustedProfileParse::Invalid(
                "model must be a visible model id without whitespace or secrets".to_string(),
            );
        }
        let display_name = parsed
            .display_name
            .as_deref()
            .map(|text| sanitize_profile_prose(text, MAX_PROFILE_DISPLAY_NAME_LEN))
            .and_then(|text| trimmed_non_empty(&text).map(str::to_string));
        let description = parsed
            .description
            .as_deref()
            .map(|text| sanitize_profile_prose(text, MAX_PROFILE_DESCRIPTION_LEN))
            .and_then(|text| trimmed_non_empty(&text).map(str::to_string));
        let instructions = parsed
            .instructions
            .as_deref()
            .map(|text| sanitize_profile_prose(text, MAX_PROFILE_INSTRUCTIONS_LEN))
            .and_then(|text| trimmed_non_empty(&text).map(str::to_string));

        let draft = FleetProfileDraft {
            id,
            display_name,
            description,
            role_hint,
            model_class_hint,
            model,
            // Never set from untrusted model output — `FleetProfileDraftJson`
            // has no `provider` field, so there is nothing to read here.
            provider: None,
            reasoning_effort: None,
            instructions,
        };
        if draft.description.is_none() && draft.instructions.is_none() {
            return UntrustedProfileParse::Empty;
        }
        UntrustedProfileParse::Drafted(Box::new(draft))
    }

    /// Deterministic TOML rendering — the exact bytes the ratify keypress
    /// would persist. Loading this back through the profile loader must
    /// succeed with the default (floor) permissions.
    #[must_use]
    pub fn render_toml(&self) -> String {
        let mut root = toml::value::Table::new();
        root.insert("id".to_string(), toml::Value::String(self.id.clone()));
        if let Some(ref display_name) = self.display_name {
            root.insert(
                "display_name".to_string(),
                toml::Value::String(display_name.clone()),
            );
        }
        if let Some(ref description) = self.description {
            root.insert(
                "description".to_string(),
                toml::Value::String(description.clone()),
            );
        }
        root.insert(
            "role_hint".to_string(),
            toml::Value::String(self.role_hint.clone()),
        );
        if let Some(ref hint) = self.model_class_hint {
            root.insert("loadout".to_string(), toml::Value::String(hint.clone()));
        }
        if let Some(ref model) = self.model {
            root.insert("model".to_string(), toml::Value::String(model.clone()));
            // A provider pin is only meaningful alongside a concrete model
            // (#4093): an `inherit` draft (`model: None`) never carries one,
            // so the rendered TOML can't imply a route it doesn't have.
            if let Some(ref provider) = self.provider {
                root.insert(
                    "provider".to_string(),
                    toml::Value::String(provider.clone()),
                );
            }
        }
        if let Some(ref reasoning_effort) = self.reasoning_effort {
            root.insert(
                "reasoning_effort".to_string(),
                toml::Value::String(reasoning_effort.clone()),
            );
        }
        if let Some(ref instructions) = self.instructions {
            let mut table = toml::value::Table::new();
            table.insert(
                "text".to_string(),
                toml::Value::String(instructions.clone()),
            );
            root.insert("instructions".to_string(), toml::Value::Table(table));
        }
        toml::to_string_pretty(&toml::Value::Table(root))
            .unwrap_or_else(|_| String::from("# failed to render profile"))
    }

    /// File name (stem + `.toml`) for this draft, always derived from the
    /// sanitized id — never a model-chosen free-form path.
    #[must_use]
    pub fn file_name(&self) -> String {
        format!("{}.toml", self.id)
    }
}

/// Keep only the loader's token alphabet, lowercased, bounded.
fn sanitize_profile_token(value: &str) -> String {
    value
        .trim()
        .chars()
        .map(|ch| ch.to_ascii_lowercase())
        .filter(|ch| is_agent_profile_token_char(*ch))
        .take(MAX_PROFILE_TOKEN_LEN)
        .collect()
}

/// Strip control characters (newline/tab survive) and bound length by chars.
fn sanitize_profile_prose(text: &str, max_len: usize) -> String {
    text.chars()
        .filter(|ch| !ch.is_control() || matches!(ch, '\n' | '\t'))
        .take(max_len)
        .collect()
}

/// Extract the first balanced `{...}` object from untrusted output, so fenced
/// or prose-wrapped JSON still parses. Mirrors the constitution pipeline's
/// extractor (which is private to codewhale-config).
fn extract_first_json_object(raw: &str) -> Option<&str> {
    let start = raw.find('{')?;
    let mut depth = 0usize;
    let mut in_string = false;
    let mut escaped = false;
    for (offset, ch) in raw[start..].char_indices() {
        if escaped {
            escaped = false;
            continue;
        }
        match ch {
            '\\' if in_string => escaped = true,
            '"' => in_string = !in_string,
            '{' if !in_string => depth += 1,
            '}' if !in_string => {
                depth -= 1;
                if depth == 0 {
                    return Some(&raw[start..=start + offset]);
                }
            }
            _ => {}
        }
    }
    None
}

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

    #[test]
    fn draft_gate_rejects_unknown_and_escalation_fields() {
        for raw in [
            r#"{"id":"x","role_hint":"reviewer","description":"d","permissions":{"allow_shell":true}}"#,
            r#"{"id":"x","role_hint":"reviewer","description":"d","tools":{"posture":"full"}}"#,
            r#"{"id":"x","role_hint":"reviewer","description":"d","provider":"openai"}"#,
            r#"{"id":"x","role_hint":"reviewer","description":"d","api_key":"sk-nope"}"#,
        ] {
            assert!(
                matches!(
                    FleetProfileDraft::from_untrusted_json(raw),
                    UntrustedProfileParse::Invalid(_)
                ),
                "{raw} must be rejected, not stripped"
            );
        }
    }

    #[test]
    fn draft_gate_bounds_and_sanitizes() {
        let huge = "x".repeat(MAX_PROFILE_INSTRUCTIONS_LEN + 500);
        // \u0007 (BEL) inside the description must be stripped by the
        // prose sanitizer; the oversized instructions must be bounded.
        let raw = format!(
            "{{\"id\":\"  Weird ID!!  \",\"role_hint\":\"Code Reviewer\",\"description\":\"has\\u0007control\",\"instructions\":\"{huge}\"}}"
        );
        let UntrustedProfileParse::Drafted(draft) = FleetProfileDraft::from_untrusted_json(&raw)
        else {
            panic!("draft should parse");
        };
        assert_eq!(draft.id, "weirdid");
        assert_eq!(draft.role_hint, "codereviewer");
        assert_eq!(draft.description.as_deref(), Some("hascontrol"));
        assert_eq!(
            draft.instructions.as_deref().unwrap().chars().count(),
            MAX_PROFILE_INSTRUCTIONS_LEN
        );
    }

    #[test]
    fn draft_gate_rejects_secret_shaped_model_and_missing_role() {
        assert!(matches!(
            FleetProfileDraft::from_untrusted_json(
                r#"{"id":"x","role_hint":"reviewer","description":"d","model":"has secret ="}"#
            ),
            UntrustedProfileParse::Invalid(_)
        ));
        assert!(matches!(
            FleetProfileDraft::from_untrusted_json(r#"{"id":"x","description":"d"}"#),
            UntrustedProfileParse::Invalid(_)
        ));
        assert!(matches!(
            FleetProfileDraft::from_untrusted_json(r#"{"id":"x","role_hint":"reviewer"}"#),
            UntrustedProfileParse::Empty
        ));
    }

    #[test]
    fn draft_gate_accepts_fenced_output() {
        let raw = "Here you go:\n```json\n{\"id\":\"reviewer\",\"role_hint\":\"reviewer\",\"description\":\"Reviews diffs.\"}\n```";
        assert!(matches!(
            FleetProfileDraft::from_untrusted_json(raw),
            UntrustedProfileParse::Drafted(_)
        ));
    }

    #[test]
    fn rendered_draft_round_trips_through_the_loader_with_floor_permissions() {
        let UntrustedProfileParse::Drafted(draft) = FleetProfileDraft::from_untrusted_json(
            r#"{"id":"reviewer","display_name":"Reviewer","description":"Reviews diffs for correctness.","role_hint":"reviewer","model_class_hint":"cheap","model":"glm-5.2","instructions":"Read the diff.\nReport findings, then stop."}"#,
        ) else {
            panic!("draft should parse");
        };

        let dir = TempDir::new().unwrap();
        let path = write_profile(dir.path(), &draft.file_name(), &draft.render_toml());
        let profiles = load_agent_profiles_from_dir(dir.path()).expect("rendered TOML loads");
        assert_eq!(profiles.len(), 1);
        let loaded = &profiles[0];
        assert_eq!(loaded.id, "reviewer");
        assert_eq!(loaded.display_name.as_deref(), Some("Reviewer"));
        assert_eq!(loaded.profile.model.as_deref(), Some("glm-5.2"));
        assert_eq!(
            loaded.profile.role.instructions.as_deref(),
            Some("Read the diff.\nReport findings, then stop.")
        );
        // The loader always installs the permission floor, no matter what.
        assert_eq!(
            loaded.profile.permissions,
            FleetProfilePermissions::default()
        );
        assert_eq!(path, loaded.source);
    }

    #[test]
    fn draft_with_explicit_provider_round_trips_through_the_loader() {
        // A structured (picker-driven) draft that pins a model on a provider
        // other than whatever the parent session happens to use (#4093): the
        // rendered TOML must carry both fields explicitly, and the loader
        // must read the provider back out verbatim — never re-derive it by
        // sniffing `model` for a provider-shaped substring.
        let draft = FleetProfileDraft {
            id: "scout-deepseek".to_string(),
            display_name: Some("Scout".to_string()),
            description: Some("Cross-provider scout profile.".to_string()),
            role_hint: "scout".to_string(),
            model_class_hint: None,
            model: Some("deepseek-v4-flash".to_string()),
            provider: Some("deepseek".to_string()),
            reasoning_effort: None,
            instructions: None,
        };

        let rendered = draft.render_toml();
        assert!(
            rendered.contains("provider = \"deepseek\""),
            "rendered TOML must persist the explicit provider: {rendered}"
        );
        assert!(rendered.contains("model = \"deepseek-v4-flash\""));

        let dir = TempDir::new().unwrap();
        write_profile(dir.path(), &draft.file_name(), &rendered);
        let profiles = load_agent_profiles_from_dir(dir.path()).expect("rendered TOML loads");
        assert_eq!(profiles.len(), 1);
        let loaded = &profiles[0];
        assert_eq!(loaded.profile.model.as_deref(), Some("deepseek-v4-flash"));
        assert_eq!(loaded.profile.provider.as_deref(), Some("deepseek"));
    }

    #[test]
    fn draft_with_reasoning_effort_round_trips_through_the_loader() {
        let draft = FleetProfileDraft {
            id: "scout-deep".to_string(),
            display_name: Some("Scout".to_string()),
            description: Some("Deep scout profile.".to_string()),
            role_hint: "scout".to_string(),
            model_class_hint: None,
            model: Some("deepseek-v4-pro".to_string()),
            provider: Some("deepseek".to_string()),
            reasoning_effort: Some("max".to_string()),
            instructions: None,
        };

        let rendered = draft.render_toml();
        assert!(
            rendered.contains("reasoning_effort = \"max\""),
            "rendered TOML must persist explicit reasoning: {rendered}"
        );

        let dir = TempDir::new().unwrap();
        write_profile(dir.path(), &draft.file_name(), &rendered);
        let profiles = load_agent_profiles_from_dir(dir.path()).expect("rendered TOML loads");
        assert_eq!(profiles.len(), 1);
        let loaded = &profiles[0];
        assert_eq!(loaded.profile.provider.as_deref(), Some("deepseek"));
        assert_eq!(loaded.profile.model.as_deref(), Some("deepseek-v4-pro"));
        assert_eq!(loaded.profile.reasoning_effort.as_deref(), Some("max"));
    }

    #[test]
    fn profile_loader_normalizes_reasoning_aliases() {
        let dir = TempDir::new().unwrap();
        write_profile(
            dir.path(),
            "scout.toml",
            r#"
id = "scout"
role_hint = "scout"
thinking = "ultracode"

[instructions]
text = "Scout deeply."
"#,
        );

        let profiles = load_agent_profiles_from_dir(dir.path()).expect("profile TOML loads");
        assert_eq!(profiles.len(), 1);
        // `xhigh` used to land here too; the thinking ladder made it a rung of
        // its own, so `ultracode` is the alias left to exercise.
        assert_eq!(
            profiles[0].profile.reasoning_effort.as_deref(),
            Some("ultra")
        );
    }

    #[test]
    fn profile_loader_migrates_advisory_role_aliases_to_consultant() {
        let dir = tempfile::tempdir().unwrap();
        for alias in ["oracle", "advisor"] {
            let path = dir.path().join(format!("{alias}.toml"));
            std::fs::write(
                &path,
                format!("id = \"{alias}\"\nrole_hint = \"{alias}\"\n"),
            )
            .unwrap();
            let loaded = load_agent_profile_file(&path).expect("load compatibility profile");
            assert_eq!(loaded.id, alias, "saved identity remains addressable");
            assert_eq!(loaded.profile.role.name, "consultant");
            assert_eq!(loaded.profile.slot.as_str(), "consultant");
        }
    }

    #[test]
    fn model_draft_migrates_advisory_role_alias_to_consultant() {
        let UntrustedProfileParse::Drafted(draft) = FleetProfileDraft::from_untrusted_json(
            r#"{"id":"second-opinion","role_hint":"oracle","description":"Counsel."}"#,
        ) else {
            panic!("expected a drafted profile");
        };
        assert_eq!(draft.role_hint, "consultant");
        assert!(draft.render_toml().contains("role_hint = \"consultant\""));
    }

    #[test]
    fn profile_loader_rejects_unknown_reasoning_effort() {
        let dir = TempDir::new().unwrap();
        write_profile(
            dir.path(),
            "scout.toml",
            r#"
id = "scout"
role_hint = "scout"
reasoning = "expensive"
"#,
        );

        let err = load_agent_profiles_from_dir(dir.path()).expect_err("invalid effort must fail");
        assert!(
            err.to_string().contains("reasoning_effort"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn inherit_draft_never_renders_a_provider_without_a_model() {
        // `provider` is only meaningful alongside a concrete model pin; an
        // `inherit` draft (no `model`) must never render one even if a stale
        // caller sets the field.
        let draft = FleetProfileDraft {
            id: "inherit".to_string(),
            display_name: None,
            description: None,
            role_hint: "general".to_string(),
            model_class_hint: None,
            model: None,
            provider: Some("deepseek".to_string()),
            reasoning_effort: None,
            instructions: None,
        };
        let rendered = draft.render_toml();
        assert!(!rendered.contains("provider"), "{rendered}");
    }

    fn write_profile(dir: &Path, filename: &str, contents: &str) -> PathBuf {
        let path = dir.join(filename);
        std::fs::write(&path, contents).unwrap();
        path
    }

    #[test]
    fn fleet_profile_round_trips_through_serde_with_safe_defaults() {
        let profile = FleetProfile::default();

        let serialized = toml::to_string(&profile).expect("profile serializes");
        let round_tripped: FleetProfile =
            toml::from_str(&serialized).expect("profile deserializes");

        assert_eq!(round_tripped, profile);
        assert_eq!(round_tripped.role.name, "general");
        assert_eq!(round_tripped.loadout, FleetLoadout::Inherit);
        assert!(!round_tripped.permissions.allow_shell);
        assert!(!round_tripped.permissions.trust);
        assert!(round_tripped.permissions.approval_required);
        assert_eq!(round_tripped.delegation.max_spawn_depth, None);
        assert_eq!(round_tripped.delegation.max_concurrency, None);
    }

    #[test]
    fn fleet_profile_explicit_toml_parses_role_loadout_permissions() {
        let profile: FleetProfile = toml::from_str(
            r#"
slot = "reviewer"
loadout = "deep-reasoning"

[role]
name = "verifier"
instructions = "Review the patch and produce verification evidence."

[permissions]
allow_shell = true
trust = true
approval_required = false

[delegation]
max_spawn_depth = 1
concurrency = 2
"#,
        )
        .expect("explicit fleet profile parses");

        assert_eq!(profile.slot, FleetSlot::Reviewer);
        assert_eq!(profile.role.name, "verifier");
        assert_eq!(
            profile.role.instructions.as_deref(),
            Some("Review the patch and produce verification evidence.")
        );
        assert_eq!(
            profile.loadout,
            FleetLoadout::Custom("deep-reasoning".to_string())
        );
        assert!(profile.permissions.allow_shell);
        assert!(profile.permissions.trust);
        assert!(!profile.permissions.approval_required);
        assert_eq!(profile.delegation.max_spawn_depth, Some(1));
        assert_eq!(profile.delegation.max_concurrency, Some(2));
    }

    #[test]
    fn fleet_profile_accepts_compact_role_string() {
        let profile: FleetProfile = toml::from_str(
            r#"
role = "scout"
loadout = "fast"
model = "deepseek-v4-flash"
"#,
        )
        .expect("compact fleet profile parses");

        assert_eq!(profile.role.name, "scout");
        assert_eq!(profile.loadout, FleetLoadout::Fast);
        assert_eq!(profile.model.as_deref(), Some("deepseek-v4-flash"));
        assert_eq!(profile.permissions, FleetProfilePermissions::default());
    }

    #[test]
    fn agent_profile_loader_returns_empty_for_missing_workspace_dir() {
        let tmp = TempDir::new().unwrap();

        let profiles = load_workspace_agent_profiles(tmp.path()).unwrap();

        assert!(profiles.is_empty());
    }

    #[test]
    fn profile_identity_loader_accepts_legacy_route_policy_fields() {
        let tmp = TempDir::new().unwrap();
        let agents_dir = tmp.path().join(WORKSPACE_AGENT_PROFILE_DIR);
        std::fs::create_dir_all(&agents_dir).unwrap();
        let source = write_profile(
            &agents_dir,
            "reviewer.toml",
            r#"
id = "reviewer"
role_hint = "reviewer"
model_class_hint = "heavy"
models = ["glm-5.2", "deepseek-v4-pro"]
"#,
        );

        let identities = load_workspace_agent_profile_identities(tmp.path())
            .expect("legacy fields do not obscure identity");

        assert_eq!(
            identities,
            vec![AgentProfileIdentity {
                id: "reviewer".to_string(),
                source,
            }]
        );
    }

    #[test]
    fn profile_identity_loader_fails_closed_for_malformed_toml() {
        let tmp = TempDir::new().unwrap();
        let agents_dir = tmp.path().join(WORKSPACE_AGENT_PROFILE_DIR);
        std::fs::create_dir_all(&agents_dir).unwrap();
        write_profile(&agents_dir, "broken.toml", "id = [\n");

        let err = load_workspace_agent_profile_identities(tmp.path())
            .expect_err("malformed TOML cannot prove collision safety")
            .to_string();

        assert!(err.contains("broken.toml"), "unexpected error: {err}");
        assert!(err.contains("profile identity"), "unexpected error: {err}");
    }

    #[test]
    fn tolerant_loader_keeps_valid_profile_beside_legacy_profile() {
        let tmp = TempDir::new().unwrap();
        let agents_dir = tmp.path().join(WORKSPACE_AGENT_PROFILE_DIR);
        std::fs::create_dir_all(&agents_dir).unwrap();
        write_profile(
            &agents_dir,
            "reviewer.toml",
            "id = \"reviewer\"\nmodel_class_hint = \"heavy\"\n",
        );
        write_profile(
            &agents_dir,
            "scout.toml",
            "id = \"scout\"\nrole_hint = \"scout\"\nprovider = \"deepseek\"\nmodel = \"deepseek-v4-flash\"\n",
        );

        let (profiles, issues) = load_workspace_agent_profiles_tolerant(tmp.path())
            .expect("directory discovery succeeds");

        assert_eq!(profiles.len(), 1);
        assert_eq!(profiles[0].id, "scout");
        assert_eq!(
            profiles[0].profile.model.as_deref(),
            Some("deepseek-v4-flash")
        );
        assert_eq!(issues.len(), 1);
        assert!(issues[0].contains("reviewer.toml"), "{issues:?}");
        assert!(issues[0].contains("model_class_hint"), "{issues:?}");
    }

    #[test]
    fn tolerant_loader_skips_every_duplicate_id_but_keeps_unique_neighbors() {
        let tmp = TempDir::new().unwrap();
        let agents_dir = tmp.path().join(WORKSPACE_AGENT_PROFILE_DIR);
        std::fs::create_dir_all(&agents_dir).unwrap();
        write_profile(&agents_dir, "a.toml", "id = \"reviewer\"\n");
        write_profile(&agents_dir, "b.toml", "name = \"reviewer\"\n");
        write_profile(&agents_dir, "scout.toml", "id = \"scout\"\n");

        let (profiles, issues) = load_workspace_agent_profiles_tolerant(tmp.path())
            .expect("directory discovery succeeds");

        assert_eq!(
            profiles
                .iter()
                .map(|profile| profile.id.as_str())
                .collect::<Vec<_>>(),
            vec!["scout"]
        );
        assert_eq!(issues.len(), 2);
        assert!(
            issues
                .iter()
                .all(|issue| issue.contains("duplicate agent profile id reviewer")),
            "{issues:?}"
        );
    }

    #[test]
    fn profile_identity_loader_fails_closed_for_invalid_id_token() {
        let tmp = TempDir::new().unwrap();
        let agents_dir = tmp.path().join(WORKSPACE_AGENT_PROFILE_DIR);
        std::fs::create_dir_all(&agents_dir).unwrap();
        write_profile(&agents_dir, "broken.toml", "id = \"bad id\"\n");

        let err = load_workspace_agent_profile_identities(tmp.path())
            .expect_err("invalid identity tokens cannot prove collision safety")
            .to_string();

        assert!(err.contains("broken.toml"), "unexpected error: {err}");
        assert!(err.contains("simple token"), "unexpected error: {err}");
    }

    #[test]
    fn scout_save_succeeds_beside_untouched_legacy_reviewer() {
        let tmp = TempDir::new().unwrap();
        let agents_dir = tmp.path().join(WORKSPACE_AGENT_PROFILE_DIR);
        std::fs::create_dir_all(&agents_dir).unwrap();
        let legacy = r#"
id = "reviewer"
role_hint = "reviewer"
model_class_hint = "heavy"
models = ["glm-5.2", "deepseek-v4-pro"]
"#;
        let reviewer_path = write_profile(&agents_dir, "reviewer.toml", legacy);
        let before = std::fs::read_to_string(&reviewer_path).unwrap();

        let identities = load_workspace_agent_profile_identities(tmp.path())
            .expect("legacy neighbor must not block identity discovery");
        assert_eq!(identities.len(), 1);
        assert_eq!(identities[0].id, "reviewer");
        assert!(
            identities
                .iter()
                .all(|identity| !identity.id.eq_ignore_ascii_case("scout")),
            "scout id must be free beside legacy reviewer"
        );

        let draft = FleetProfileDraft {
            id: "scout".to_string(),
            display_name: Some("Scout".to_string()),
            description: Some("Workspace scout.".to_string()),
            role_hint: "scout".to_string(),
            model_class_hint: None,
            model: Some("deepseek-v4-flash".to_string()),
            provider: Some("deepseek".to_string()),
            reasoning_effort: None,
            instructions: None,
        };
        let scout_path = write_profile(&agents_dir, &draft.file_name(), &draft.render_toml());

        let after = std::fs::read_to_string(&reviewer_path).unwrap();
        assert_eq!(before, after, "legacy reviewer must remain unmodified");
        assert!(scout_path.exists());

        let (profiles, issues) = load_workspace_agent_profiles_tolerant(tmp.path())
            .expect("directory discovery succeeds");
        assert_eq!(profiles.len(), 1);
        assert_eq!(profiles[0].id, "scout");
        assert_eq!(
            profiles[0].profile.model.as_deref(),
            Some("deepseek-v4-flash")
        );
        assert_eq!(issues.len(), 1);
        assert!(issues[0].contains("reviewer.toml"), "{issues:?}");
    }

    #[test]
    fn agent_profile_loader_normalizes_project_agent_toml() {
        let tmp = TempDir::new().unwrap();
        let agents_dir = tmp.path().join(WORKSPACE_AGENT_PROFILE_DIR);
        std::fs::create_dir_all(&agents_dir).unwrap();
        let source = write_profile(
            &agents_dir,
            "reviewer.toml",
            r#"
name = "adversarial_reviewer"
display_name = "Adversarial Reviewer"
description = "Skeptical read-only review posture"
role_hint = "reviewer"
loadout = "balanced"
model = "deepseek-v4-pro"

[instructions]
text = "Focus on regressions, missing tests, and fragile assumptions."

[tools]
posture = "read-only"
"#,
        );

        let profiles = load_workspace_agent_profiles(tmp.path()).unwrap();

        assert_eq!(profiles.len(), 1);
        let profile = &profiles[0];
        assert_eq!(profile.id, "adversarial_reviewer");
        assert_eq!(
            profile.display_name.as_deref(),
            Some("Adversarial Reviewer")
        );
        assert_eq!(
            profile.description.as_deref(),
            Some("Skeptical read-only review posture")
        );
        assert_eq!(profile.profile.slot, FleetSlot::Reviewer);
        assert_eq!(profile.profile.role.name, "reviewer");
        assert_eq!(
            profile.profile.role.instructions.as_deref(),
            Some("Focus on regressions, missing tests, and fragile assumptions.")
        );
        assert_eq!(
            profile.profile.loadout,
            FleetLoadout::Custom("balanced".to_string())
        );
        assert_eq!(profile.profile.model.as_deref(), Some("deepseek-v4-pro"));
        assert_eq!(
            profile.profile.permissions,
            FleetProfilePermissions::default()
        );
        assert_eq!(profile.source, source);
    }

    #[test]
    fn agent_profile_loader_rejects_retired_model_policy_aliases() {
        for (field, value) in [("model_class_hint", "balanced"), ("route_tier", "fast")] {
            let tmp = TempDir::new().unwrap();
            write_profile(
                tmp.path(),
                "reviewer.toml",
                &format!(
                    r#"
name = "reviewer"
role_hint = "reviewer"
{field} = "{value}"
"#
                ),
            );

            let err = load_agent_profiles_from_dir(tmp.path())
                .unwrap_err()
                .to_string();

            assert!(
                err.contains(field) || err.contains("unknown field"),
                "unexpected error for {field}: {err}"
            );
        }
    }

    #[test]
    fn agent_profile_loader_accepts_and_round_trips_explicit_provider_field() {
        // #4093: `provider` is now a first-class, validated field — a Fleet
        // profile can name its own route explicitly, independent of whatever
        // provider is active when the profile is later loaded/launched.
        let tmp = TempDir::new().unwrap();
        write_profile(
            tmp.path(),
            "reviewer.toml",
            r#"
name = "reviewer"
provider = "openrouter"
model = "deepseek/deepseek-v4-pro"
"#,
        );

        let profiles = load_agent_profiles_from_dir(tmp.path()).expect("profile loads");
        assert_eq!(profiles.len(), 1);
        assert_eq!(profiles[0].profile.provider.as_deref(), Some("openrouter"));
        assert_eq!(
            profiles[0].profile.model.as_deref(),
            Some("deepseek/deepseek-v4-pro")
        );
    }

    #[test]
    fn agent_profile_loader_accepts_custom_provider_name() {
        // #3965: LM Studio and other user-named OpenAI-compatible providers
        // are resolved from `[providers.<id>]` at launch time, so the profile
        // loader must preserve the safe id instead of requiring a built-in.
        let tmp = TempDir::new().unwrap();
        write_profile(
            tmp.path(),
            "reviewer.toml",
            r#"
name = "reviewer"
provider = "lm-studio"
model = "qwen-2.5-7b"
"#,
        );

        let profiles = load_agent_profiles_from_dir(tmp.path()).expect("profile loads");

        assert_eq!(profiles[0].profile.provider.as_deref(), Some("lm-studio"));
        assert_eq!(profiles[0].profile.model.as_deref(), Some("qwen-2.5-7b"));
    }

    #[test]
    fn agent_profile_loader_rejects_malformed_provider_name() {
        let tmp = TempDir::new().unwrap();
        write_profile(
            tmp.path(),
            "reviewer.toml",
            r#"
name = "reviewer"
provider = "lm studio"
model = "some-model"
"#,
        );

        let err = load_agent_profiles_from_dir(tmp.path())
            .unwrap_err()
            .to_string();

        assert!(
            err.contains("provider must be a simple provider id"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn agent_profile_loader_rejects_permission_expansion() {
        let tmp = TempDir::new().unwrap();
        write_profile(
            tmp.path(),
            "builder.toml",
            r#"
name = "builder"

[tools]
posture = "read-write"
"#,
        );

        let err = load_agent_profiles_from_dir(tmp.path())
            .unwrap_err()
            .to_string();

        assert!(
            err.contains("would widen permissions"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn agent_profile_loader_rejects_secret_like_model_hint() {
        let tmp = TempDir::new().unwrap();
        write_profile(
            tmp.path(),
            "reviewer.toml",
            r#"
name = "reviewer"
model = "deepseek-v4-pro api_key=secret"
"#,
        );

        let err = load_agent_profiles_from_dir(tmp.path())
            .unwrap_err()
            .to_string();

        assert!(
            err.contains("model must be a visible model id"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn agent_profile_loader_rejects_duplicate_ids() {
        let tmp = TempDir::new().unwrap();
        write_profile(tmp.path(), "a.toml", "name = \"reviewer\"\n");
        write_profile(tmp.path(), "b.toml", "id = \"reviewer\"\n");

        let err = load_agent_profiles_from_dir(tmp.path())
            .unwrap_err()
            .to_string();

        assert!(
            err.contains("duplicate agent profile id reviewer"),
            "unexpected error: {err}"
        );
    }
}