newt-core 0.8.0

Newt-Agent core types, errors, and the NeMoCode-style tier router
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
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
//! `RoleProfile` — promotes a persona from a prompt-only overlay into a
//! "role profile" that binds a system-prompt overlay together with a toolset,
//! a capability (caveat) profile, and backend/router policy.
//!
//! ## Why this exists
//!
//! A persona today is just a system-prompt overlay loaded from a `.md` file
//! (see `newt-tui`'s `Persona`). The one-airframe-many-roles topology — a
//! single newt binary that can embody a `dragon-rider` (orchestrator), a
//! `wing-commander` (arbiter/judge), or a `worker` — needs each role to carry
//! *more* than prose: which tools it may call, what authority (caveats) it
//! holds, and which model/tier it should route to. This module is that seam.
//!
//! ## File format (backward compatible)
//!
//! A role profile is still a plain `.md` file. The only addition is an
//! **optional** TOML front-matter block fenced by `+++` lines at the very top
//! of the file:
//!
//! ```text
//! +++
//! role = "worker"
//! tools = ["read_file", "write_file", "run_command"]
//! model = "qwen2.5-coder:14b"
//! tier = "STANDARD"
//!
//! [caveats]
//! fs_read = "all"
//! fs_write = ["src/"]
//! exec = ["cargo"]
//! net = "none"
//! max_calls = 40
//! +++
//!
//! # Worker
//!
//! You edit files and run builds...
//! ```
//!
//! A file with **no** `+++` front-matter parses into a `RoleProfile` whose
//! every field except `prompt` is `None` — i.e. exactly today's prompt-only
//! persona. This is the load-bearing backward-compat guarantee.
//!
//! ## What this slice wires vs. follow-ups
//!
//! This module only *parses and represents* a role profile and converts the
//! caveat shape into the canonical [`Caveats`]. It does **not** enforce the
//! toolset or caveats — enforcement (an agent-bridle registry at the tool
//! dispatch site, worker/MCP entry points reading the profile) is a deliberate
//! follow-up. See `docs/design/role-profiles.md`.

use content_addressable::{canonical, ContentAddressable, ContentError};
use serde::{Deserialize, Serialize};

use crate::initiative::Initiative;
use crate::router::Tier;
use crate::{Caveats, CountBound, Scope};

/// A parsed role profile: a system-prompt overlay plus the optional toolset /
/// capability / router policy declared in TOML front-matter.
///
/// `prompt` is always the markdown body (front-matter stripped). Every other
/// field is `Some` only when the front-matter declared it; a profile with no
/// front-matter has all-`None` non-prompt fields and behaves exactly like
/// today's prompt-only persona.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RoleProfile {
    /// The markdown body (front-matter removed). Injected as the persona
    /// overlay exactly as today.
    pub prompt: String,
    /// Declared role name (e.g. `"dragon-rider"`, `"worker"`). Independent of
    /// the persona file's stem, so a file can name the role it embodies.
    pub role: Option<String>,
    /// Preferred tools for an interactive persona; `None` means no preference.
    /// Dedicated worker/server entrypoints may apply this as a role boundary.
    pub tools: Option<Vec<String>>,
    /// Skill names (matching a `SKILL.md` `name` under `skill_search_dirs`)
    /// this role binds on activation (FR-4, #1041). `None` = no bound
    /// skills — today's behavior, unaffected.
    pub skills: Option<Vec<String>>,
    /// Declared capability profile. Advisory for interactive personas; explicit
    /// worker/server role bindings may use it as an authority ceiling.
    pub caveats: Option<CaveatProfile>,
    /// Preferred backend model id (router policy hint).
    pub model: Option<String>,
    /// Preferred router tier (router policy hint).
    // INERT-CODE-RATCHET: F14 WIRE: role tier is displayed but never participates in backend placement.
    pub tier: Option<Tier>,
    /// Operating ALTITUDE — act (doer, the default) vs advise (coach). Selected
    /// in front-matter as `altitude = "coach"`. `None` = doer. Drives which base
    /// identity the system prompt installs (FR-5, #999): a `Coach` altitude
    /// REPLACES `DEFAULT_SOUL` with `COACH_SOUL` so a coaching persona doesn't
    /// ship two contradictory identities (doer soul + advise overlay).
    pub altitude: Option<Altitude>,
    /// BACKEND — names a `[[backends]]` entry this persona runs on (e.g.
    /// `"sol"` → gpt-5.6-sol). `None` = the session's configured backend.
    /// Auto-selection (overriding `default_backend` while this persona is
    /// active) is a follow-up; declaring it is wired here first.
    pub backend: Option<String>,
    /// COGNITION — per-call reasoning depth (the psyche dial). `None` = backend
    /// default. The backend projects this semantic level onto its own request
    /// controls.
    pub cognition: Option<Cognition>,
    /// INITIATIVE — how much this persona looks before acting. `None` = the
    /// model-family / config default. (Persona tenacity no longer exists:
    /// tenacity is set only explicitly.)
    pub initiative: Option<Initiative>,
    /// CREW — when `true`, this persona runs with the multi-agent crew (`/team`)
    /// on by default. `None`/`false` = single-agent. Enforcement is a follow-up.
    pub crew: Option<bool>,
    /// Operator-selected communication style. Unspecified traits inherit the
    /// persona/backend's style; these levels never confer tool authority.
    pub personality: Option<PersonalityTraits>,
}

/// An operator-selected style level, not a psychological measurement.
/// Construction and deserialization both enforce the inclusive 0..=100 range.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "u8")]
pub struct PersonalityLevel(u8);

impl PersonalityLevel {
    /// The validated integer selected by the operator.
    #[must_use]
    pub fn get(self) -> u8 {
        self.0
    }
}

impl TryFrom<u8> for PersonalityLevel {
    type Error = &'static str;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        if value <= 100 {
            Ok(Self(value))
        } else {
            Err("personality levels must be integers from 0 through 100")
        }
    }
}

/// The shared ordering and names used by the persona parser and style controls.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PersonalityTrait {
    Agreeableness,
    Extraversion,
    Warmth,
    Approachability,
    ProsocialBehavior,
}

impl PersonalityTrait {
    pub const ALL: [Self; 5] = [
        Self::Agreeableness,
        Self::Extraversion,
        Self::Warmth,
        Self::Approachability,
        Self::ProsocialBehavior,
    ];

    /// The stable TOML field name.
    #[must_use]
    pub fn key(self) -> &'static str {
        match self {
            Self::Agreeableness => "agreeableness",
            Self::Extraversion => "extraversion",
            Self::Warmth => "warmth",
            Self::Approachability => "approachability",
            Self::ProsocialBehavior => "prosocial_behavior",
        }
    }

    /// The operator-facing name.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::ProsocialBehavior => "prosocial behavior",
            _ => self.key(),
        }
    }

    /// The lower/higher communication behavior this operator preference selects.
    #[must_use]
    pub fn describe(self) -> &'static str {
        match self {
            Self::Agreeableness => "Lower: candid/challenging; higher: collaborative framing, without agreeing with incorrect claims.",
            Self::Extraversion => "Lower: reserved; higher: conversational, without unsolicited actions.",
            Self::Warmth => "Lower: neutral; higher: reassuring.",
            Self::Approachability => "Lower: formal; higher: accessible.",
            Self::ProsocialBehavior => "Lower: task-focused; higher: considering affected people/helpfulness, still no unauthorized acts.",
        }
    }
}

/// Optional style selections carried by the existing role-profile record.
/// `None` is unspecified, not an implicit midpoint. These are communication
/// preferences only: neither authority nor honesty is adjustable here.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
pub struct PersonalityTraits {
    pub agreeableness: Option<PersonalityLevel>,
    pub extraversion: Option<PersonalityLevel>,
    pub warmth: Option<PersonalityLevel>,
    pub approachability: Option<PersonalityLevel>,
    pub prosocial_behavior: Option<PersonalityLevel>,
}

impl PersonalityTraits {
    #[must_use]
    pub fn get(&self, kind: PersonalityTrait) -> Option<PersonalityLevel> {
        match kind {
            PersonalityTrait::Agreeableness => self.agreeableness,
            PersonalityTrait::Extraversion => self.extraversion,
            PersonalityTrait::Warmth => self.warmth,
            PersonalityTrait::Approachability => self.approachability,
            PersonalityTrait::ProsocialBehavior => self.prosocial_behavior,
        }
    }

    pub fn set(&mut self, kind: PersonalityTrait, level: Option<PersonalityLevel>) {
        let slot = match kind {
            PersonalityTrait::Agreeableness => &mut self.agreeableness,
            PersonalityTrait::Extraversion => &mut self.extraversion,
            PersonalityTrait::Warmth => &mut self.warmth,
            PersonalityTrait::Approachability => &mut self.approachability,
            PersonalityTrait::ProsocialBehavior => &mut self.prosocial_behavior,
        };
        *slot = level;
    }

    /// Resolve only unspecified axes from the inherited persona. Explicit zero
    /// is a selection, not an inheritance sentinel.
    #[must_use]
    pub fn resolve(mut self, inherited: Option<Self>) -> Self {
        if let Some(inherited) = inherited {
            for kind in PersonalityTrait::ALL {
                self.set(kind, self.get(kind).or(inherited.get(kind)));
            }
        }
        self
    }

    /// One communication-style overlay, omitted entirely when no axis is set.
    /// The same canonical trait vocabulary drives both controls and rendering.
    #[must_use]
    pub fn prompt_block(&self) -> String {
        let lines: Vec<_> = PersonalityTrait::ALL
            .into_iter()
            .filter_map(|kind| {
                self.get(kind).map(|level| {
                    format!(
                        "- {}: {}/100\n  {}",
                        kind.label(),
                        level.get(),
                        kind.describe()
                    )
                })
            })
            .collect();
        if lines.is_empty() {
            return String::new();
        }
        format!(
            "## Communication style\nOperator-selected communication-style levels (0-100):\n{}\n\n\
             These are communication-style preferences, not psychological measurements. They do not change tool authority, tenacity, or honesty. Remain civil and respectful even at low levels.",
            lines.join("\n")
        )
    }
}

impl ContentAddressable for PersonalityTraits {
    fn canonical_form(&self) -> Result<Vec<u8>, ContentError> {
        canonical::to_canonical_dagcbor(self)
    }
}

/// The persona's operating altitude (FR-5, #999). Decides whether the base
/// identity ("soul") is the doer `DEFAULT_SOUL` or the advise-first
/// `COACH_SOUL`. Serialized in front-matter as `altitude = "coach"` (or the
/// synonym `"advise"`); an absent field is [`Altitude::Doer`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Altitude {
    /// Act: make the change, run the command. Today's behavior.
    #[default]
    Doer,
    /// Advise: explain, present options, recommend — never mutate. Accepts the
    /// synonym `"advise"` in front-matter.
    #[serde(alias = "advise")]
    Coach,
}

/// COGNITION — the psyche's reasoning-depth dial: how hard the model thinks
/// per call. Declared in front-matter as `cognition = "thoughtful"`; an
/// absent field leaves the backend default. Responses projects it onto
/// `reasoning.effort`; an explicitly capable Chat Completions endpoint projects
/// it onto a local generation policy.
///
/// The ladder runs from the least reasoning the endpoint allows to the most
/// (paired with tenacity and crew under the `obsessive` posture). The
/// pre-rename labels (`glancing` … `contemplating`) are the one-time
/// importer's job ([`crate::psyche_import`]), never accepted here.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Cognition {
    /// The least reasoning the endpoint allows. Wire: `reasoning.effort = minimal`.
    Zen,
    /// Short reasoning before acting. Wire: `low`.
    Rational,
    /// Weighs the options — the default. Wire: `medium`.
    #[default]
    Thoughtful,
    /// The deepest reasoning. Wire: `high`.
    Meticulous,
}

impl Cognition {
    /// The OpenAI `reasoning.effort` value this level maps to on the Responses
    /// wire (emitted by `agentic::responses_reasoning_field`). Chat Completions
    /// uses the backend-neutral generation policy instead and only when the
    /// endpoint explicitly advertises support.
    #[must_use]
    pub fn reasoning_effort(self) -> &'static str {
        crate::model_card::ReasoningEffort::from(self).as_str()
    }

    /// Stable lowercase label — the front-matter / `/cognition` spelling.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Zen => "zen",
            Self::Rational => "rational",
            Self::Thoughtful => "thoughtful",
            Self::Meticulous => "meticulous",
        }
    }

    /// One-line backend-neutral description for `/cognition` listings.
    #[must_use]
    pub fn describe(self) -> &'static str {
        match self {
            Self::Zen => "least reasoning the endpoint allows (minimal)",
            Self::Rational => "short reasoning before acting (low)",
            Self::Thoughtful => "weighs the options (medium)",
            Self::Meticulous => "deepest reasoning (high)",
        }
    }

    /// All levels, light → deep (for `/cognition list` and menus).
    #[must_use]
    pub fn all() -> [Self; 4] {
        [
            Self::Zen,
            Self::Rational,
            Self::Thoughtful,
            Self::Meticulous,
        ]
    }
}

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

impl std::str::FromStr for Cognition {
    type Err = String;

    /// Accepts the current labels and `default`. A pre-rename label is an
    /// error that names its replacement — never silently accepted.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.trim().to_ascii_lowercase();
        if s == "default" {
            return Ok(Self::default());
        }
        if let Some(level) = Self::all().into_iter().find(|c| c.label() == s) {
            return Ok(level);
        }
        if let Some(new) = crate::psyche_import::renamed_cognition(&s) {
            return Err(format!("cognition '{s}' was renamed to '{new}'"));
        }
        let levels: Vec<&str> = Self::all().into_iter().map(Self::label).collect();
        Err(format!("unknown cognition '{s}' ({})", levels.join("|")))
    }
}

/// The TOML front-matter shape. Kept separate from [`RoleProfile`] so the
/// `prompt` (markdown body) is never part of the serde surface.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
struct FrontMatter {
    #[serde(default)]
    role: Option<String>,
    #[serde(default)]
    tools: Option<Vec<String>>,
    #[serde(default)]
    skills: Option<Vec<String>>,
    #[serde(default)]
    caveats: Option<CaveatProfile>,
    #[serde(default)]
    model: Option<String>,
    #[serde(default)]
    tier: Option<Tier>,
    #[serde(default)]
    altitude: Option<Altitude>,
    #[serde(default)]
    backend: Option<String>,
    #[serde(default)]
    cognition: Option<Cognition>,
    #[serde(default)]
    initiative: Option<Initiative>,
    #[serde(default)]
    crew: Option<bool>,
    #[serde(default)]
    personality: Option<PersonalityTraits>,
}

/// A small, human-friendly serde shape for an agent-bridle capability profile.
///
/// Each filesystem/exec/net axis is a [`ScopeSpec`] that maps onto the
/// canonical [`Scope<String>`]; `max_calls` maps onto [`CountBound`]. Omitting
/// an axis defaults it to the top of that axis (unrestricted) via
/// [`ScopeSpec::default`], matching `Caveats::top()` so a sparse profile
/// attenuates only the axes it names. Convert with [`CaveatProfile::to_caveats`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct CaveatProfile {
    #[serde(default)]
    pub fs_read: ScopeSpec,
    #[serde(default)]
    pub fs_write: ScopeSpec,
    #[serde(default)]
    pub exec: ScopeSpec,
    #[serde(default)]
    pub net: ScopeSpec,
    /// Upper bound on tool calls. `None`/omitted = unlimited.
    #[serde(default)]
    pub max_calls: Option<u64>,
}

/// A human-friendly serde form of a single [`Scope<String>`] axis.
///
/// Accepts either the bare string `"all"`/`"none"` or a list of allowed items:
///
/// ```text
/// fs_read  = "all"            # Scope::All
/// net      = "none"           # Scope::Only({})  — authorizes nothing
/// fs_write = ["src/", "Cargo.toml"]   # Scope::Only({...})
/// ```
///
/// Defaults to [`ScopeSpec::All`] (unrestricted) so an omitted axis is the top
/// of that axis, matching `Caveats::top()`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ScopeSpec {
    /// The keyword `"all"` or `"none"`.
    Keyword(ScopeKeyword),
    /// An explicit allow-list of items.
    Items(Vec<String>),
}

impl Default for ScopeSpec {
    fn default() -> Self {
        Self::Keyword(ScopeKeyword::All)
    }
}

/// The `"all"` / `"none"` keywords for a [`ScopeSpec`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ScopeKeyword {
    /// Unrestricted (top of the axis).
    All,
    /// Authorizes nothing.
    None,
}

impl ScopeSpec {
    /// Convert to the canonical lattice [`Scope<String>`].
    #[must_use]
    pub fn to_scope(&self) -> Scope<String> {
        match self {
            Self::Keyword(ScopeKeyword::All) => Scope::All,
            Self::Keyword(ScopeKeyword::None) => Scope::none(),
            Self::Items(items) => Scope::only(items.iter().cloned()),
        }
    }

    /// One-line human summary of this axis (`"all"`, `"none"`, or `"[a, b]"`),
    /// used by `/persona show` reporting.
    #[must_use]
    pub fn summary(&self) -> String {
        match self {
            Self::Keyword(ScopeKeyword::All) => "all".to_string(),
            Self::Keyword(ScopeKeyword::None) => "none".to_string(),
            Self::Items(items) => format!("[{}]", items.join(", ")),
        }
    }
}

impl CaveatProfile {
    /// Convert this profile into the canonical [`Caveats`] lattice element.
    ///
    /// Omitted axes default to the top of their axis (unrestricted),
    /// `valid_for_generation` is always `Scope::All` here (the profile does not
    /// express generation bounds — that is minted at dispatch time), and
    /// `max_calls` becomes [`CountBound::AtMost`] when set, else
    /// [`CountBound::Unlimited`].
    #[must_use]
    pub fn to_caveats(&self) -> Caveats {
        Caveats {
            fs_read: self.fs_read.to_scope(),
            fs_write: self.fs_write.to_scope(),
            exec: self.exec.to_scope(),
            net: self.net.to_scope(),
            max_calls: match self.max_calls {
                Some(n) => CountBound::AtMost(n),
                None => CountBound::Unlimited,
            },
            // DEFERRED (issue #755 / epic #749): `valid_for_generation` is a
            // causal-generation-window axis, not a filesystem/exec/net
            // capability a preset or role profile clamps — it is minted at
            // dispatch time. Narrowing it here is out of scope for the M6
            // grammar-gap fix; left at `Scope::All` as a follow-up.
            valid_for_generation: Scope::All,
        }
    }

    /// One-line human summary of this capability profile for `/persona show`,
    /// e.g. `fs_read=all fs_write=none exec=[cargo] net=all max_calls=40`.
    #[must_use]
    pub fn summary(&self) -> String {
        let calls = match self.max_calls {
            Some(n) => n.to_string(),
            None => "unlimited".to_string(),
        };
        format!(
            "fs_read={} fs_write={} exec={} net={} max_calls={}",
            self.fs_read.summary(),
            self.fs_write.summary(),
            self.exec.summary(),
            self.net.summary(),
            calls,
        )
    }
}

/// A **named permission preset** (issue #307): a config-declared authority
/// *clamp* that maps onto the same [`CaveatProfile`] / [`Caveats`] lattice a
/// role profile uses. It is deliberately a thin, human-friendly surface over
/// [`CaveatProfile`] — the existing caveat-profile mechanism — rather than a
/// parallel type, so the same `to_scope` / `to_caveats` lowering is reused.
///
/// ## Config shape (`[permission_presets.<name>]`)
///
/// ```toml
/// [permission_presets.readonly-triage]
/// readonly   = true            # read anything; deny all writes
/// exec_allow = ["git", "gh"]   # a small exec allowlist
/// deny       = ["*"]           # everything else (net) denied
/// max_calls  = 40              # optional tool-call ceiling
/// # fs_read  = ["src/"]        # optional: confine reads (omit ⇒ read all)
/// ```
///
/// ## Semantics — a clamp, never a grant
///
/// The clamp is consumed via [`NamedPermissionPreset::clamp`], which lowers to a
/// [`Caveats`] **ceiling**. The session's effective authority is the
/// *intersection* (`meet`) of the session's base caveats and this ceiling — a
/// preset can only ever **attenuate**, never widen. This is the load-bearing
/// property: the ceiling wins over `--disable-ocap` / `--yolo` and over
/// interactive session-grants, because it is `meet`-ed into the authority the
/// enforcement site consults (and re-`meet`-ed over any re-minted grant).
///
/// Each field maps onto a [`CaveatProfile`] axis:
/// - `fs_read = [..]` / `"none"` ⇒ clamp `fs_read = Only({..})` / `none`.
///   **Optional** — omitted (`None`) leaves `fs_read` unrestricted (`all`),
///   the back-compat default. Before this field a preset structurally could
///   *not* narrow reads (the M6 grammar gap, issue #755) even though
///   [`CaveatProfile`] / [`Caveats`] can express a read clamp. A read-only
///   triage mode still reads everything unless it sets this deliberately.
/// - `readonly = true` ⇒ `fs_write = none`, `exec = none` (the floor a triage
///   mode wants). `false`/omitted leaves those axes unconstrained (`all`).
/// - `exec_allow = [..]` ⇒ `exec = Only({..})`. Overrides `readonly`'s
///   exec clamp with the explicit allowlist (so a triage mode can permit a few
///   read-only commands).
/// - `deny = ["*"]` ⇒ clamp `net` to `none` (the remaining "everything else"
///   axis once fs/exec are pinned). A non-`*` `deny` list is recorded but does
///   not subtract from an allowlist here — the lattice is allow-list shaped, so
///   "deny everything else" is the expressible clamp.
/// - `max_calls` ⇒ the [`CountBound`] ceiling, as on a role profile.
///
/// A preset with no fields set is the identity clamp (`Caveats::top()`), so an
/// empty `[permission_presets.x]` block leaves authority unchanged.
///
/// **Footgun (review #312):** omitted axes stay at `TOP`. A preset that sets
/// only `exec_allow = ["git"]` clamps *exec* but leaves `fs_write` and `net`
/// wide open — it is NOT "locked down" despite reading that way. For a true
/// read-only triage clamp, set `readonly = true` (denies writes + exec) and
/// add `exec_allow` only for the few programs the mode genuinely needs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct NamedPermissionPreset {
    /// Optional `fs_read` clamp (issue #755 — the M6 grammar-gap fix).
    /// `None`/omitted ⇒ the `fs_read` axis stays at the top of its axis
    /// (`all`), exactly the pre-#755 behavior where a preset structurally
    /// could not narrow reads. `Some(spec)` narrows reads (e.g.
    /// `Only({..})` to confine a triage mode to a subtree). Serde-defaults
    /// to `None`, so every existing preset is byte-for-byte unchanged.
    #[serde(default)]
    pub fs_read: Option<ScopeSpec>,
    /// `true` ⇒ deny all writes and (unless `exec_allow` overrides) all exec.
    #[serde(default)]
    pub readonly: bool,
    /// Explicit exec allowlist. Non-empty ⇒ `exec = Only({..})`, overriding the
    /// `readonly` exec clamp. Empty + `readonly` ⇒ `exec = none`.
    #[serde(default)]
    pub exec_allow: Vec<String>,
    /// "Deny everything else" marker. `["*"]` clamps the `net` axis to `none`
    /// (writes/exec are pinned by `readonly`/`exec_allow`). Other entries are
    /// accepted for forward-compat but the allow-list lattice expresses denial
    /// as "not in the allowlist", so they do not subtract here.
    #[serde(default)]
    pub deny: Vec<String>,
    /// Optional tool-call ceiling. `None` ⇒ no extra bound.
    #[serde(default)]
    pub max_calls: Option<u64>,
}

impl NamedPermissionPreset {
    /// `true` when `deny` asks to deny everything else (`["*"]`).
    fn denies_all(&self) -> bool {
        self.deny.iter().any(|d| d == "*")
    }

    /// Lower this named preset into the equivalent [`CaveatProfile`] — reusing
    /// the SAME serde-shaped caveat mechanism a role profile carries, rather
    /// than a parallel lowering. Axes the preset does not constrain stay at the
    /// top of their axis (`all`) so `clamp` is the identity on them.
    #[must_use]
    pub fn to_caveat_profile(&self) -> CaveatProfile {
        // fs_write: readonly pins it to none; otherwise unconstrained.
        let fs_write = if self.readonly {
            ScopeSpec::Keyword(ScopeKeyword::None)
        } else {
            ScopeSpec::default()
        };
        // exec: an explicit allowlist wins; else readonly pins it to none; else
        // unconstrained.
        let exec = if !self.exec_allow.is_empty() {
            ScopeSpec::Items(self.exec_allow.clone())
        } else if self.readonly {
            ScopeSpec::Keyword(ScopeKeyword::None)
        } else {
            ScopeSpec::default()
        };
        // net: `deny = ["*"]` clamps the remaining axis to none.
        let net = if self.denies_all() {
            ScopeSpec::Keyword(ScopeKeyword::None)
        } else {
            ScopeSpec::default()
        };
        // fs_read: an explicit clamp narrows reads (issue #755 — the M6
        // grammar-gap fix). `None`/omitted ⇒ the top of the axis (`all`), the
        // historical behavior: before #755 this was hardcoded to
        // `ScopeSpec::default()`, so a preset structurally could not clamp
        // reads even though `CaveatProfile`/`Caveats` can. A read-only triage
        // mode still reads everything unless a preset deliberately narrows it.
        let fs_read = self.fs_read.clone().unwrap_or_default();
        // DEFERRED (default-deny is step 8's job, not here): the "empty/absent
        // preset ⇒ identity clamp (`Caveats::top()`)" default — each unset axis
        // staying at the top of its axis — is the CORRECT meet-identity
        // semantics for a *clamp*: an empty clamp adds no restriction and is
        // applied via `meet`, so an absent axis must be the top. The
        // "default-deny for un-annotated subtasks" (an absent subtask `kind` ⇒
        // the most-restrictive preset) belongs in step 8's subtask-clamp
        // derivation, NOT in this general lowering. Flipping the general default
        // to deny here would break back-compat for every preset consumer
        // (steps 2-7), so step 8 owns that default-deny.
        CaveatProfile {
            fs_read,
            fs_write,
            exec,
            net,
            max_calls: self.max_calls,
        }
    }

    /// The authority **ceiling** this preset imposes, as a [`Caveats`]. The
    /// session's effective authority is `base.meet(&preset.clamp())` — the
    /// clamp can only attenuate, never widen. Reuses [`CaveatProfile::to_caveats`].
    #[must_use]
    pub fn clamp(&self) -> Caveats {
        self.to_caveat_profile().to_caveats()
    }

    /// One-line human summary for `/permissions` and `/posture` reporting, e.g.
    /// `readonly exec=[git, gh] deny=* max_calls=40`.
    #[must_use]
    pub fn summary(&self) -> String {
        let mut parts: Vec<String> = Vec::new();
        if self.readonly {
            parts.push("readonly".to_string());
        }
        if !self.exec_allow.is_empty() {
            parts.push(format!("exec=[{}]", self.exec_allow.join(", ")));
        } else if self.readonly {
            parts.push("exec=none".to_string());
        }
        if self.denies_all() {
            parts.push("deny=*".to_string());
        }
        if let Some(n) = self.max_calls {
            parts.push(format!("max_calls={n}"));
        }
        if parts.is_empty() {
            "unconstrained".to_string()
        } else {
            parts.join(" ")
        }
    }
}

impl RoleProfile {
    /// Parse a role-profile `.md` file's full text into a [`RoleProfile`].
    ///
    /// If the text begins with a `+++` fence line, everything up to the closing
    /// `+++` line is parsed as TOML front-matter and the remainder is the
    /// prompt body. Otherwise the whole text is the prompt and every other
    /// field is `None` (prompt-only — today's behavior).
    ///
    /// # Errors
    ///
    /// Returns an error if a front-matter fence is opened but never closed, or
    /// if the front-matter is not valid TOML for the expected shape.
    pub fn parse(text: &str) -> anyhow::Result<Self> {
        // The envelope grammar moved to `crate::markup` (A1, #1825); role
        // profiles are its first consumer. Error text preserved verbatim.
        let split = crate::markup::split_newt_metadata(text).map_err(|e| match e {
            crate::markup::EnvelopeError::Unclosed => {
                anyhow::anyhow!("role-profile front-matter opened with `+++` but never closed")
            }
            other => anyhow::anyhow!("role-profile front-matter: {other}"),
        })?;
        let (front_matter, body) = (split.front_matter, split.body);
        let body = body.trim().to_string();
        let Some(fm_text) = front_matter else {
            // No front-matter: prompt-only, exactly today's persona.
            return Ok(Self {
                prompt: body,
                ..Self::default()
            });
        };
        let fm: FrontMatter = toml::from_str(fm_text)
            .map_err(|e| anyhow::anyhow!("invalid role-profile front-matter: {e}"))?;
        Ok(Self {
            prompt: body,
            role: fm.role,
            tools: fm.tools,
            skills: fm.skills,
            caveats: fm.caveats,
            model: fm.model,
            tier: fm.tier,
            altitude: fm.altitude,
            backend: fm.backend,
            cognition: fm.cognition,
            initiative: fm.initiative,
            crew: fm.crew,
            personality: fm.personality,
        })
    }

    /// Serialize all known metadata and the prompt through the existing TOML
    /// envelope. Preserves parsed semantics, not source comments/formatting.
    /// An empty envelope keeps a metadata-like prompt body unambiguous.
    ///
    /// # Errors
    ///
    /// Returns an error if the front-matter cannot be serialized as TOML or
    /// would exceed the envelope limit or contain a closing-fence line.
    pub fn to_markdown(&self) -> anyhow::Result<String> {
        let front_matter = FrontMatter {
            role: self.role.clone(),
            tools: self.tools.clone(),
            skills: self.skills.clone(),
            caveats: self.caveats.clone(),
            model: self.model.clone(),
            tier: self.tier,
            altitude: self.altitude,
            backend: self.backend.clone(),
            cognition: self.cognition,
            initiative: self.initiative,
            crew: self.crew,
            personality: self.personality,
        };
        crate::markup::assemble_newt_metadata(
            &toml::to_string(&front_matter)?,
            &format!("\n{}\n", self.prompt),
        )
        .map_err(Into::into)
    }

    /// `true` when this profile declares more than a prompt (i.e. front-matter
    /// bound a role, tools, skills, caveats, model, tier, altitude, or any
    /// psyche dial). A prompt-only persona returns `false`.
    #[must_use]
    pub fn is_role_bound(&self) -> bool {
        self.role.is_some()
            || self.tools.is_some()
            || self.skills.is_some()
            || self.caveats.is_some()
            || self.model.is_some()
            || self.tier.is_some()
            || self.altitude.is_some()
            || self.backend.is_some()
            || self.cognition.is_some()
            || self.initiative.is_some()
            || self.crew.is_some()
            || self.personality.is_some()
    }

    /// Load a named persona `.md` file from `dir` (#1021 PR 5.2 — the
    /// headless counterpart of `newt-tui`'s `PersonaStore::load`).
    ///
    /// Deliberately does **not** seed a shipped default when the file is
    /// missing — `PersonaStore`'s per-file-idempotent seeding (FR-16, #1000)
    /// is correct first-run UX for an interactive session, but a stdio
    /// server silently writing files into `~/.newt/personas/` on every
    /// startup is a footgun under CI/systemd. A headless caller with an
    /// unresolvable `--persona <name>` should fail loudly instead. An existing
    /// file with pre-rename labels is rewritten once by
    /// [`crate::psyche_import::read_persona_file`], like every persona read.
    ///
    /// # Errors
    ///
    /// Returns an error if `name` isn't a valid persona name (letters,
    /// numbers, `-`, `_` only — the same rule `PersonaStore` enforces, kept
    /// in sync deliberately rather than shared, since crossing the
    /// `newt-core`/`newt-tui` boundary for an 8-line check isn't worth the
    /// coupling), if the file doesn't exist, or if it fails to parse.
    pub fn load_from_dir(
        name: &str,
        dir: &std::path::Path,
        report: &mut dyn FnMut(crate::tty::Notice<'static>),
    ) -> anyhow::Result<Self> {
        let name = name.trim().to_ascii_lowercase();
        if name.is_empty()
            || !name
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
        {
            anyhow::bail!("persona names may only contain letters, numbers, '-' and '_'");
        }
        let path = dir.join(format!("{name}.md"));
        let raw = crate::psyche_import::read_persona_file(&path, report).map_err(|e| {
            anyhow::anyhow!("persona `{name}` not found at {}: {e}", path.display())
        })?;
        let profile = Self::parse(&raw).map_err(|e| anyhow::anyhow!("persona `{name}`: {e}"))?;
        if profile.prompt.is_empty() {
            anyhow::bail!("persona `{name}` is empty: {}", path.display());
        }
        Ok(profile)
    }
}

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

    /// The shipped personas must preserve the old explicit persona nudge.
    /// This is distinct from the obsessive command, which holds initiative.
    #[test]
    fn psyche_split_review_bundled_personas_preserve_action_timing() {
        for (name, text) in [
            ("bob", include_str!("../../personas/bob.md")),
            ("obsessive", include_str!("../../personas/obsessive.md")),
        ] {
            assert_eq!(
                RoleProfile::parse(text).unwrap().initiative,
                Some(Initiative::Eager),
                "{name}"
            );
        }
    }

    #[test]
    fn no_front_matter_is_prompt_only() {
        let text = "# Coder\n\nYou write code.\n";
        let rp = RoleProfile::parse(text).unwrap();
        assert_eq!(rp.prompt, "# Coder\n\nYou write code.");
        assert_eq!(rp.role, None);
        assert_eq!(rp.tools, None);
        assert_eq!(rp.caveats, None);
        assert_eq!(rp.model, None);
        assert_eq!(rp.tier, None);
        assert!(!rp.is_role_bound());
    }

    #[test]
    fn parses_full_front_matter() {
        let text = "\
+++
role = \"worker\"
tools = [\"read_file\", \"write_file\", \"run_command\"]
model = \"qwen2.5-coder:14b\"
tier = \"STANDARD\"

[caveats]
fs_read = \"all\"
fs_write = [\"src/\"]
exec = [\"cargo\"]
net = \"none\"
max_calls = 40
+++

# Worker

You edit files and run builds.
";
        let rp = RoleProfile::parse(text).unwrap();
        assert_eq!(rp.prompt, "# Worker\n\nYou edit files and run builds.");
        assert_eq!(rp.role.as_deref(), Some("worker"));
        assert_eq!(
            rp.tools,
            Some(vec![
                "read_file".to_string(),
                "write_file".to_string(),
                "run_command".to_string(),
            ])
        );
        assert_eq!(rp.model.as_deref(), Some("qwen2.5-coder:14b"));
        assert_eq!(rp.tier, Some(Tier::Standard));
        assert!(rp.is_role_bound());

        let caveats = rp.caveats.unwrap().to_caveats();
        assert_eq!(caveats.fs_read, Scope::All);
        assert_eq!(caveats.fs_write, Scope::only(["src/".to_string()]));
        assert_eq!(caveats.exec, Scope::only(["cargo".to_string()]));
        assert_eq!(caveats.net, Scope::none());
        assert_eq!(caveats.max_calls, CountBound::AtMost(40));
    }

    #[test]
    fn parses_psyche_fields() {
        // A persona (Bob the researcher) that names its backend and pegs the
        // psyche dials — the shape the `obsessive`/`bob` shipped personas use.
        let text = "\
+++
role = \"researcher\"
backend = \"sol\"
cognition = \"meticulous\"
initiative = \"eager\"
crew = true
+++

# Bob

You are Bob, a researcher.
";
        let rp = RoleProfile::parse(text).unwrap();
        assert_eq!(rp.role.as_deref(), Some("researcher"));
        assert_eq!(rp.backend.as_deref(), Some("sol"));
        assert_eq!(rp.cognition, Some(Cognition::Meticulous));
        assert_eq!(rp.initiative, Some(Initiative::Eager));
        assert_eq!(rp.crew, Some(true));
        assert!(rp.is_role_bound());
        // The dial maps onto the OpenAI reasoning-effort wire value.
        assert_eq!(rp.cognition.unwrap().reasoning_effort(), "high");
        assert_eq!(rp.cognition.unwrap().label(), "meticulous");
    }

    #[test]
    fn cognition_alone_is_role_bound() {
        // Even a single psyche dial promotes a persona past prompt-only.
        let text = "+++\ncognition = \"rational\"\n+++\n\n# Thinker\n";
        let rp = RoleProfile::parse(text).unwrap();
        assert_eq!(rp.cognition, Some(Cognition::Rational));
        assert!(rp.is_role_bound());
        assert_eq!(Cognition::default(), Cognition::Thoughtful);
    }

    /// Slice 1a rename: an old label is refused with its replacement named,
    /// never silently accepted; persona files reach the strict parser only
    /// after `psyche_import` has rewritten them.
    #[test]
    fn old_cognition_labels_are_refused_with_the_rename() {
        for (old, new) in crate::psyche_import::LEGACY_COGNITION {
            let err = old.parse::<Cognition>().unwrap_err();
            assert_eq!(err, format!("cognition '{old}' was renamed to '{new}'"));
            let text = format!("+++\ncognition = \"{old}\"\n+++\nBody\n");
            assert!(RoleProfile::parse(&text).is_err(), "{old} must stay strict");
        }
        assert_eq!("default".parse::<Cognition>(), Ok(Cognition::Thoughtful));
        assert_eq!(
            " Meticulous ".parse::<Cognition>(),
            Ok(Cognition::Meticulous)
        );
        assert_eq!(
            "telepathic".parse::<Cognition>().unwrap_err(),
            "unknown cognition 'telepathic' (zen|rational|thoughtful|meticulous)"
        );
    }

    const PERSONALITY_TRAITS: [&str; 5] = [
        "agreeableness",
        "extraversion",
        "warmth",
        "approachability",
        "prosocial_behavior",
    ];

    /// These integers are operator-selected style levels, not psychological
    /// measurements. Every inclusive 0..=100 value must be accepted, and even
    /// one explicitly selected trait makes the persona more than prompt-only.
    #[test]
    fn personality_only_front_matter_is_role_bound_for_each_valid_level() {
        for (trait_name, trait_kind) in PERSONALITY_TRAITS.into_iter().zip(PersonalityTrait::ALL) {
            assert_eq!(trait_kind.key(), trait_name);
            for level in 0..=100 {
                let text = format!(
                    "+++\n[personality]\n{trait_name} = {level}\n+++\n\n# Friendly coder\n"
                );
                let rp = RoleProfile::parse(&text).unwrap();
                assert!(
                    rp.is_role_bound(),
                    "{trait_name} = {level} must bind the role"
                );
                assert_eq!(rp.prompt, "# Friendly coder");
                let traits = rp.personality.unwrap();
                assert_eq!(traits.get(trait_kind).unwrap().get(), level);
                for other in PersonalityTrait::ALL {
                    if other != trait_kind {
                        assert_eq!(traits.get(other), None);
                    }
                }
            }
        }
    }

    #[test]
    fn personality_traits_refuse_out_of_range_and_non_integer_levels() {
        for trait_name in PERSONALITY_TRAITS {
            for invalid in [
                "-1", "101", "255", "256", "1.0", "nan", "inf", "\"50\"", "true", "[]", "{}",
            ] {
                let text = format!(
                    "+++\n[personality]\n{trait_name} = {invalid}\n+++\n\n# Friendly coder\n"
                );
                assert!(
                    RoleProfile::parse(&text).is_err(),
                    "{trait_name} = {invalid} must be refused, not ignored or clamped"
                );
            }
        }
    }

    #[test]
    fn personality_metadata_preserves_the_complete_restrictive_role() {
        let metadata = r#"role = "reviewer"
tools = ["read_file"]
skills = ["review-guidance"]
altitude = "coach"
model = "local-test-model"
backend = "local"
tier = "REVIEW"
cognition = "rational"
initiative = "patient"
crew = false

[caveats]
fs_read = ["workspace"]
fs_write = "none"
exec = "none"
net = "none"
max_calls = 7
"#;
        let body = "# Reviewer\n\nExplain findings without editing files.";
        let baseline = RoleProfile::parse(&format!("+++\n{metadata}+++\n\n{body}")).unwrap();
        let personality = "[personality]\nagreeableness = 0\nextraversion = 25\nwarmth = 50\napproachability = 75\nprosocial_behavior = 100\n";
        let styled =
            RoleProfile::parse(&format!("+++\n{metadata}\n{personality}+++\n\n{body}")).unwrap();

        assert!(styled.is_role_bound());
        assert_eq!(styled.prompt, baseline.prompt);
        assert_eq!(styled.role, baseline.role);
        assert_eq!(styled.tools, baseline.tools);
        assert_eq!(styled.skills, baseline.skills);
        assert_eq!(styled.altitude, baseline.altitude);
        assert_eq!(styled.model, baseline.model);
        assert_eq!(styled.backend, baseline.backend);
        assert_eq!(styled.tier, baseline.tier);
        assert_eq!(styled.cognition, baseline.cognition);
        assert_eq!(styled.initiative, baseline.initiative);
        assert_eq!(styled.crew, baseline.crew);
        assert_eq!(styled.caveats, baseline.caveats);
        let mut escaped = styled.clone();
        escaped.backend = Some("local \"quoted\" \\ route".to_string());
        escaped
            .prompt
            .push_str("\n\nKeep `code`, \"quotes\", and \\ paths.");
        let encoded = escaped.to_markdown().unwrap();
        assert_eq!(RoleProfile::parse(&encoded).unwrap(), escaped);
        let caveats = styled.caveats.unwrap().to_caveats();
        assert_eq!(caveats.fs_read, Scope::only(["workspace".to_string()]));
        assert_eq!(caveats.fs_write, Scope::none());
        assert_eq!(caveats.exec, Scope::none());
        assert_eq!(caveats.net, Scope::none());
        assert_eq!(caveats.max_calls, CountBound::AtMost(7));
    }

    #[test]
    fn to_markdown_preserves_prompt_only_semantics_even_with_a_metadata_like_body() {
        for body in ["# Friendly coder", "+++\nThis is body text, not TOML.\n+++"] {
            let profile = RoleProfile {
                prompt: body.to_string(),
                ..RoleProfile::default()
            };
            let decoded = RoleProfile::parse(&profile.to_markdown().unwrap()).unwrap();
            assert_eq!(decoded, profile);
            assert!(!decoded.is_role_bound());
        }
    }

    #[test]
    fn to_markdown_refuses_metadata_that_serializes_as_an_envelope_fence() {
        // Escaped newlines make this a valid input profile, but the TOML writer
        // emits a multiline value containing an actual closing-fence line.
        let profile =
            RoleProfile::parse("+++\nrole = \"reviewer\\n+++\\nextra\"\n+++\n\n# Reviewer\n")
                .expect("escaped metadata is a valid source profile");
        assert_eq!(profile.role.as_deref(), Some("reviewer\n+++\nextra"));
        let error = profile
            .to_markdown()
            .expect_err("refuse an unreadable envelope before a saver can overwrite its source");
        assert!(matches!(
            error.downcast_ref::<crate::markup::EnvelopeError>(),
            Some(crate::markup::EnvelopeError::FrontMatterContainsFence)
        ));
    }

    #[test]
    fn to_markdown_refuses_a_style_edit_that_outgrows_a_valid_envelope() {
        let limit = crate::markup::MAX_ENVELOPE_BYTES;
        let metadata = format!("role = \"{}\"\n", "r".repeat(limit - "role = \"\"\n".len()));
        assert_eq!(metadata.len(), limit);
        let mut profile = RoleProfile::parse(&format!("+++\n{metadata}+++\n\n# Reviewer\n"))
            .expect("the source metadata fits exactly within the envelope limit");
        let unchanged = profile
            .to_markdown()
            .expect("unchanged metadata still fits");
        assert_eq!(RoleProfile::parse(&unchanged).unwrap(), profile);
        profile.personality = Some(PersonalityTraits {
            warmth: Some(PersonalityLevel::try_from(0).unwrap()),
            ..Default::default()
        });
        let error = profile
            .to_markdown()
            .expect_err("a valid style edit must not save an oversized envelope");
        assert!(matches!(
            error.downcast_ref::<crate::markup::EnvelopeError>(),
            Some(crate::markup::EnvelopeError::Oversized { bytes }) if *bytes > limit
        ));
    }

    #[test]
    fn personality_accessors_preserve_independent_values_and_content_identity() {
        use content_addressable::ContentAddressable;

        let mut traits = PersonalityTraits::default();
        let initial_id = traits.content_id().unwrap();
        for (index, kind) in PersonalityTrait::ALL.into_iter().enumerate() {
            traits.set(
                kind,
                Some(PersonalityLevel::try_from((index * 25) as u8).unwrap()),
            );
        }
        for (index, kind) in PersonalityTrait::ALL.into_iter().enumerate() {
            assert_eq!(traits.get(kind).unwrap().get(), (index * 25) as u8);
        }
        assert_ne!(traits.content_id().unwrap(), initial_id);
        let decoded: PersonalityTraits =
            toml::from_str(&toml::to_string(&traits).unwrap()).unwrap();
        assert_eq!(decoded.content_id().unwrap(), traits.content_id().unwrap());
        for kind in PersonalityTrait::ALL {
            traits.set(kind, None);
        }
        assert_eq!(traits.content_id().unwrap(), initial_id);
        assert!(PersonalityLevel::try_from(101).is_err());
        assert!(toml::from_str::<PersonalityTraits>("warmht = 50").is_err());
    }

    #[test]
    fn personality_prompt_block_omits_unspecified_traits_and_keeps_style_guardrails() {
        for kind in PersonalityTrait::ALL {
            for level in [0, 50, 100] {
                let mut traits = PersonalityTraits::default();
                traits.set(kind, Some(PersonalityLevel::try_from(level).unwrap()));
                let block = traits.prompt_block();
                assert!(block.starts_with("## Communication style\n"), "{block}");
                assert!(block.contains("Operator-selected communication-style levels (0-100)"));
                let line = format!("- {}: {level}/100", kind.label());
                assert_eq!(
                    block.lines().filter(|candidate| *candidate == line).count(),
                    1
                );
                for other in PersonalityTrait::ALL {
                    if other != kind {
                        assert!(!block.contains(&format!("- {}:", other.label())), "{block}");
                    }
                }
                let meaning = match kind {
                    PersonalityTrait::Agreeableness => [
                        "candid/challenging",
                        "collaborative framing",
                        "without agreeing with incorrect claims",
                    ],
                    PersonalityTrait::Extraversion => {
                        ["reserved", "conversational", "without unsolicited actions"]
                    }
                    PersonalityTrait::Warmth => ["neutral", "reassuring", "Lower"],
                    PersonalityTrait::Approachability => ["formal", "accessible", "Lower"],
                    PersonalityTrait::ProsocialBehavior => [
                        "task-focused",
                        "affected people/helpfulness",
                        "no unauthorized acts",
                    ],
                };
                for fragment in meaning {
                    assert!(
                        block.contains(fragment),
                        "{} meaning missing: {block}",
                        kind.key()
                    );
                }
                assert!(block
                    .contains("communication-style preferences, not psychological measurements"));
                assert!(block.contains("do not change tool authority, tenacity, or honesty"));
                assert!(block.contains("Remain civil and respectful even at low levels"));
            }
        }
    }

    #[test]
    fn personality_prompt_block_is_empty_for_inherited_style_and_has_one_canonical_order() {
        let mut traits = PersonalityTraits::default();
        assert!(traits.prompt_block().is_empty());
        for kind in PersonalityTrait::ALL.into_iter().rev() {
            traits.set(kind, Some(PersonalityLevel::try_from(25).unwrap()));
        }
        let block = traits.prompt_block();
        let lines: Vec<_> = block
            .lines()
            .filter(|line| line.starts_with("- "))
            .collect();
        let expected: Vec<_> = PersonalityTrait::ALL
            .into_iter()
            .map(|kind| format!("- {}: 25/100", kind.label()))
            .collect();
        assert_eq!(lines, expected);
        assert_eq!(block.matches("## Communication style").count(), 1);
        for kind in PersonalityTrait::ALL {
            traits.set(kind, None);
        }
        assert!(traits.prompt_block().is_empty());
    }

    #[test]
    fn personality_resolve_inherits_each_axis_but_explicit_zero_overrides_it() {
        for kind in PersonalityTrait::ALL {
            for level in [0, 100] {
                let mut inherited = PersonalityTraits::default();
                inherited.set(kind, Some(PersonalityLevel::try_from(level).unwrap()));
                assert_eq!(
                    PersonalityTraits::default().resolve(Some(inherited)),
                    inherited
                );
                let mut explicit = PersonalityTraits::default();
                explicit.set(kind, Some(PersonalityLevel::try_from(0).unwrap()));
                assert_eq!(explicit.resolve(Some(inherited)), explicit);
                assert_eq!(explicit.resolve(None), explicit);
            }
        }
        assert_eq!(
            PersonalityTraits::default().resolve(None),
            PersonalityTraits::default()
        );
    }

    #[test]
    fn personality_resolve_combines_mixed_overrides_without_changing_unspecified_axes() {
        let level = |value| Some(PersonalityLevel::try_from(value).unwrap());
        let inherited = PersonalityTraits {
            agreeableness: level(100),
            extraversion: level(0),
            warmth: level(25),
            approachability: level(75),
            prosocial_behavior: None,
        };
        let overrides = PersonalityTraits {
            agreeableness: level(0),
            extraversion: None,
            warmth: level(100),
            approachability: None,
            prosocial_behavior: level(50),
        };
        let expected = PersonalityTraits {
            agreeableness: level(0),
            extraversion: level(0),
            warmth: level(100),
            approachability: level(75),
            prosocial_behavior: level(50),
        };
        assert_eq!(overrides.resolve(Some(inherited)), expected);
        assert_eq!(overrides.resolve(None), overrides);
        assert_eq!(
            overrides.resolve(Some(PersonalityTraits::default())),
            overrides
        );
    }

    #[test]
    fn sparse_caveats_default_to_top() {
        // Only fs_write named; every other axis defaults to unrestricted.
        let text = "\
+++
role = \"reviewer\"
[caveats]
fs_write = \"none\"
+++

# Reviewer
Grade diffs.
";
        let rp = RoleProfile::parse(text).unwrap();
        let c = rp.caveats.unwrap().to_caveats();
        assert_eq!(c.fs_read, Scope::All);
        assert_eq!(c.fs_write, Scope::none());
        assert_eq!(c.exec, Scope::All);
        assert_eq!(c.net, Scope::All);
        assert_eq!(c.max_calls, CountBound::Unlimited);
    }

    #[test]
    fn malformed_front_matter_errors_clearly() {
        let text = "\
+++
role = \"oops
+++

body
";
        let err = RoleProfile::parse(text).unwrap_err().to_string();
        assert!(
            err.contains("front-matter"),
            "error should mention front-matter, got: {err}"
        );
    }

    #[test]
    fn unclosed_front_matter_errors() {
        let text = "+++\nrole = \"worker\"\n\n# body never fenced\n";
        let err = RoleProfile::parse(text).unwrap_err().to_string();
        assert!(
            err.contains("never closed"),
            "error should mention unclosed fence, got: {err}"
        );
    }

    #[test]
    fn empty_front_matter_block_is_valid() {
        // A `+++ +++` with nothing between is valid empty TOML → all None.
        let text = "+++\n+++\n\n# Just a prompt\n";
        let rp = RoleProfile::parse(text).unwrap();
        assert_eq!(rp.prompt, "# Just a prompt");
        assert!(!rp.is_role_bound());
    }

    /// FR-5 (#999): `altitude` parses (with `advise` as a synonym for `coach`),
    /// defaults to `None` when absent, and counts as role-binding front-matter.
    #[test]
    fn parses_altitude_with_advise_synonym() {
        let coach = RoleProfile::parse("+++\naltitude = \"coach\"\n+++\n\nx\n").unwrap();
        assert_eq!(coach.altitude, Some(Altitude::Coach));
        assert!(coach.is_role_bound(), "altitude alone binds the role");
        assert_eq!(
            RoleProfile::parse("+++\naltitude = \"advise\"\n+++\n\nx\n")
                .unwrap()
                .altitude,
            Some(Altitude::Coach),
            "`advise` is a synonym for coach"
        );
        assert_eq!(
            RoleProfile::parse("+++\naltitude = \"doer\"\n+++\n\nx\n")
                .unwrap()
                .altitude,
            Some(Altitude::Doer)
        );
        assert_eq!(
            RoleProfile::parse("+++\nrole = \"w\"\n+++\n\nx\n")
                .unwrap()
                .altitude,
            None,
            "absent altitude is None (doer applies downstream)"
        );
    }

    /// FR-4 (#1041): `skills` parses as a list of skill names, defaults to
    /// `None` when absent, and counts as role-binding front-matter.
    #[test]
    fn parses_skills_field() {
        let rp = RoleProfile::parse(
            "+++\nskills = [\"gila-personal-assistant\", \"other-skill\"]\n+++\n\nx\n",
        )
        .unwrap();
        assert_eq!(
            rp.skills,
            Some(vec![
                "gila-personal-assistant".to_string(),
                "other-skill".to_string(),
            ])
        );
        assert!(rp.is_role_bound(), "skills alone binds the role");
        assert_eq!(
            RoleProfile::parse("+++\nrole = \"w\"\n+++\n\nx\n")
                .unwrap()
                .skills,
            None,
            "absent skills is None (no bound skills)"
        );
    }

    #[test]
    fn leading_plus_text_is_not_a_fence() {
        // `+++foo` on the first line is body text, not a fence opener.
        let text = "+++foo bar\nstill body\n";
        let rp = RoleProfile::parse(text).unwrap();
        assert_eq!(rp.prompt, "+++foo bar\nstill body");
        assert!(!rp.is_role_bound());
    }

    #[test]
    fn scope_spec_items_round_trip() {
        let spec = ScopeSpec::Items(vec!["a".to_string(), "b".to_string()]);
        assert_eq!(
            spec.to_scope(),
            Scope::only(["a".to_string(), "b".to_string()])
        );
    }

    #[test]
    fn caveat_profile_default_is_top() {
        let c = CaveatProfile::default().to_caveats();
        assert_eq!(c, Caveats::top());
    }

    #[test]
    fn scope_spec_summary_renders_each_variant() {
        assert_eq!(ScopeSpec::Keyword(ScopeKeyword::All).summary(), "all");
        assert_eq!(ScopeSpec::Keyword(ScopeKeyword::None).summary(), "none");
        assert_eq!(
            ScopeSpec::Items(vec!["a".to_string(), "b".to_string()]).summary(),
            "[a, b]"
        );
    }

    #[test]
    fn caveat_profile_summary_is_one_line_per_axis() {
        let text = "\
+++
role = \"worker\"
[caveats]
fs_read = \"all\"
fs_write = \"none\"
exec = [\"cargo\"]
max_calls = 40
+++

# Worker
body
";
        let rp = RoleProfile::parse(text).unwrap();
        let summary = rp.caveats.unwrap().summary();
        assert_eq!(
            summary,
            "fs_read=all fs_write=none exec=[cargo] net=all max_calls=40"
        );
    }

    #[test]
    fn caveat_profile_summary_unlimited_when_no_max_calls() {
        let summary = CaveatProfile::default().summary();
        assert!(
            summary.ends_with("max_calls=unlimited"),
            "omitted max_calls renders as unlimited, got: {summary}"
        );
    }

    // --- #307 named permission presets ----------------------------------

    #[test]
    fn empty_preset_is_identity_clamp() {
        // An empty `[permission_presets.x]` block leaves authority unchanged:
        // its clamp is `top()`, so `base.meet(clamp) == base`.
        let p = NamedPermissionPreset::default();
        assert_eq!(p.clamp(), Caveats::top());
    }

    #[test]
    fn readonly_preset_denies_writes_and_exec() {
        // `readonly = true` ⇒ fs_write=none, exec=none; fs_read/net untouched.
        let p = NamedPermissionPreset {
            readonly: true,
            ..NamedPermissionPreset::default()
        };
        let c = p.clamp();
        assert_eq!(c.fs_read, Scope::All, "read-only still reads everything");
        assert_eq!(c.fs_write, Scope::none());
        assert_eq!(c.exec, Scope::none());
        assert_eq!(c.net, Scope::All, "net untouched without deny=*");
    }

    #[test]
    fn exec_allow_overrides_readonly_exec_clamp() {
        // A readonly triage mode may still permit a few read-only commands.
        let p = NamedPermissionPreset {
            readonly: true,
            exec_allow: vec!["git".to_string(), "gh".to_string()],
            ..NamedPermissionPreset::default()
        };
        let c = p.clamp();
        assert_eq!(c.fs_write, Scope::none(), "readonly still pins writes");
        assert_eq!(
            c.exec,
            Scope::only(["git".to_string(), "gh".to_string()]),
            "explicit allowlist wins over readonly's exec=none"
        );
    }

    #[test]
    fn deny_star_clamps_net_to_none() {
        let p = NamedPermissionPreset {
            fs_read: None,
            readonly: true,
            exec_allow: vec!["git".to_string()],
            deny: vec!["*".to_string()],
            max_calls: Some(40),
        };
        let c = p.clamp();
        assert_eq!(c.net, Scope::none(), "deny=* clamps the net axis");
        assert_eq!(c.max_calls, CountBound::AtMost(40));
    }

    #[test]
    fn preset_clamp_only_attenuates_a_full_base() {
        // The load-bearing property: meeting a fully-authorized base with a
        // readonly clamp yields exactly the clamp's restrictions — never wider.
        let p = NamedPermissionPreset {
            readonly: true,
            exec_allow: vec!["git".to_string()],
            deny: vec!["*".to_string()],
            ..NamedPermissionPreset::default()
        };
        let clamp = p.clamp();
        let effective = Caveats::top().meet(&clamp);
        assert_eq!(effective, clamp, "meet(top, clamp) == clamp");
        assert!(effective.leq(&Caveats::top()), "clamp ⊑ top (attenuation)");
    }

    #[test]
    fn preset_parses_from_config_toml_shape() {
        // The exact `[permission_presets.<name>]` shape from the issue.
        let toml = "\
readonly = true
exec_allow = [\"git\", \"gh\"]
deny = [\"*\"]
max_calls = 40
";
        let p: NamedPermissionPreset = toml::from_str(toml).unwrap();
        assert!(p.readonly);
        assert_eq!(p.exec_allow, vec!["git".to_string(), "gh".to_string()]);
        assert_eq!(p.deny, vec!["*".to_string()]);
        assert_eq!(p.max_calls, Some(40));
    }

    #[test]
    fn preset_summary_renders_each_clamp() {
        let p = NamedPermissionPreset {
            fs_read: None,
            readonly: true,
            exec_allow: vec!["git".to_string(), "gh".to_string()],
            deny: vec!["*".to_string()],
            max_calls: Some(40),
        };
        assert_eq!(p.summary(), "readonly exec=[git, gh] deny=* max_calls=40");
        assert_eq!(NamedPermissionPreset::default().summary(), "unconstrained");
    }

    // --- #755 M6 grammar gap: a preset can clamp fs_read -----------------

    #[test]
    fn fs_read_clamp_narrows_reads() {
        // M6 grammar-gap fix (issue #755): a preset CAN now clamp `fs_read`.
        //
        // RED on pre-#755 code: `to_caveat_profile` hardcoded
        // `fs_read: ScopeSpec::default()` (= `Scope::All`), so the `fs_read`
        // axis was *always* unrestricted regardless of the preset — this
        // assertion would have read `Scope::All`. GREEN once the optional
        // `fs_read` clamp is honored.
        let p = NamedPermissionPreset {
            fs_read: Some(ScopeSpec::Items(vec!["src/".to_string()])),
            ..NamedPermissionPreset::default()
        };
        let c = p.clamp();
        assert_eq!(
            c.fs_read,
            Scope::only(["src/".to_string()]),
            "an fs_read clamp must narrow the read axis"
        );
        // The other axes are untouched by an fs_read-only clamp.
        assert_eq!(c.fs_write, Scope::All);
        assert_eq!(c.exec, Scope::All);
        assert_eq!(c.net, Scope::All);
    }

    #[test]
    fn omitted_fs_read_clamp_reads_all() {
        // Back-compat: a preset that does not set `fs_read` leaves the read
        // axis at the top (`all`), exactly the pre-#755 behavior. A `None`
        // serde-default lowers to `ScopeSpec::default()` ⇒ `Scope::All`.
        let p = NamedPermissionPreset {
            readonly: true,
            ..NamedPermissionPreset::default()
        };
        assert_eq!(
            p.clamp().fs_read,
            Scope::All,
            "an unspecified fs_read clamp must leave reads unrestricted"
        );
        // The default preset declares no fs_read clamp.
        assert_eq!(NamedPermissionPreset::default().fs_read, None);
    }

    #[test]
    fn fs_read_clamp_parses_from_config_toml() {
        // The `[permission_presets.<name>]` config shape accepts an optional
        // `fs_read` clamp as a keyword or an allow-list, like the other axes.
        let toml = "\
readonly = true
fs_read = [\"src/\", \"docs/\"]
";
        let p: NamedPermissionPreset = toml::from_str(toml).unwrap();
        assert!(p.readonly);
        assert_eq!(
            p.fs_read,
            Some(ScopeSpec::Items(vec![
                "src/".to_string(),
                "docs/".to_string()
            ]))
        );
        assert_eq!(
            p.clamp().fs_read,
            Scope::only(["src/".to_string(), "docs/".to_string()])
        );
    }

    // --- #1021 PR 5.2: headless `RoleProfile::load_from_dir` -------------

    #[test]
    fn load_from_dir_parses_an_existing_persona() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("personal-assistant.md"),
            "+++\nrole = \"personal-assistant\"\ntools = [\"a\"]\n+++\n\n# PA\nbody\n",
        )
        .unwrap();
        let rp = RoleProfile::load_from_dir("personal-assistant", tmp.path(), &mut |_| {}).unwrap();
        assert_eq!(rp.role.as_deref(), Some("personal-assistant"));
        assert_eq!(rp.prompt, "# PA\nbody");
    }

    #[test]
    fn load_from_dir_errors_loudly_on_a_missing_file_no_seeding() {
        let tmp = tempfile::TempDir::new().unwrap();
        let err = RoleProfile::load_from_dir("nope", tmp.path(), &mut |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("not found"), "got: {err}");
        assert!(
            !tmp.path().join("nope.md").exists(),
            "a missing persona must NOT be silently seeded (headless callers fail loudly instead)"
        );
    }

    #[test]
    fn load_from_dir_rejects_invalid_names() {
        let tmp = tempfile::TempDir::new().unwrap();
        let err = RoleProfile::load_from_dir("bad name!", tmp.path(), &mut |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("letters, numbers"), "got: {err}");
    }

    #[test]
    fn load_from_dir_rejects_an_empty_persona_file() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::write(tmp.path().join("blank.md"), "   \n").unwrap();
        let err = RoleProfile::load_from_dir("blank", tmp.path(), &mut |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("is empty"), "got: {err}");
    }

    /// Slice 1a rename: the headless `--persona` path migrates an old
    /// cognition label instead of failing the strict parse. Grounds the
    /// mocked `psyche_import` seam test: this real read reaches the importer.
    #[test]
    #[ignore = "real-resource: weekly/release tier; touches the filesystem"]
    #[serial_test::serial(real_fs)]
    fn load_from_dir_migrates_an_old_cognition_label() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("deep.md");
        std::fs::write(&path, "+++\ncognition = \"contemplating\"\n+++\n# Deep\n").unwrap();
        let rp = RoleProfile::load_from_dir("deep", tmp.path(), &mut |_| {}).unwrap();
        assert_eq!(rp.cognition, Some(Cognition::Meticulous));
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "+++\ncognition = \"meticulous\"\n+++\n# Deep\n"
        );
    }

    #[test]
    fn load_from_dir_lowercases_the_name() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::write(tmp.path().join("coach.md"), "# Coach\nbody\n").unwrap();
        let rp = RoleProfile::load_from_dir("  CoAcH  ", tmp.path(), &mut |_| {}).unwrap();
        assert_eq!(rp.prompt, "# Coach\nbody");
    }
}