mars-schema 0.36.2

Pure schema reader and editor for Mars agent packages
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
//! What `mars.toml` holds beyond `[package]` and the dependency tables: `[settings]`,
//! `[models]`, `[agents]`, `[skills]` and `[plugin]`, read as the CLI reads them, and the reader
//! the project's other config files share.
//!
//! One serde pass reads a whole file; a key it leaves unread becomes one `field.unknown` note and
//! stays in the file. Nothing here names a key that was once read (see `retired`).

use indexmap::IndexMap;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_ignored::Path as IgnoredPath;

use crate::alias::ModelAlias;
use crate::dependency::RawEntry;
use crate::diagnostic::{PathSegment, SchemaDiagnostic, unknown_field};
use crate::keys;
use crate::model_policy::ModelPolicyRule;
use crate::names::SourceName;
use crate::network::{NetworkHost, NetworkPolicy};
use crate::package::PackageMetadata as PackageInfo;
use crate::permission_set::PermissionSet;
use crate::tool_rule_map::ToolRuleMap;

/// Top-level mars.toml configuration.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct Config {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub package: Option<PackageInfo>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plugin: Option<toml::Value>,
    #[serde(default)]
    pub dependencies: IndexMap<SourceName, RawEntry>,
    /// Local-only dependencies — installed when syncing this repo but NOT
    /// exported to consumers via manifest. Use for dev tooling, prompt
    /// authoring helpers, etc.
    #[serde(
        default,
        skip_serializing_if = "IndexMap::is_empty",
        rename = "local-dependencies"
    )]
    pub local_dependencies: IndexMap<SourceName, RawEntry>,
    #[serde(default)]
    pub settings: Settings,
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub models: IndexMap<String, ModelAlias>,
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub agents: IndexMap<String, AgentOverlay>,
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub skills: IndexMap<String, SkillOverlay>,
    /// A note for each key of the file this Mars did not read, set when the file is read.
    #[serde(skip)]
    pub unknown_keys: Vec<SchemaDiagnostic>,
    /// The Mars the file's tool rules need, set when the file is read.
    #[serde(skip)]
    pub floor: Option<keys::Floor>,
}

/// `approval` and `sandbox` in an overlay take the values an Agent file does, and a bad one
/// fails where it is written.
fn overlay_value<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
    key: &str,
    valid: fn(&str) -> bool,
    allowed: &str,
) -> Result<Option<String>, D::Error> {
    let value = Option::<String>::deserialize(deserializer)?;
    match value {
        Some(value) if !valid(&value) => Err(serde::de::Error::custom(format!(
            "`{key}` has invalid value `{value}`; allowed: {allowed}"
        ))),
        value => Ok(value),
    }
}

/// `effort` in an overlay takes the values an Agent file does; TOML has no null, so the
/// harness default is `auto`.
fn overlay_effort<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<crate::agent::EffortRequest>, D::Error> {
    use crate::agent::EffortRequest;
    let Some(value) = Option::<String>::deserialize(deserializer)? else {
        return Ok(None);
    };
    if let Some(request) = EffortRequest::parse(&value) {
        return Ok(Some(request));
    }
    Err(serde::de::Error::custom(format!(
        "`effort` has invalid value `{value}`; allowed: {}",
        EffortRequest::ALLOWED
    )))
}

fn overlay_approval<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<String>, D::Error> {
    use crate::agent::ApprovalMode;
    overlay_value(
        deserializer,
        "approval",
        |value| ApprovalMode::parse(value).is_some(),
        ApprovalMode::ALLOWED,
    )
}

fn overlay_sandbox<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<String>, D::Error> {
    use crate::agent::SandboxMode;
    overlay_value(
        deserializer,
        "sandbox",
        |value| SandboxMode::parse(value).is_some(),
        SandboxMode::ALLOWED,
    )
}

/// Per-agent launch-bundle overlay policy in mars.toml `[agents.<name>]`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct AgentOverlay {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub harness: Option<String>,
    #[serde(
        default,
        deserialize_with = "overlay_effort",
        skip_serializing_if = "Option::is_none"
    )]
    pub effort: Option<crate::agent::EffortRequest>,
    #[serde(
        default,
        deserialize_with = "overlay_approval",
        skip_serializing_if = "Option::is_none"
    )]
    pub approval: Option<String>,
    #[serde(
        default,
        deserialize_with = "overlay_sandbox",
        skip_serializing_if = "Option::is_none"
    )]
    pub sandbox: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub network: Option<NetworkPolicy>,
    #[serde(
        default,
        rename = "network-allow",
        alias = "network_allow",
        skip_serializing_if = "PermissionSet::is_noop"
    )]
    pub network_allow: PermissionSet<NetworkHost>,
    #[serde(
        default,
        rename = "network-deny",
        alias = "network_deny",
        skip_serializing_if = "PermissionSet::is_noop"
    )]
    pub network_deny: PermissionSet<NetworkHost>,
    #[serde(
        default,
        rename = "model-invocable",
        alias = "model_invocable",
        skip_serializing_if = "Option::is_none"
    )]
    pub model_invocable: Option<bool>,
    #[serde(
        default,
        rename = "user-invocable",
        alias = "user_invocable",
        skip_serializing_if = "Option::is_none"
    )]
    pub user_invocable: Option<bool>,
    #[serde(default, skip_serializing_if = "ToolRuleMap::is_empty")]
    pub tools: ToolRuleMap,
    #[serde(
        default,
        rename = "model-policies",
        skip_serializing_if = "Option::is_none"
    )]
    pub model_policies: Option<Vec<ModelPolicyRule>>,
}

/// Per-skill overlay policy in mars.toml `[skills.<name>]`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct SkillOverlay {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(
        default,
        rename = "model-invocable",
        alias = "model_invocable",
        skip_serializing_if = "Option::is_none"
    )]
    pub model_invocable: Option<bool>,
    #[serde(
        default,
        rename = "user-invocable",
        alias = "user_invocable",
        skip_serializing_if = "Option::is_none"
    )]
    pub user_invocable: Option<bool>,
}

impl SkillOverlay {
    pub fn is_empty(&self) -> bool {
        self.description.is_none()
            && self.model_invocable.is_none()
            && self.user_invocable.is_none()
    }
}

/// Global settings — extensible via additional fields.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct Settings {
    /// Custom managed output directory (e.g. ".claude").
    ///
    /// When unset, mars no longer creates a generic `.agents` target by default;
    /// `.mars/` is the canonical compiled store and native emission is handled
    /// by target-specific compiler paths.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub managed_root: Option<String>,
    /// Managed target directories materialized from .mars/ canonical store.
    /// When set, only listed targets are populated. When unset, `managed_root`
    /// is used for backwards compatibility; otherwise no target-sync targets
    /// are enabled by default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub targets: Option<Vec<String>>,
    /// Unset means `DEFAULT_MODELS_CACHE_TTL_HOURS`; read it through `models_cache_ttl_hours()`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub models_cache_ttl_hours: Option<u32>,
    /// Minimum mars binary version required to use this project.
    /// Old binary + new package with this set → compatibility error.
    /// New binary + old package without this set → succeeds with defaults.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_mars_version: Option<String>,
    /// Default harness for launch routing when profile/alias/provider cannot resolve one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_harness: Option<String>,
    /// Project-wide default model token when no CLI override or profile model is set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_model: Option<String>,
    /// Project-wide network mode when no higher policy layer sets one.
    #[serde(
        default,
        alias = "default-network",
        skip_serializing_if = "Option::is_none"
    )]
    pub default_network: Option<NetworkPolicy>,
    #[serde(
        default,
        rename = "network-allow",
        alias = "network_allow",
        skip_serializing_if = "PermissionSet::is_noop"
    )]
    pub network_allow: PermissionSet<NetworkHost>,
    #[serde(
        default,
        rename = "network-deny",
        alias = "network_deny",
        skip_serializing_if = "PermissionSet::is_noop"
    )]
    pub network_deny: PermissionSet<NetworkHost>,
    /// Tool rules for every agent and for a launch with no agent. Takes `allow`, `ask` and `deny`; never `*`.
    #[serde(default, skip_serializing_if = "ToolRuleMap::is_empty")]
    pub tools: ToolRuleMap,
    /// Ordered harness preference for launch-bundle candidate selection.
    ///
    /// When set, replaces built-in provider preference ordering for candidate
    /// selection. First installed candidate wins. When unset, Mars uses the
    /// built-in default (`claude`, `pi`, `codex`, `opencode`, `cursor`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub harness_order: Option<Vec<String>>,
    /// Ordered provider preference for model-first routing tie-breaks.
    ///
    /// Optional soft preference used only after model-name matching. Empty means
    /// preserve harness-reported model order.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_order: Option<Vec<String>>,
    /// models.dev provider keys ingested into the models cache.
    ///
    /// Unset uses the built-in default (`anthropic`, `openai`, `google`, `meta`,
    /// `deepseek`, `xai`, `openrouter`). Set replaces that list. `["*"]` ingests
    /// every provider. Catalog-only: a pinned alias still works if the harness
    /// can resolve the provider.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub catalog_providers: Option<Vec<String>>,
    /// Controls whether harness-bound agents are emitted to native harness dirs.
    ///
    /// `auto` (the default when unset) emits for standalone mars syncs and
    /// suppresses native agent artifacts when Meridian invokes mars with
    /// `MERIDIAN_MANAGED=1`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_emission: Option<AgentEmission>,
    #[serde(default, skip_serializing_if = "MeridianSettings::is_empty")]
    pub meridian: MeridianSettings,
    #[serde(
        default,
        rename = "model-policies",
        skip_serializing_if = "Option::is_none"
    )]
    pub model_policies: Option<Vec<ModelPolicyRule>>,
}

/// Selective native agent emission under managed mode or `agent_emission = "never"`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct AgentCopyConfig {
    #[serde(default)]
    pub harnesses: Vec<String>,
    #[serde(default)]
    pub include_fanout: bool,
}

/// Fanout agent list for native emission qualification and `mars agents` routing output.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct FanoutConfig {
    #[serde(default)]
    pub agents: Vec<String>,
}

/// Meridian-managed settings nested under `[settings.meridian]`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct MeridianSettings {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_copy: Option<AgentCopyConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fanout: Option<FanoutConfig>,
}

impl MeridianSettings {
    pub fn is_empty(&self) -> bool {
        self.agent_copy.is_none() && self.fanout.is_none()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum AgentEmission {
    Auto,
    Always,
    Never,
}

const DEFAULT_MODELS_CACHE_TTL_HOURS: u32 = 24;

impl Settings {
    pub fn models_cache_ttl_hours(&self) -> u32 {
        self.models_cache_ttl_hours
            .unwrap_or(DEFAULT_MODELS_CACHE_TTL_HOURS)
    }

    pub fn model_policies(&self) -> &[ModelPolicyRule] {
        self.model_policies.as_deref().unwrap_or_default()
    }

    /// Selective native agent copy config from `[settings.meridian.agent_copy]`.
    pub fn meridian_agent_copy(&self) -> Option<&AgentCopyConfig> {
        self.meridian.agent_copy.as_ref()
    }

    /// The network keys a project sets in `[settings]` (or inherits from the user config), each
    /// with whether it restricts: `default_network = "allow"` is a grant.
    pub fn network_keys(&self) -> Vec<(&'static str, bool)> {
        [
            (
                "default-network",
                self.default_network
                    .as_ref()
                    .map(|policy| *policy != crate::network::NetworkPolicy::Allow),
            ),
            (
                "network-allow",
                (!self.network_allow.entries().is_empty()).then_some(true),
            ),
            (
                "network-deny",
                (!self.network_deny.entries().is_empty()).then_some(true),
            ),
        ]
        .into_iter()
        .filter_map(|(key, restricts)| restricts.map(|restricts| (key, restricts)))
        .collect()
    }

    /// Fanout agent list from `[settings.meridian.fanout]`.
    pub fn meridian_fanout_agents(&self) -> &[String] {
        self.meridian
            .fanout
            .as_ref()
            .map(|f| f.agents.as_slice())
            .unwrap_or(&[])
    }
}

impl Config {
    /// One note for each key of a dependency entry that Mars did not read.
    pub fn dependency_unknown_keys(&self) -> Vec<SchemaDiagnostic> {
        [
            ("dependencies", &self.dependencies),
            ("local-dependencies", &self.local_dependencies),
        ]
        .into_iter()
        .flat_map(|(table, dependencies)| {
            dependencies.iter().flat_map(move |(name, entry)| {
                entry.unknown.keys().map(move |key| {
                    let path = vec![
                        PathSegment::Key(table.to_owned()),
                        PathSegment::Key(name.to_string()),
                        PathSegment::Key(key.clone()),
                    ];
                    unknown_field(path, &format!("{table}.{name}"), key)
                })
            })
        })
        .collect()
    }
}

/// A file read: the value, one `Info` for each key Mars did not read, and the Mars its tool
/// rules need.
pub struct Read<T> {
    pub value: T,
    pub unknown_keys: Vec<SchemaDiagnostic>,
    pub floor: Option<keys::Floor>,
}

/// Read a `mars.toml`-shaped file. `Err` is the TOML or serde error as the parser words it.
pub fn read<T: DeserializeOwned>(content: &str) -> Result<Read<T>, toml::de::Error> {
    let mut ignored = Vec::new();
    let value = serde_ignored::deserialize(toml::Deserializer::new(content), |at| {
        ignored.push(segments(&at));
    })?;
    let unknown_keys = unknown_notes(ignored, &[]);
    let floor = content
        .parse::<toml::Table>()
        .ok()
        .and_then(|table| keys::floor(keys::used(&table, keys::Document::Consumer)));
    Ok(Read {
        value,
        unknown_keys,
        floor,
    })
}

/// One `field.unknown` note for each key a serde pass left unread, `prefix` being where the
/// pass started.
fn unknown_notes(ignored: Vec<Vec<PathSegment>>, prefix: &[PathSegment]) -> Vec<SchemaDiagnostic> {
    let mut notes = Vec::new();
    for at in ignored {
        let mut at: Vec<PathSegment> = prefix.iter().cloned().chain(at).collect();
        let Some(PathSegment::Key(key)) = at.pop() else {
            continue;
        };
        // `[package]` and `[plugin]` belong to the package readers, which report their own.
        if matches!(at.first(), Some(PathSegment::Key(table)) if table == "package" || table == "plugin")
        {
            continue;
        }
        let table = table_name(&at);
        let mut path = at;
        path.push(PathSegment::Key(key.clone()));
        notes.push(unknown_field(path, &table, &key));
    }
    notes
}

/// A table of a `mars.toml` this Mars refused, and why. `path` names it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigIssue {
    pub path: Vec<PathSegment>,
    pub message: String,
}

/// A `mars.toml` read for its consumer configuration.
pub struct ConsumerRead {
    /// Every table that is valid on its own. A table the file breaks is absent (`models.a` of
    /// `models`, or the whole of `settings`); `package` and the dependency tables come from the
    /// whole-file pass only when it succeeds.
    pub config: Config,
    /// What was refused: a table that failed, `[settings.tools]` with a `*`, a
    /// `min_mars_version` that is not a requirement.
    pub issues: Vec<ConfigIssue>,
    /// The error of the whole-file pass, when it failed. Its text points at the line, and the
    /// CLI, which refuses the project's own file whole, reports it as it always has.
    pub parse_error: Option<toml::de::Error>,
}

/// Read a project's `mars.toml`: the one reading the CLI's `parse_config` and the WASM
/// `read('mars.toml')` share. The whole file is read in one serde pass; when that fails, each
/// table is read apart, so one broken value costs its own table and nothing else.
pub fn read_consumer(content: &str) -> ConsumerRead {
    match read::<Config>(content) {
        Ok(read) => {
            let mut config = read.value;
            config.unknown_keys = read.unknown_keys;
            config.unknown_keys.extend(config.dependency_unknown_keys());
            config.floor = read.floor;
            let issues = settings_refusals(
                Some(&config.settings.tools),
                config.settings.min_mars_version.as_deref(),
            );
            ConsumerRead {
                config,
                issues,
                parse_error: None,
            }
        }
        Err(error) => {
            let (config, issues) = read_tables(content, &error);
            ConsumerRead {
                config,
                issues,
                parse_error: Some(error),
            }
        }
    }
}

fn key_path(parts: &[&str]) -> Vec<PathSegment> {
    parts
        .iter()
        .map(|part| PathSegment::Key((*part).to_owned()))
        .collect()
}

/// The tables of `content` that are valid alone. `package` and `[plugin]` are the package
/// readers' and the dependency entries are only read for their unknown keys: their refusals are
/// reported where the package and its dependencies are read.
fn read_tables(content: &str, whole: &toml::de::Error) -> (Config, Vec<ConfigIssue>) {
    let mut config = Config::default();
    let Ok(table) = content.parse::<toml::Table>() else {
        let issue = ConfigIssue {
            path: Vec::new(),
            message: whole.to_string(),
        };
        return (config, vec![issue]);
    };
    let mut issues = Vec::new();
    let mut unknown = Vec::new();
    config.floor = keys::floor(keys::used(&table, keys::Document::Consumer));
    config.plugin = table.get("plugin").cloned();
    if let Some(value) = table.get("settings") {
        match read_value::<Settings>(value, key_path(&["settings"]), &mut unknown) {
            Ok(settings) => {
                issues.extend(settings_refusals(
                    Some(&settings.tools),
                    settings.min_mars_version.as_deref(),
                ));
                config.settings = settings;
            }
            Err(issue) => issues.push(issue),
        }
    }
    config.models = read_entries(&table, "models", &mut unknown, &mut issues);
    config.agents = read_entries(&table, "agents", &mut unknown, &mut issues);
    config.skills = read_entries(&table, "skills", &mut unknown, &mut issues);
    config.dependencies = read_dependency_entries(&table, "dependencies", &mut unknown);
    config.local_dependencies = read_dependency_entries(&table, "local-dependencies", &mut unknown);
    config.unknown_keys = unknown;
    config.unknown_keys.extend(config.dependency_unknown_keys());
    (config, issues)
}

fn read_value<T: DeserializeOwned>(
    value: &toml::Value,
    at: Vec<PathSegment>,
    unknown: &mut Vec<SchemaDiagnostic>,
) -> Result<T, ConfigIssue> {
    let mut ignored = Vec::new();
    match serde_ignored::deserialize(value.clone(), |path| ignored.push(segments(&path))) {
        Ok(read) => {
            unknown.extend(unknown_notes(ignored, &at));
            Ok(read)
        }
        Err(error) => Err(ConfigIssue {
            path: at,
            message: error.to_string().trim_end().to_owned(),
        }),
    }
}

/// The entries of a table of named entries (`[models.<alias>]`), each read alone.
fn read_entries<T: DeserializeOwned>(
    table: &toml::Table,
    key: &str,
    unknown: &mut Vec<SchemaDiagnostic>,
    issues: &mut Vec<ConfigIssue>,
) -> IndexMap<String, T> {
    let mut entries = IndexMap::new();
    match table.get(key) {
        None => {}
        Some(toml::Value::Table(named)) => {
            for (name, value) in named {
                match read_value(value, key_path(&[key, name]), unknown) {
                    Ok(entry) => {
                        entries.insert(name.clone(), entry);
                    }
                    Err(issue) => issues.push(issue),
                }
            }
        }
        Some(_) => issues.push(ConfigIssue {
            path: key_path(&[key]),
            message: format!("`{key}` must be a table"),
        }),
    }
    entries
}

fn read_dependency_entries(
    table: &toml::Table,
    key: &str,
    unknown: &mut Vec<SchemaDiagnostic>,
) -> IndexMap<SourceName, RawEntry> {
    let mut entries = IndexMap::new();
    let Some(toml::Value::Table(named)) = table.get(key) else {
        return entries;
    };
    for (name, value) in named {
        let Ok(source) = toml::Value::String(name.clone()).try_into::<SourceName>() else {
            continue;
        };
        if let Ok(entry) = read_value(value, key_path(&[key, name]), unknown) {
            entries.insert(source, entry);
        }
    }
    entries
}

/// Only the `[models]` table of a manifest: a dependency's other consumer tables belong to its
/// own project, not to its dependents.
pub fn read_models(content: &str) -> Result<IndexMap<String, ModelAlias>, toml::de::Error> {
    #[derive(Deserialize)]
    struct Models {
        #[serde(default)]
        models: IndexMap<String, ModelAlias>,
    }
    toml::from_str::<Models>(content).map(|parsed| parsed.models)
}

/// What a file's `[settings]` refuses. `[settings.tools]` takes no `*`: it would turn every agent
/// into an allowlist or sit ahead of every profile's `approval`, which already is the default for
/// calls no rule matches. A `min_mars_version` that is not a requirement is refused because the
/// key's job is to stop an older Mars (see [`parse_min_mars_version`]).
pub fn settings_refusals(
    tools: Option<&ToolRuleMap>,
    min_mars_version: Option<&str>,
) -> Vec<ConfigIssue> {
    let tools = tools
        .and_then(|tools| {
            tools.wildcard_refusal(
                "[settings.tools]",
                "`approval` is the default for calls no rule matches",
            )
        })
        .map(|message| ConfigIssue {
            path: key_path(&["settings", "tools"]),
            message,
        });
    let min = min_mars_version
        .and_then(|raw| parse_min_mars_version(raw).err())
        .map(|message| ConfigIssue {
            path: key_path(&["settings", "min_mars_version"]),
            message,
        });
    tools.into_iter().chain(min).collect()
}

/// A project's `min_mars_version`, read as `requires-mars` is: a bare version means that version
/// or newer, and a range is accepted. One that does not parse would let an older Mars through
/// the one key whose job is to stop it, so the file does not load.
pub fn parse_min_mars_version(raw: &str) -> Result<semver::VersionReq, String> {
    crate::package::parse_requirement(raw).map_err(|error| {
        format!("`min_mars_version = \"{raw}\"` is not a version requirement: {error}")
    })
}

fn segments(at: &IgnoredPath<'_>) -> Vec<PathSegment> {
    match at {
        IgnoredPath::Root => Vec::new(),
        IgnoredPath::Seq { parent, index } => {
            let mut out = segments(parent);
            out.push(PathSegment::Index(*index));
            out
        }
        IgnoredPath::Map { parent, key } => {
            let mut out = segments(parent);
            out.push(PathSegment::Key(key.clone()));
            out
        }
        IgnoredPath::Some { parent }
        | IgnoredPath::NewtypeStruct { parent }
        | IgnoredPath::NewtypeVariant { parent } => segments(parent),
    }
}

/// `agents.a.model-policies[0]`: the dotted table, with list positions in brackets.
fn table_name(at: &[PathSegment]) -> String {
    let mut name = String::new();
    for segment in at {
        match segment {
            PathSegment::Key(key) => {
                if !name.is_empty() {
                    name.push('.');
                }
                name.push_str(key);
            }
            PathSegment::Index(index) => name.push_str(&format!("[{index}]")),
        }
    }
    name
}