mars-agents 0.4.8-rc.2

Agent package manager for .agents/ directories
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
/// Agent-profile schema, parser, and validation.
///
/// Parses agent markdown frontmatter into strongly-typed [`AgentProfile`] fields.
/// Used by the dual-surface compilation pipeline to:
/// - Validate agent profiles at compile time
/// - Route agents to the correct harness-native output surface
/// - Report lossiness diagnostics when fields cannot be expressed in a target format
pub mod lower;

use serde_yaml::Value;

use crate::frontmatter::{Frontmatter, FrontmatterError};

// ---------------------------------------------------------------------------
// Field enums
// ---------------------------------------------------------------------------

/// Agent execution mode — how the agent is launched.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AgentMode {
    Primary,
    Subagent,
}

impl AgentMode {
    pub fn as_str(&self) -> &str {
        match self {
            AgentMode::Primary => "primary",
            AgentMode::Subagent => "subagent",
        }
    }
}

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

/// Known harness execution targets.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HarnessKind {
    Claude,
    Codex,
    OpenCode,
    Cursor,
    Pi,
}

impl HarnessKind {
    pub fn all() -> &'static [Self] {
        &[
            Self::Claude,
            Self::Codex,
            Self::OpenCode,
            Self::Cursor,
            Self::Pi,
        ]
    }

    /// Parse from a frontmatter string value.
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "claude" => Some(Self::Claude),
            "codex" => Some(Self::Codex),
            "opencode" => Some(Self::OpenCode),
            "cursor" => Some(Self::Cursor),
            "pi" => Some(Self::Pi),
            _ => None,
        }
    }

    /// Target directory root for harness-native artifacts.
    pub fn target_dir(&self) -> &str {
        match self {
            Self::Claude => ".claude",
            Self::Codex => ".codex",
            Self::OpenCode => ".opencode",
            Self::Cursor => ".cursor",
            Self::Pi => ".pi",
        }
    }
}

/// Approval policy field.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApprovalMode {
    Default,
    Auto,
    Confirm,
    Yolo,
}

impl ApprovalMode {
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "default" => Some(Self::Default),
            "auto" => Some(Self::Auto),
            "confirm" => Some(Self::Confirm),
            "yolo" => Some(Self::Yolo),
            _ => None,
        }
    }
}

/// Sandbox mode field.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SandboxMode {
    Default,
    ReadOnly,
    WorkspaceWrite,
    DangerFullAccess,
}

impl SandboxMode {
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "default" => Some(Self::Default),
            "read-only" => Some(Self::ReadOnly),
            "workspace-write" => Some(Self::WorkspaceWrite),
            "danger-full-access" => Some(Self::DangerFullAccess),
            _ => None,
        }
    }

    pub fn as_str(&self) -> &str {
        match self {
            Self::Default => "default",
            Self::ReadOnly => "read-only",
            Self::WorkspaceWrite => "workspace-write",
            Self::DangerFullAccess => "danger-full-access",
        }
    }
}

/// Effort level field.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EffortLevel {
    Low,
    Medium,
    High,
    XHigh,
}

impl EffortLevel {
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "low" => Some(Self::Low),
            "medium" => Some(Self::Medium),
            "high" => Some(Self::High),
            "xhigh" | "max" => Some(Self::XHigh),
            _ => None,
        }
    }

    pub fn as_str(&self) -> &str {
        match self {
            Self::Low => "low",
            Self::Medium => "medium",
            Self::High => "high",
            Self::XHigh => "xhigh",
        }
    }

    /// Normalized value for Claude ("xhigh" → "max").
    pub fn claude_str(&self) -> &str {
        match self {
            Self::XHigh => "max",
            other => other.as_str(),
        }
    }
}

// ---------------------------------------------------------------------------
// Override table types
// ---------------------------------------------------------------------------

/// A set of overridable field values for one harness or model override entry.
/// Only fields explicitly specified in the override block are present.
#[derive(Debug, Clone, Default)]
pub struct OverrideFields {
    pub effort: Option<EffortLevel>,
    pub autocompact: Option<u32>,
    pub autocompact_pct: Option<u8>,
    pub approval: Option<ApprovalMode>,
    pub sandbox: Option<SandboxMode>,
    pub skills: Option<Vec<String>>,
    pub tools: Option<Vec<String>>,
    pub tools_denied: Option<Vec<String>>,
    pub disallowed_tools: Option<Vec<String>>,
    pub mcp_tools: Option<Vec<String>>,
    pub native_config: Option<serde_json::Map<String, serde_json::Value>>,
}

/// Per-harness override table (`harness-overrides:`).
#[derive(Debug, Clone, Default)]
pub struct HarnessOverrides {
    pub claude: Option<OverrideFields>,
    pub codex: Option<OverrideFields>,
    pub opencode: Option<OverrideFields>,
    pub cursor: Option<OverrideFields>,
    pub pi: Option<OverrideFields>,
}

impl HarnessOverrides {
    pub fn get(&self, harness: &HarnessKind) -> Option<&OverrideFields> {
        match harness {
            HarnessKind::Claude => self.claude.as_ref(),
            HarnessKind::Codex => self.codex.as_ref(),
            HarnessKind::OpenCode => self.opencode.as_ref(),
            HarnessKind::Cursor => self.cursor.as_ref(),
            HarnessKind::Pi => self.pi.as_ref(),
        }
    }
}

/// Parsed `model-policies:` entry.
///
/// Per the spec (D43), model-policies are consumed by Meridian at runtime.
/// Mars parses them at compile time only for validation and preservation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelPolicyEntry {
    pub match_type: ModelPolicyMatchType,
    pub match_value: String,
    pub no_fallback: bool,
    pub overrides: serde_yaml::Mapping,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ModelPolicyMatchType {
    Model,
    Alias,
    ModelGlob,
}

/// Marker for a validated fanout inventory entry (`fanout:`).
///
/// Fanout is metadata-only (D43): it never gains lowering behavior.
/// Mars parses it for validation and preservation; no harness-native artifact
/// receives fanout entries.
#[derive(Debug, Clone)]
pub struct FanoutEntry;

// ---------------------------------------------------------------------------
// AgentProfile — the fully parsed frontmatter
// ---------------------------------------------------------------------------

/// Strongly-typed representation of an agent profile's frontmatter.
///
/// Parsed from YAML frontmatter by [`parse_agent_profile`].
/// Used for:
/// - Compile-time validation (mode values, non-overridable fields in overrides)
/// - Dual-surface routing (harness → output target)
/// - Per-target lowering (field lowering per agent-compilation-mapping.md)
#[derive(Debug, Clone)]
pub struct AgentProfile {
    // --- Identity fields ---
    pub name: Option<String>,
    pub description: Option<String>,

    // --- Routing fields ---
    pub harness: Option<HarnessKind>,

    // --- Model fields ---
    pub model: Option<String>,

    // --- Runtime policy fields ---
    pub mode: Option<AgentMode>,
    pub model_invocable: bool,
    pub approval: Option<ApprovalMode>,
    pub sandbox: Option<SandboxMode>,
    pub effort: Option<EffortLevel>,
    pub autocompact: Option<u32>,
    pub autocompact_pct: Option<u8>,

    // --- Tool fields ---
    pub skills: Vec<String>,
    pub tools: Vec<String>,
    pub tools_denied: Vec<String>,
    pub disallowed_tools: Vec<String>,
    pub mcp_tools: Vec<String>,

    // --- Override tables ---
    pub harness_overrides: HarnessOverrides,
    pub model_policies: Vec<ModelPolicyEntry>,
    pub fanout: Vec<FanoutEntry>,
}

/// Portable tool policy after applying harness override replacement semantics.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EffectiveToolPolicy {
    pub allowed: Vec<String>,
    pub disallowed: Vec<String>,
    pub mcp: Vec<String>,
}

impl AgentProfile {
    pub fn effective_skills(&self, harness: &HarnessKind) -> &[String] {
        self.harness_overrides
            .get(harness)
            .and_then(|entry| entry.skills.as_ref())
            .unwrap_or(&self.skills)
    }

    pub fn effective_native_config(
        &self,
        harness: &HarnessKind,
    ) -> Option<&serde_json::Map<String, serde_json::Value>> {
        self.harness_overrides
            .get(harness)
            .and_then(|entry| entry.native_config.as_ref())
            .filter(|map| !map.is_empty())
    }

    pub fn effective_tool_policy(&self, harness: &HarnessKind) -> EffectiveToolPolicy {
        let overrides = self.harness_overrides.get(harness);
        let allowed = overrides
            .and_then(|entry| entry.tools.clone())
            .unwrap_or_else(|| self.tools.clone());
        let tools_denied = overrides
            .and_then(|entry| entry.tools_denied.clone())
            .unwrap_or_else(|| self.tools_denied.clone());
        let explicit_disallowed = overrides
            .and_then(|entry| entry.disallowed_tools.clone())
            .unwrap_or_else(|| self.disallowed_tools.clone());
        let mcp = overrides
            .and_then(|entry| entry.mcp_tools.clone())
            .unwrap_or_else(|| self.mcp_tools.clone());

        EffectiveToolPolicy {
            allowed: dedupe_ordered(allowed),
            disallowed: dedupe_ordered(
                tools_denied
                    .into_iter()
                    .chain(explicit_disallowed)
                    .collect(),
            ),
            mcp: dedupe_ordered(mcp),
        }
    }
}

// ---------------------------------------------------------------------------
// Validation warnings/errors
// ---------------------------------------------------------------------------

/// A validation finding from agent profile parsing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AgentDiagnostic {
    /// Field value is not in the allowed set.
    InvalidFieldValue {
        field: String,
        value: String,
        allowed: &'static str,
    },
    /// Deprecated `models:` field was found (use `model-overrides:` instead).
    LegacyModelsField,
    /// Unknown harness name — not one of claude/codex/opencode/pi.
    UnknownHarness { value: String },
    /// Non-overridable field appears inside an override block.
    NonOverridableFieldInOverride { field: String, table: String },
    /// `native-config` key collides with a known portable policy field name.
    NativeConfigPortableKeyCollision { key: String, table: String },
}

impl AgentDiagnostic {
    pub fn is_error(&self) -> bool {
        matches!(
            self,
            AgentDiagnostic::InvalidFieldValue { .. }
                | AgentDiagnostic::UnknownHarness { .. }
                | AgentDiagnostic::NonOverridableFieldInOverride { .. }
        )
    }

    pub fn message(&self) -> String {
        match self {
            AgentDiagnostic::InvalidFieldValue {
                field,
                value,
                allowed,
            } => {
                format!("agent field `{field}` has invalid value `{value}`; allowed: {allowed}")
            }
            AgentDiagnostic::LegacyModelsField => {
                "agent uses deprecated `models:` field; rename to `model-overrides:`".to_string()
            }
            AgentDiagnostic::UnknownHarness { value } => {
                format!("unknown harness `{value}`; known: claude, codex, opencode, cursor, pi")
            }
            AgentDiagnostic::NonOverridableFieldInOverride { field, table } => {
                format!("field `{field}` is not overridable; remove from `{table}`")
            }
            AgentDiagnostic::NativeConfigPortableKeyCollision { key, table } => format!(
                "native-config key `{key}` in `{table}` collides with a portable field name; preserving as native-config"
            ),
        }
    }
}

// ---------------------------------------------------------------------------
// Non-overridable field names (compile error if inside an override block)
// ---------------------------------------------------------------------------

const NON_OVERRIDABLE: &[&str] = &[
    "name",
    "description",
    "model",
    "harness",
    "mode",
    "model-invocable",
    "model-overrides",
    "harness-overrides",
];

// ---------------------------------------------------------------------------
// Parsing helpers
// ---------------------------------------------------------------------------

fn yaml_str_list(val: &Value) -> Vec<String> {
    match val {
        Value::Sequence(seq) => seq
            .iter()
            .filter_map(|v| v.as_str())
            .map(str::to_owned)
            .collect(),
        Value::String(s) => vec![s.clone()],
        _ => vec![],
    }
}

fn normalize_tool_name(raw: &str) -> String {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return String::new();
    }

    let (head, tail) = match trimmed.find('(') {
        Some(index) => (&trimmed[..index], &trimmed[index..]),
        None => (trimmed, ""),
    };
    let canonical = match head {
        value if value.eq_ignore_ascii_case("bash") => "Bash",
        value if value.eq_ignore_ascii_case("read") => "Read",
        value if value.eq_ignore_ascii_case("write") => "Write",
        value if value.eq_ignore_ascii_case("edit") => "Edit",
        value if value.eq_ignore_ascii_case("agent") => "Agent",
        _ => head,
    };
    format!("{canonical}{tail}")
}

fn dedupe_ordered(values: Vec<String>) -> Vec<String> {
    let mut seen = std::collections::HashSet::new();
    let mut out = Vec::new();
    for value in values {
        let trimmed = value.trim();
        if trimmed.is_empty() {
            continue;
        }
        let key = trimmed.to_string();
        if seen.insert(key.clone()) {
            out.push(key);
        }
    }
    out
}

fn yaml_tool_list(val: &Value) -> Vec<String> {
    dedupe_ordered(
        yaml_str_list(val)
            .into_iter()
            .map(|tool| normalize_tool_name(&tool))
            .collect(),
    )
}

#[derive(Default)]
struct ParsedToolsField {
    allowed: Vec<String>,
    denied: Vec<String>,
}

fn parse_tools_field(
    field: &str,
    val: &Value,
    diags: &mut Vec<AgentDiagnostic>,
) -> ParsedToolsField {
    match val {
        Value::Mapping(mapping) => {
            let mut allowed = Vec::new();
            let mut denied = Vec::new();
            for (key, value) in mapping {
                let Some(tool_name) = key.as_str() else {
                    diags.push(AgentDiagnostic::InvalidFieldValue {
                        field: field.to_string(),
                        value: format!("{key:?}"),
                        allowed: "string tool keys",
                    });
                    continue;
                };

                let Some(policy) = value.as_str() else {
                    diags.push(AgentDiagnostic::InvalidFieldValue {
                        field: format!("{field}.{tool_name}"),
                        value: format!("{value:?}"),
                        allowed: "allow or deny",
                    });
                    continue;
                };

                let normalized_tool = normalize_tool_name(tool_name);
                if policy.eq_ignore_ascii_case("allow") {
                    allowed.push(normalized_tool);
                } else if policy.eq_ignore_ascii_case("deny") {
                    denied.push(normalized_tool);
                } else {
                    diags.push(AgentDiagnostic::InvalidFieldValue {
                        field: format!("{field}.{tool_name}"),
                        value: policy.to_string(),
                        allowed: "allow or deny",
                    });
                }
            }
            ParsedToolsField {
                allowed: dedupe_ordered(allowed),
                denied: dedupe_ordered(denied),
            }
        }
        _ => ParsedToolsField {
            allowed: yaml_tool_list(val),
            denied: vec![],
        },
    }
}

fn parse_native_config_value(
    field: &str,
    value: &Value,
    diags: &mut Vec<AgentDiagnostic>,
) -> Option<serde_json::Value> {
    match value {
        Value::Null => {
            diags.push(AgentDiagnostic::InvalidFieldValue {
                field: field.to_string(),
                value: "null".to_string(),
                allowed: "non-null scalar, array, or map value",
            });
            None
        }
        Value::Bool(v) => Some(serde_json::Value::Bool(*v)),
        Value::String(v) => Some(serde_json::Value::String(v.clone())),
        Value::Number(v) => {
            if let Some(number) = v.as_i64().map(serde_json::Number::from) {
                Some(serde_json::Value::Number(number))
            } else if let Some(number) = v.as_u64().map(serde_json::Number::from) {
                Some(serde_json::Value::Number(number))
            } else if let Some(float) = v.as_f64() {
                match serde_json::Number::from_f64(float) {
                    Some(number) => Some(serde_json::Value::Number(number)),
                    None => {
                        diags.push(AgentDiagnostic::InvalidFieldValue {
                            field: field.to_string(),
                            value: float.to_string(),
                            allowed: "finite JSON number",
                        });
                        None
                    }
                }
            } else {
                diags.push(AgentDiagnostic::InvalidFieldValue {
                    field: field.to_string(),
                    value: format!("{value:?}"),
                    allowed: "JSON number",
                });
                None
            }
        }
        Value::Sequence(seq) => {
            let mut out = Vec::with_capacity(seq.len());
            for (index, entry) in seq.iter().enumerate() {
                let child_field = format!("{field}[{index}]");
                let parsed = parse_native_config_value(&child_field, entry, diags)?;
                out.push(parsed);
            }
            Some(serde_json::Value::Array(out))
        }
        Value::Mapping(mapping) => {
            let mut out = serde_json::Map::new();
            for (key, entry) in mapping {
                let Some(key_text) = key.as_str() else {
                    diags.push(AgentDiagnostic::InvalidFieldValue {
                        field: field.to_string(),
                        value: format!("{key:?}"),
                        allowed: "string keys",
                    });
                    return None;
                };
                let child_field = format!("{field}.{key_text}");
                let parsed = parse_native_config_value(&child_field, entry, diags)?;
                out.insert(key_text.to_string(), parsed);
            }
            Some(serde_json::Value::Object(out))
        }
        _ => {
            diags.push(AgentDiagnostic::InvalidFieldValue {
                field: field.to_string(),
                value: format!("{value:?}"),
                allowed: "YAML/TOML/JSON-serializable value",
            });
            None
        }
    }
}

fn parse_native_config_map(
    field: &str,
    val: &Value,
    diags: &mut Vec<AgentDiagnostic>,
) -> Option<serde_json::Map<String, serde_json::Value>> {
    const PORTABLE_FIELD_NAMES: &[&str] = &[
        "sandbox",
        "approval",
        "effort",
        "autocompact",
        "autocompact_pct",
        "skills",
        "tools",
        "disallowed-tools",
        "mcp-tools",
    ];

    let Some(mapping) = val.as_mapping() else {
        diags.push(AgentDiagnostic::InvalidFieldValue {
            field: field.to_string(),
            value: format!("{val:?}"),
            allowed: "mapping with string keys and non-null serializable values",
        });
        return None;
    };

    let mut out = serde_json::Map::new();
    for (key, value) in mapping {
        let Some(key_text) = key.as_str() else {
            diags.push(AgentDiagnostic::InvalidFieldValue {
                field: field.to_string(),
                value: format!("{key:?}"),
                allowed: "string keys",
            });
            return None;
        };

        if PORTABLE_FIELD_NAMES.contains(&key_text) {
            diags.push(AgentDiagnostic::NativeConfigPortableKeyCollision {
                key: key_text.to_string(),
                table: field.to_string(),
            });
        }

        let value_field = format!("{field}.{key_text}");
        let parsed = parse_native_config_value(&value_field, value, diags)?;
        out.insert(key_text.to_string(), parsed);
    }

    Some(out)
}

fn parse_override_fields(
    mapping: &serde_yaml::Mapping,
    table_name: &str,
    diags: &mut Vec<AgentDiagnostic>,
) -> OverrideFields {
    let mut out = OverrideFields::default();

    for (k, v) in mapping {
        let key = match k.as_str() {
            Some(s) => s,
            None => continue,
        };

        if NON_OVERRIDABLE.contains(&key) {
            diags.push(AgentDiagnostic::NonOverridableFieldInOverride {
                field: key.to_string(),
                table: table_name.to_string(),
            });
            continue;
        }

        match key {
            "effort" => {
                if let Some(s) = v.as_str() {
                    if let Some(e) = EffortLevel::from_str(s) {
                        out.effort = Some(e);
                    } else {
                        diags.push(AgentDiagnostic::InvalidFieldValue {
                            field: format!("{table_name}.effort"),
                            value: s.to_string(),
                            allowed: "low, medium, high, xhigh",
                        });
                    }
                }
            }
            "autocompact" => {
                if let Some(n) = v.as_u64() {
                    match u32::try_from(n) {
                        Ok(v32) => out.autocompact = Some(v32),
                        Err(_) => diags.push(AgentDiagnostic::InvalidFieldValue {
                            field: format!("{table_name}.autocompact"),
                            value: n.to_string(),
                            allowed: "integer 0–4294967295",
                        }),
                    }
                } else {
                    diags.push(AgentDiagnostic::InvalidFieldValue {
                        field: format!("{table_name}.autocompact"),
                        value: format!("{v:?}"),
                        allowed: "integer (token count)",
                    });
                }
            }
            "autocompact_pct" => {
                if let Some(n) = v.as_u64() {
                    if (1..=100).contains(&n) {
                        out.autocompact_pct = Some(n as u8);
                    } else {
                        diags.push(AgentDiagnostic::InvalidFieldValue {
                            field: format!("{table_name}.autocompact_pct"),
                            value: n.to_string(),
                            allowed: "integer 1–100",
                        });
                    }
                } else {
                    diags.push(AgentDiagnostic::InvalidFieldValue {
                        field: format!("{table_name}.autocompact_pct"),
                        value: format!("{v:?}"),
                        allowed: "integer 1–100",
                    });
                }
            }
            "approval" => {
                if let Some(s) = v.as_str() {
                    if let Some(a) = ApprovalMode::from_str(s) {
                        out.approval = Some(a);
                    } else {
                        diags.push(AgentDiagnostic::InvalidFieldValue {
                            field: format!("{table_name}.approval"),
                            value: s.to_string(),
                            allowed: "default, auto, confirm, yolo",
                        });
                    }
                }
            }
            "sandbox" => {
                if let Some(s) = v.as_str() {
                    if let Some(sb) = SandboxMode::from_str(s) {
                        out.sandbox = Some(sb);
                    } else {
                        diags.push(AgentDiagnostic::InvalidFieldValue {
                            field: format!("{table_name}.sandbox"),
                            value: s.to_string(),
                            allowed: "default, read-only, workspace-write, danger-full-access",
                        });
                    }
                }
            }
            "skills" => {
                out.skills = Some(yaml_str_list(v));
            }
            "tools" => {
                let parsed = parse_tools_field(&format!("{table_name}.tools"), v, diags);
                out.tools = Some(parsed.allowed);
                out.tools_denied = Some(parsed.denied);
            }
            "disallowed-tools" => {
                out.disallowed_tools = Some(yaml_tool_list(v));
            }
            "mcp-tools" => {
                out.mcp_tools = Some(yaml_str_list(v));
            }
            "native-config" => {
                out.native_config =
                    parse_native_config_map(&format!("{table_name}.native-config"), v, diags);
            }
            _ => {
                // Unknown override field — tolerate (forward compat).
            }
        }
    }

    out
}

fn parse_harness_overrides(val: &Value, diags: &mut Vec<AgentDiagnostic>) -> HarnessOverrides {
    let mut out = HarnessOverrides::default();
    let Some(mapping) = val.as_mapping() else {
        return out;
    };

    for (k, v) in mapping {
        let harness_name = match k.as_str() {
            Some(s) => s,
            None => continue,
        };
        let sub_mapping = match v.as_mapping() {
            Some(m) => m,
            None => continue,
        };
        let table_name = format!("harness-overrides.{harness_name}");
        let fields = parse_override_fields(sub_mapping, &table_name, diags);
        match harness_name {
            "claude" => out.claude = Some(fields),
            "codex" => out.codex = Some(fields),
            "opencode" => out.opencode = Some(fields),
            "cursor" => out.cursor = Some(fields),
            "pi" => out.pi = Some(fields),
            other => {
                diags.push(AgentDiagnostic::UnknownHarness {
                    value: other.to_string(),
                });
            }
        }
    }

    out
}

fn push_model_policy_invalid(
    diags: &mut Vec<AgentDiagnostic>,
    field: impl Into<String>,
    value: impl Into<String>,
    allowed: &'static str,
) {
    diags.push(AgentDiagnostic::InvalidFieldValue {
        field: field.into(),
        value: value.into(),
        allowed,
    });
}

fn parse_model_policies(val: &Value, diags: &mut Vec<AgentDiagnostic>) -> Vec<ModelPolicyEntry> {
    let Some(seq) = val.as_sequence() else {
        push_model_policy_invalid(
            diags,
            "model-policies",
            format!("{val:?}"),
            "sequence of rules",
        );
        return vec![];
    };

    let mut out = Vec::new();
    for (index, entry) in seq.iter().enumerate() {
        let position = index + 1;
        let Some(rule) = entry.as_mapping() else {
            push_model_policy_invalid(
                diags,
                format!("model-policies[{position}]"),
                format!("{entry:?}"),
                "mapping with match and override",
            );
            continue;
        };

        let match_value = rule.get(Value::String("match".to_string()));
        let Some(match_mapping) = match_value.and_then(Value::as_mapping) else {
            push_model_policy_invalid(
                diags,
                format!("model-policies[{position}].match"),
                match_value
                    .map(|value| format!("{value:?}"))
                    .unwrap_or_else(|| "<missing>".to_string()),
                "mapping with exactly one of model, alias, model-glob",
            );
            continue;
        };

        let normalized_match_keys: Vec<&str> =
            match_mapping.keys().filter_map(Value::as_str).collect();
        if normalized_match_keys.len() != 1 {
            push_model_policy_invalid(
                diags,
                format!("model-policies[{position}].match"),
                format!("{match_mapping:?}"),
                "exactly one of model, alias, model-glob",
            );
            continue;
        }
        let match_key = normalized_match_keys[0];
        if !matches!(match_key, "model" | "alias" | "model-glob") {
            push_model_policy_invalid(
                diags,
                format!("model-policies[{position}].match"),
                match_key,
                "model, alias, model-glob",
            );
            continue;
        }
        let raw_match_value = match_mapping.get(Value::String(match_key.to_string()));
        let Some(match_text) = raw_match_value.and_then(Value::as_str).map(str::trim) else {
            push_model_policy_invalid(
                diags,
                format!("model-policies[{position}].match.{match_key}"),
                raw_match_value
                    .map(|value| format!("{value:?}"))
                    .unwrap_or_else(|| "<missing>".to_string()),
                "non-empty string",
            );
            continue;
        };
        if match_text.is_empty() {
            push_model_policy_invalid(
                diags,
                format!("model-policies[{position}].match.{match_key}"),
                "<empty>",
                "non-empty string",
            );
            continue;
        }

        let override_value = rule.get(Value::String("override".to_string()));
        let empty_override = serde_yaml::Mapping::new();
        let override_mapping = match override_value {
            None | Some(Value::Null) => &empty_override,
            Some(value) => {
                let Some(mapping) = value.as_mapping() else {
                    push_model_policy_invalid(
                        diags,
                        format!("model-policies[{position}].override"),
                        format!("{value:?}"),
                        "mapping",
                    );
                    continue;
                };
                mapping
            }
        };

        let no_fallback = match rule.get(Value::String("no-fallback".to_string())) {
            None | Some(Value::Null) => false,
            Some(Value::Bool(value)) => *value,
            Some(value) => {
                push_model_policy_invalid(
                    diags,
                    format!("model-policies[{position}].no-fallback"),
                    format!("{value:?}"),
                    "boolean",
                );
                continue;
            }
        };

        let match_type = match match_key {
            "model" => ModelPolicyMatchType::Model,
            "alias" => ModelPolicyMatchType::Alias,
            "model-glob" => ModelPolicyMatchType::ModelGlob,
            _ => unreachable!("match_key was validated above"),
        };

        out.push(ModelPolicyEntry {
            match_type,
            match_value: match_text.to_string(),
            no_fallback,
            overrides: override_mapping.clone(),
        });
    }
    out
}

fn parse_fanout(val: &Value) -> Vec<FanoutEntry> {
    match val {
        Value::Sequence(seq) => seq.iter().map(|_| FanoutEntry).collect(),
        _ => vec![],
    }
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Parse an agent profile from a [`Frontmatter`].
///
/// Collects diagnostics without failing — the caller decides whether errors
/// are fatal. The parsed [`AgentProfile`] is always returned even when there
/// are validation errors; invalid fields are skipped (omitted from the profile).
pub fn parse_agent_profile(fm: &Frontmatter, diags: &mut Vec<AgentDiagnostic>) -> AgentProfile {
    let name = fm.name().map(str::to_owned);
    let description = fm
        .get("description")
        .and_then(Value::as_str)
        .map(str::to_owned);

    // harness:
    let harness = fm.get("harness").and_then(Value::as_str).and_then(|s| {
        if let Some(h) = HarnessKind::from_str(s) {
            Some(h)
        } else {
            diags.push(AgentDiagnostic::UnknownHarness {
                value: s.to_string(),
            });
            None
        }
    });

    // model:
    let model = fm.get("model").and_then(Value::as_str).map(str::to_owned);

    // mode:
    let mode = fm
        .get("mode")
        .and_then(Value::as_str)
        .and_then(|s| match s {
            "primary" => Some(AgentMode::Primary),
            "subagent" => Some(AgentMode::Subagent),
            other => {
                diags.push(AgentDiagnostic::InvalidFieldValue {
                    field: "mode".to_string(),
                    value: other.to_string(),
                    allowed: "primary, subagent",
                });
                None
            }
        });

    // model-invocable:
    let model_invocable = match fm.get("model-invocable") {
        None => true,
        Some(Value::Bool(value)) => *value,
        Some(value) => {
            diags.push(AgentDiagnostic::InvalidFieldValue {
                field: "model-invocable".to_string(),
                value: format!("{value:?}"),
                allowed: "boolean",
            });
            true
        }
    };

    // approval:
    let approval = fm.get("approval").and_then(Value::as_str).and_then(|s| {
        if let Some(a) = ApprovalMode::from_str(s) {
            Some(a)
        } else {
            diags.push(AgentDiagnostic::InvalidFieldValue {
                field: "approval".to_string(),
                value: s.to_string(),
                allowed: "default, auto, confirm, yolo",
            });
            None
        }
    });

    // sandbox:
    let sandbox = fm.get("sandbox").and_then(Value::as_str).and_then(|s| {
        if let Some(sb) = SandboxMode::from_str(s) {
            Some(sb)
        } else {
            diags.push(AgentDiagnostic::InvalidFieldValue {
                field: "sandbox".to_string(),
                value: s.to_string(),
                allowed: "default, read-only, workspace-write, danger-full-access",
            });
            None
        }
    });

    // effort:
    let effort = fm.get("effort").and_then(Value::as_str).and_then(|s| {
        if let Some(e) = EffortLevel::from_str(s) {
            Some(e)
        } else {
            diags.push(AgentDiagnostic::InvalidFieldValue {
                field: "effort".to_string(),
                value: s.to_string(),
                allowed: "low, medium, high, xhigh",
            });
            None
        }
    });

    // autocompact:
    let autocompact = match fm.get("autocompact") {
        None => None,
        Some(v) => {
            if let Some(n) = v.as_u64() {
                match u32::try_from(n) {
                    Ok(v32) => Some(v32),
                    Err(_) => {
                        diags.push(AgentDiagnostic::InvalidFieldValue {
                            field: "autocompact".to_string(),
                            value: n.to_string(),
                            allowed: "integer 0–4294967295",
                        });
                        None
                    }
                }
            } else {
                diags.push(AgentDiagnostic::InvalidFieldValue {
                    field: "autocompact".to_string(),
                    value: format!("{v:?}"),
                    allowed: "integer (token count)",
                });
                None
            }
        }
    };

    // autocompact_pct:
    let autocompact_pct = match fm.get("autocompact_pct") {
        None => None,
        Some(v) => {
            if let Some(n) = v.as_u64() {
                if (1..=100).contains(&n) {
                    Some(n as u8)
                } else {
                    diags.push(AgentDiagnostic::InvalidFieldValue {
                        field: "autocompact_pct".to_string(),
                        value: n.to_string(),
                        allowed: "integer 1–100",
                    });
                    None
                }
            } else {
                diags.push(AgentDiagnostic::InvalidFieldValue {
                    field: "autocompact_pct".to_string(),
                    value: format!("{v:?}"),
                    allowed: "integer 1–100",
                });
                None
            }
        }
    };

    // skills/tools/disallowed-tools/mcp-tools:
    let skills = fm.skills();
    let parsed_tools = fm
        .get("tools")
        .map(|value| parse_tools_field("tools", value, diags))
        .unwrap_or_default();
    let tools = parsed_tools.allowed;
    let tools_denied = parsed_tools.denied;
    let disallowed_tools = fm
        .get("disallowed-tools")
        .map(yaml_tool_list)
        .unwrap_or_default();
    let mcp_tools = fm.get("mcp-tools").map(yaml_str_list).unwrap_or_default();

    // harness-overrides:
    let harness_overrides = fm
        .get("harness-overrides")
        .map(|v| parse_harness_overrides(v, diags))
        .unwrap_or_default();

    // model-policies:
    let model_policies = fm
        .get("model-policies")
        .map(|value| parse_model_policies(value, diags))
        .unwrap_or_default();

    // fanout:
    let fanout = fm.get("fanout").map(parse_fanout).unwrap_or_default();

    // Legacy models: field
    if fm.get("models").is_some() {
        diags.push(AgentDiagnostic::LegacyModelsField);
    }

    AgentProfile {
        name,
        description,
        harness,
        model,
        mode,
        model_invocable,
        approval,
        sandbox,
        effort,
        autocompact,
        autocompact_pct,
        skills,
        tools,
        tools_denied,
        disallowed_tools,
        mcp_tools,
        harness_overrides,
        model_policies,
        fanout,
    }
}

/// Parse an agent profile from raw markdown content.
///
/// Convenience wrapper over [`parse_agent_profile`].
pub fn parse_agent_content(
    content: &str,
    diags: &mut Vec<AgentDiagnostic>,
) -> Result<(AgentProfile, Frontmatter), FrontmatterError> {
    let fm = Frontmatter::parse(content)?;
    let profile = parse_agent_profile(&fm, diags);
    Ok((profile, fm))
}

#[cfg(test)]
mod tests;