Skip to main content

mars_schema/
config.rs

1//! What `mars.toml` holds beyond `[package]` and the dependency tables: `[settings]`,
2//! `[models]`, `[agents]`, `[skills]` and `[plugin]`, read as the CLI reads them, and the reader
3//! the project's other config files share.
4//!
5//! One serde pass reads a whole file; a key it leaves unread becomes one `field.unknown` note and
6//! stays in the file. Nothing here names a key that was once read (see `retired`).
7
8use indexmap::IndexMap;
9use serde::de::DeserializeOwned;
10use serde::{Deserialize, Serialize};
11use serde_ignored::Path as IgnoredPath;
12
13use crate::alias::ModelAlias;
14use crate::dependency::RawEntry;
15use crate::diagnostic::{PathSegment, SchemaDiagnostic, unknown_field};
16use crate::keys;
17use crate::model_policy::{ModelPolicyRule, ModelsItem};
18use crate::names::SourceName;
19use crate::network::{NetworkHost, NetworkPolicy};
20use crate::package::PackageMetadata as PackageInfo;
21use crate::permission_set::PermissionSet;
22use crate::tool_rule_map::ToolRuleMap;
23
24/// Top-level mars.toml configuration.
25#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
26pub struct Config {
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    pub package: Option<PackageInfo>,
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub plugin: Option<toml::Value>,
31    #[serde(default)]
32    pub dependencies: IndexMap<SourceName, RawEntry>,
33    /// Local-only dependencies — installed when syncing this repo but NOT
34    /// exported to consumers via manifest. Use for dev tooling, prompt
35    /// authoring helpers, etc.
36    #[serde(
37        default,
38        skip_serializing_if = "IndexMap::is_empty",
39        rename = "local-dependencies"
40    )]
41    pub local_dependencies: IndexMap<SourceName, RawEntry>,
42    #[serde(default)]
43    pub settings: Settings,
44    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
45    pub models: IndexMap<String, ModelAlias>,
46    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
47    pub agents: IndexMap<String, AgentOverlay>,
48    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
49    pub skills: IndexMap<String, SkillOverlay>,
50    /// A note for each key of the file this Mars did not read, set when the file is read.
51    #[serde(skip)]
52    pub unknown_keys: Vec<SchemaDiagnostic>,
53    /// The Mars the file's tool rules need, set when the file is read.
54    #[serde(skip)]
55    pub floor: Option<keys::Floor>,
56}
57
58/// `approval` and `sandbox` in an overlay take the values an Agent file does, and a bad one
59/// fails where it is written.
60fn overlay_value<'de, D: serde::Deserializer<'de>>(
61    deserializer: D,
62    key: &str,
63    valid: fn(&str) -> bool,
64    allowed: &str,
65) -> Result<Option<String>, D::Error> {
66    let value = Option::<String>::deserialize(deserializer)?;
67    match value {
68        Some(value) if !valid(&value) => Err(serde::de::Error::custom(format!(
69            "`{key}` has invalid value `{value}`; allowed: {allowed}"
70        ))),
71        value => Ok(value),
72    }
73}
74
75/// `effort` in an overlay takes the values an Agent file does; TOML has no null, so the
76/// harness default is `auto`.
77fn overlay_effort<'de, D: serde::Deserializer<'de>>(
78    deserializer: D,
79) -> Result<Option<crate::agent::EffortRequest>, D::Error> {
80    use crate::agent::EffortRequest;
81    let Some(value) = Option::<String>::deserialize(deserializer)? else {
82        return Ok(None);
83    };
84    if let Some(request) = EffortRequest::parse(&value) {
85        return Ok(Some(request));
86    }
87    Err(serde::de::Error::custom(format!(
88        "`effort` has invalid value `{value}`; allowed: {}",
89        EffortRequest::ALLOWED
90    )))
91}
92
93fn overlay_approval<'de, D: serde::Deserializer<'de>>(
94    deserializer: D,
95) -> Result<Option<String>, D::Error> {
96    use crate::agent::ApprovalMode;
97    overlay_value(
98        deserializer,
99        "approval",
100        |value| ApprovalMode::parse(value).is_some(),
101        ApprovalMode::ALLOWED,
102    )
103}
104
105fn overlay_sandbox<'de, D: serde::Deserializer<'de>>(
106    deserializer: D,
107) -> Result<Option<String>, D::Error> {
108    use crate::agent::SandboxMode;
109    overlay_value(
110        deserializer,
111        "sandbox",
112        |value| SandboxMode::parse(value).is_some(),
113        SandboxMode::ALLOWED,
114    )
115}
116
117/// Per-agent launch-bundle overlay policy in mars.toml `[agents.<name>]`.
118#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
119pub struct AgentOverlay {
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub description: Option<String>,
122    /// Replaces the list's default (its first entry) and keeps the rest; applies before `models`.
123    /// Beside `models` in one table it applies first, then `models` edits the list.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub model: Option<String>,
126    /// The agent's ordered list of models for this layer: entries, and [`ModelsItem::Rest`] for
127    /// the list the layer below produced. Without `Rest` it replaces that list.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub models: Option<Vec<ModelsItem>>,
130    #[serde(default, skip_serializing_if = "Option::is_none")]
131    pub harness: Option<String>,
132    #[serde(
133        default,
134        deserialize_with = "overlay_effort",
135        skip_serializing_if = "Option::is_none"
136    )]
137    pub effort: Option<crate::agent::EffortRequest>,
138    #[serde(
139        default,
140        deserialize_with = "overlay_approval",
141        skip_serializing_if = "Option::is_none"
142    )]
143    pub approval: Option<String>,
144    #[serde(
145        default,
146        deserialize_with = "overlay_sandbox",
147        skip_serializing_if = "Option::is_none"
148    )]
149    pub sandbox: Option<String>,
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub network: Option<NetworkPolicy>,
152    #[serde(
153        default,
154        rename = "network-allow",
155        alias = "network_allow",
156        skip_serializing_if = "PermissionSet::is_noop"
157    )]
158    pub network_allow: PermissionSet<NetworkHost>,
159    #[serde(
160        default,
161        rename = "network-deny",
162        alias = "network_deny",
163        skip_serializing_if = "PermissionSet::is_noop"
164    )]
165    pub network_deny: PermissionSet<NetworkHost>,
166    #[serde(
167        default,
168        rename = "model-invocable",
169        alias = "model_invocable",
170        skip_serializing_if = "Option::is_none"
171    )]
172    pub model_invocable: Option<bool>,
173    #[serde(
174        default,
175        rename = "user-invocable",
176        alias = "user_invocable",
177        skip_serializing_if = "Option::is_none"
178    )]
179    pub user_invocable: Option<bool>,
180    #[serde(default, skip_serializing_if = "ToolRuleMap::is_empty")]
181    pub tools: ToolRuleMap,
182    #[serde(
183        default,
184        rename = "model-policies",
185        skip_serializing_if = "Option::is_none"
186    )]
187    pub model_policies: Option<Vec<ModelPolicyRule>>,
188}
189
190/// Per-skill overlay policy in mars.toml `[skills.<name>]`.
191#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
192pub struct SkillOverlay {
193    #[serde(default, skip_serializing_if = "Option::is_none")]
194    pub description: Option<String>,
195    #[serde(
196        default,
197        rename = "model-invocable",
198        alias = "model_invocable",
199        skip_serializing_if = "Option::is_none"
200    )]
201    pub model_invocable: Option<bool>,
202    #[serde(
203        default,
204        rename = "user-invocable",
205        alias = "user_invocable",
206        skip_serializing_if = "Option::is_none"
207    )]
208    pub user_invocable: Option<bool>,
209}
210
211impl SkillOverlay {
212    pub fn is_empty(&self) -> bool {
213        self.description.is_none()
214            && self.model_invocable.is_none()
215            && self.user_invocable.is_none()
216    }
217}
218
219/// Global settings — extensible via additional fields.
220#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
221pub struct Settings {
222    /// The v0.36 spelling of one target. Retired: nothing reads it as a target. It is a field only
223    /// so a warning can name the `targets` to write instead (`retired::managed_root_note`).
224    #[serde(default, skip_serializing_if = "Option::is_none")]
225    pub managed_root: Option<String>,
226    /// Managed target directories materialized from .mars/ canonical store.
227    /// When set, only listed targets are populated. When unset, no target-sync
228    /// targets are enabled by default.
229    #[serde(default, skip_serializing_if = "Option::is_none")]
230    pub targets: Option<Vec<String>>,
231    /// Unset means `DEFAULT_MODELS_CACHE_TTL_HOURS`; read it through `models_cache_ttl_hours()`.
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub models_cache_ttl_hours: Option<u32>,
234    /// Minimum mars binary version required to use this project.
235    /// Old binary + new package with this set → compatibility error.
236    /// New binary + old package without this set → succeeds with defaults.
237    #[serde(default, skip_serializing_if = "Option::is_none")]
238    pub min_mars_version: Option<String>,
239    /// Default harness for launch routing when profile/alias/provider cannot resolve one.
240    #[serde(default, skip_serializing_if = "Option::is_none")]
241    pub default_harness: Option<String>,
242    /// Project-wide default model token when no CLI override or profile model is set.
243    #[serde(default, skip_serializing_if = "Option::is_none")]
244    pub default_model: Option<String>,
245    /// Project-wide network mode when no higher policy layer sets one.
246    #[serde(
247        default,
248        alias = "default-network",
249        skip_serializing_if = "Option::is_none"
250    )]
251    pub default_network: Option<NetworkPolicy>,
252    #[serde(
253        default,
254        rename = "network-allow",
255        alias = "network_allow",
256        skip_serializing_if = "PermissionSet::is_noop"
257    )]
258    pub network_allow: PermissionSet<NetworkHost>,
259    #[serde(
260        default,
261        rename = "network-deny",
262        alias = "network_deny",
263        skip_serializing_if = "PermissionSet::is_noop"
264    )]
265    pub network_deny: PermissionSet<NetworkHost>,
266    /// Tool rules for every agent and for a launch with no agent. Takes `allow`, `ask` and `deny`; never `*`.
267    #[serde(default, skip_serializing_if = "ToolRuleMap::is_empty")]
268    pub tools: ToolRuleMap,
269    /// Ordered harness preference for launch-bundle candidate selection.
270    ///
271    /// When set, replaces built-in provider preference ordering for candidate
272    /// selection. First installed candidate wins. When unset, Mars uses the
273    /// built-in default (`claude`, `pi`, `codex`, `opencode`).
274    #[serde(default, skip_serializing_if = "Option::is_none")]
275    pub harness_order: Option<Vec<String>>,
276    /// Ordered provider preference for model-first routing tie-breaks.
277    ///
278    /// Optional soft preference used only after model-name matching. Empty means
279    /// preserve harness-reported model order.
280    #[serde(default, skip_serializing_if = "Option::is_none")]
281    pub provider_order: Option<Vec<String>>,
282    /// models.dev provider keys ingested into the models cache.
283    ///
284    /// Unset uses the built-in default (`anthropic`, `openai`, `google`, `meta`,
285    /// `deepseek`, `xai`, `openrouter`). Set replaces that list. `["*"]` ingests
286    /// every provider. Catalog-only: a pinned alias still works if the harness
287    /// can resolve the provider.
288    #[serde(default, skip_serializing_if = "Option::is_none")]
289    pub catalog_providers: Option<Vec<String>>,
290    /// Controls whether harness-bound agents are emitted to native harness dirs.
291    ///
292    /// `auto` (the default when unset) emits for standalone mars syncs and
293    /// suppresses native agent artifacts when Meridian invokes mars with
294    /// `MERIDIAN_MANAGED=1`.
295    #[serde(default, skip_serializing_if = "Option::is_none")]
296    pub agent_emission: Option<AgentEmission>,
297    #[serde(default, skip_serializing_if = "MeridianSettings::is_empty")]
298    pub meridian: MeridianSettings,
299    #[serde(
300        default,
301        rename = "model-policies",
302        skip_serializing_if = "Option::is_none"
303    )]
304    pub model_policies: Option<Vec<ModelPolicyRule>>,
305}
306
307/// Selective native agent emission under managed mode or `agent_emission = "never"`.
308#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
309pub struct AgentCopyConfig {
310    #[serde(default)]
311    pub harnesses: Vec<String>,
312    /// Deprecated, read and ignored: a fan-out agent never gets a native copy.
313    #[serde(default, skip_serializing_if = "Option::is_none")]
314    pub include_fanout: Option<bool>,
315}
316
317/// Agents launched by `meridian spawn` only: no native copy, and `mars agents` marks them.
318#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
319pub struct FanoutConfig {
320    #[serde(default)]
321    pub agents: Vec<String>,
322}
323
324/// Meridian-managed settings nested under `[settings.meridian]`.
325#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
326pub struct MeridianSettings {
327    #[serde(default, skip_serializing_if = "Option::is_none")]
328    pub agent_copy: Option<AgentCopyConfig>,
329    #[serde(default, skip_serializing_if = "Option::is_none")]
330    pub fanout: Option<FanoutConfig>,
331}
332
333impl MeridianSettings {
334    pub fn is_empty(&self) -> bool {
335        self.agent_copy.is_none() && self.fanout.is_none()
336    }
337}
338
339#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
340#[serde(rename_all = "lowercase")]
341pub enum AgentEmission {
342    Auto,
343    Always,
344    Never,
345}
346
347const DEFAULT_MODELS_CACHE_TTL_HOURS: u32 = 24;
348
349impl Settings {
350    pub fn models_cache_ttl_hours(&self) -> u32 {
351        self.models_cache_ttl_hours
352            .unwrap_or(DEFAULT_MODELS_CACHE_TTL_HOURS)
353    }
354
355    pub fn model_policies(&self) -> &[ModelPolicyRule] {
356        self.model_policies.as_deref().unwrap_or_default()
357    }
358
359    /// Selective native agent copy config from `[settings.meridian.agent_copy]`.
360    pub fn meridian_agent_copy(&self) -> Option<&AgentCopyConfig> {
361        self.meridian.agent_copy.as_ref()
362    }
363
364    /// The network keys a project sets in `[settings]` (or inherits from the user config), each
365    /// with whether it restricts: `default_network = "allow"` is a grant.
366    pub fn network_keys(&self) -> Vec<(&'static str, bool)> {
367        [
368            (
369                "default-network",
370                self.default_network
371                    .as_ref()
372                    .map(|policy| *policy != crate::network::NetworkPolicy::Allow),
373            ),
374            (
375                "network-allow",
376                (!self.network_allow.entries().is_empty()).then_some(true),
377            ),
378            (
379                "network-deny",
380                (!self.network_deny.entries().is_empty()).then_some(true),
381            ),
382        ]
383        .into_iter()
384        .filter_map(|(key, restricts)| restricts.map(|restricts| (key, restricts)))
385        .collect()
386    }
387
388    /// Fanout agent list from `[settings.meridian.fanout]`.
389    pub fn meridian_fanout_agents(&self) -> &[String] {
390        self.meridian
391            .fanout
392            .as_ref()
393            .map(|f| f.agents.as_slice())
394            .unwrap_or(&[])
395    }
396}
397
398impl Config {
399    /// One note for each key of a dependency entry that Mars did not read.
400    pub fn dependency_unknown_keys(&self) -> Vec<SchemaDiagnostic> {
401        [
402            ("dependencies", &self.dependencies),
403            ("local-dependencies", &self.local_dependencies),
404        ]
405        .into_iter()
406        .flat_map(|(table, dependencies)| {
407            dependencies.iter().flat_map(move |(name, entry)| {
408                entry.unknown.keys().map(move |key| {
409                    let path = vec![
410                        PathSegment::Key(table.to_owned()),
411                        PathSegment::Key(name.to_string()),
412                        PathSegment::Key(key.clone()),
413                    ];
414                    unknown_field(path, &format!("{table}.{name}"), key)
415                })
416            })
417        })
418        .collect()
419    }
420}
421
422/// A file read: the value, one `Info` for each key Mars did not read, and the Mars its tool
423/// rules need.
424pub struct Read<T> {
425    pub value: T,
426    pub unknown_keys: Vec<SchemaDiagnostic>,
427    pub floor: Option<keys::Floor>,
428}
429
430/// Read a `mars.toml`-shaped file. `Err` is the TOML or serde error as the parser words it.
431pub fn read<T: DeserializeOwned>(
432    content: &str,
433    document: keys::Document,
434) -> Result<Read<T>, toml::de::Error> {
435    let mut ignored = Vec::new();
436    let value = serde_ignored::deserialize(toml::Deserializer::new(content), |at| {
437        ignored.push(segments(&at));
438    })?;
439    let mut unknown_keys = unknown_notes(ignored, &[]);
440    let table = content.parse::<toml::Table>().ok();
441    unknown_keys.extend(table.iter().flat_map(crate::retired::config_notes));
442    let floor = table.and_then(|table| keys::floor(keys::used(&table, document)));
443    Ok(Read {
444        value,
445        unknown_keys,
446        floor,
447    })
448}
449
450/// One `field.unknown` note for each key a serde pass left unread, `prefix` being where the
451/// pass started.
452fn unknown_notes(ignored: Vec<Vec<PathSegment>>, prefix: &[PathSegment]) -> Vec<SchemaDiagnostic> {
453    let mut notes = Vec::new();
454    for at in ignored {
455        let mut at: Vec<PathSegment> = prefix.iter().cloned().chain(at).collect();
456        let Some(PathSegment::Key(key)) = at.pop() else {
457            continue;
458        };
459        // `[package]` and `[plugin]` belong to the package readers, which report their own.
460        if matches!(at.first(), Some(PathSegment::Key(table)) if table == "package" || table == "plugin")
461        {
462            continue;
463        }
464        let table = table_name(&at);
465        let mut path = at;
466        path.push(PathSegment::Key(key.clone()));
467        notes.push(unknown_field(path, &table, &key));
468    }
469    notes
470}
471
472/// A table of a `mars.toml` this Mars refused, and why. `path` names it.
473#[derive(Debug, Clone, PartialEq, Eq)]
474pub struct ConfigIssue {
475    pub path: Vec<PathSegment>,
476    pub message: String,
477}
478
479/// A `mars.toml` read for its consumer configuration.
480pub struct ConsumerRead {
481    /// Every table that is valid on its own. A table the file breaks is absent (`models.a` of
482    /// `models`, or the whole of `settings`); `package` and the dependency tables come from the
483    /// whole-file pass only when it succeeds.
484    pub config: Config,
485    /// What was refused: a table that failed, `[settings.tools]` with a `*`, a
486    /// `min_mars_version` that is not a requirement.
487    pub issues: Vec<ConfigIssue>,
488    /// The error of the whole-file pass, when it failed. Its text points at the line, and the
489    /// CLI, which refuses the project's own file whole, reports it as it always has.
490    pub parse_error: Option<toml::de::Error>,
491}
492
493/// Read a project's `mars.toml`: the one reading the CLI's `parse_config` and the WASM
494/// `read('mars.toml')` share. The whole file is read in one serde pass; when that fails, each
495/// table is read apart, so one broken value costs its own table and nothing else.
496pub fn read_consumer(content: &str) -> ConsumerRead {
497    match read::<Config>(content, keys::Document::Consumer) {
498        Ok(read) => {
499            let mut config = read.value;
500            config.unknown_keys = read.unknown_keys;
501            config.unknown_keys.extend(config.dependency_unknown_keys());
502            config.floor = read.floor;
503            let mut issues = settings_refusals(
504                Some(&config.settings.tools),
505                config.settings.min_mars_version.as_deref(),
506            );
507            issues.extend(agent_overlay_refusals(&config.agents));
508            ConsumerRead {
509                config,
510                issues,
511                parse_error: None,
512            }
513        }
514        Err(error) => {
515            let (config, issues) = read_tables(content, &error);
516            ConsumerRead {
517                config,
518                issues,
519                parse_error: Some(error),
520            }
521        }
522    }
523}
524
525fn key_path(parts: &[&str]) -> Vec<PathSegment> {
526    parts
527        .iter()
528        .map(|part| PathSegment::Key((*part).to_owned()))
529        .collect()
530}
531
532/// The tables of `content` that are valid alone. `package` and `[plugin]` are the package
533/// readers' and the dependency entries are only read for their unknown keys: their refusals are
534/// reported where the package and its dependencies are read.
535fn read_tables(content: &str, whole: &toml::de::Error) -> (Config, Vec<ConfigIssue>) {
536    let mut config = Config::default();
537    let Ok(table) = content.parse::<toml::Table>() else {
538        let issue = ConfigIssue {
539            path: Vec::new(),
540            message: whole.to_string(),
541        };
542        return (config, vec![issue]);
543    };
544    let mut issues = Vec::new();
545    let mut unknown = Vec::new();
546    config.floor = keys::floor(keys::used(&table, keys::Document::Consumer));
547    config.plugin = table.get("plugin").cloned();
548    unknown.extend(crate::retired::config_notes(&table));
549    if let Some(value) = table.get("settings") {
550        match read_value::<Settings>(value, key_path(&["settings"]), &mut unknown) {
551            Ok(settings) => {
552                issues.extend(settings_refusals(
553                    Some(&settings.tools),
554                    settings.min_mars_version.as_deref(),
555                ));
556                config.settings = settings;
557            }
558            Err(issue) => issues.push(issue),
559        }
560    }
561    config.models = read_entries(&table, "models", &mut unknown, &mut issues);
562    config.agents = read_entries(&table, "agents", &mut unknown, &mut issues);
563    issues.extend(agent_overlay_refusals(&config.agents));
564    config.skills = read_entries(&table, "skills", &mut unknown, &mut issues);
565    config.dependencies = read_dependency_entries(&table, "dependencies", &mut unknown);
566    config.local_dependencies = read_dependency_entries(&table, "local-dependencies", &mut unknown);
567    config.unknown_keys = unknown;
568    config.unknown_keys.extend(config.dependency_unknown_keys());
569    (config, issues)
570}
571
572fn read_value<T: DeserializeOwned>(
573    value: &toml::Value,
574    at: Vec<PathSegment>,
575    unknown: &mut Vec<SchemaDiagnostic>,
576) -> Result<T, ConfigIssue> {
577    let mut ignored = Vec::new();
578    match serde_ignored::deserialize(value.clone(), |path| ignored.push(segments(&path))) {
579        Ok(read) => {
580            unknown.extend(unknown_notes(ignored, &at));
581            Ok(read)
582        }
583        Err(error) => Err(ConfigIssue {
584            path: at,
585            message: error.to_string().trim_end().to_owned(),
586        }),
587    }
588}
589
590/// The entries of a table of named entries (`[models.<alias>]`), each read alone.
591fn read_entries<T: DeserializeOwned>(
592    table: &toml::Table,
593    key: &str,
594    unknown: &mut Vec<SchemaDiagnostic>,
595    issues: &mut Vec<ConfigIssue>,
596) -> IndexMap<String, T> {
597    let mut entries = IndexMap::new();
598    match table.get(key) {
599        None => {}
600        Some(toml::Value::Table(named)) => {
601            for (name, value) in named {
602                match read_value(value, key_path(&[key, name]), unknown) {
603                    Ok(entry) => {
604                        entries.insert(name.clone(), entry);
605                    }
606                    Err(issue) => issues.push(issue),
607                }
608            }
609        }
610        Some(_) => issues.push(ConfigIssue {
611            path: key_path(&[key]),
612            message: format!("`{key}` must be a table"),
613        }),
614    }
615    entries
616}
617
618fn read_dependency_entries(
619    table: &toml::Table,
620    key: &str,
621    unknown: &mut Vec<SchemaDiagnostic>,
622) -> IndexMap<SourceName, RawEntry> {
623    let mut entries = IndexMap::new();
624    let Some(toml::Value::Table(named)) = table.get(key) else {
625        return entries;
626    };
627    for (name, value) in named {
628        let Ok(source) = toml::Value::String(name.clone()).try_into::<SourceName>() else {
629            continue;
630        };
631        if let Ok(entry) = read_value(value, key_path(&[key, name]), unknown) {
632            entries.insert(source, entry);
633        }
634    }
635    entries
636}
637
638/// Only the `[models]` table of a manifest: a dependency's other consumer tables belong to its
639/// own project, not to its dependents.
640pub fn read_models(content: &str) -> Result<IndexMap<String, ModelAlias>, toml::de::Error> {
641    #[derive(Deserialize)]
642    struct Models {
643        #[serde(default)]
644        models: IndexMap<String, ModelAlias>,
645    }
646    toml::from_str::<Models>(content).map(|parsed| parsed.models)
647}
648
649/// What an overlay's `models` line refuses: what a profile's list refuses
650/// ([`crate::model_policy::list_problems`]).
651pub fn agent_overlay_refusals(agents: &IndexMap<String, AgentOverlay>) -> Vec<ConfigIssue> {
652    agents
653        .iter()
654        .flat_map(|(name, overlay)| {
655            let problems = overlay.models.as_ref().map_or_else(Vec::new, |items| {
656                crate::model_policy::list_problems(items.iter().map(ModelsItem::entry))
657            });
658            problems.into_iter().map(move |problem| ConfigIssue {
659                path: key_path(&["agents", name, "models"]),
660                message: format!("[agents.{name}] {}", problem.message),
661            })
662        })
663        .collect()
664}
665
666/// What a file's `[settings]` refuses. `[settings.tools]` takes no `*`: it would turn every agent
667/// into an allowlist or sit ahead of every profile's `approval`, which already is the default for
668/// calls no rule matches. A `min_mars_version` that is not a requirement is refused because the
669/// key's job is to stop an older Mars (see [`parse_min_mars_version`]).
670pub fn settings_refusals(
671    tools: Option<&ToolRuleMap>,
672    min_mars_version: Option<&str>,
673) -> Vec<ConfigIssue> {
674    let tools = tools
675        .and_then(|tools| {
676            tools.wildcard_refusal(
677                "[settings.tools]",
678                "`approval` is the default for calls no rule matches",
679            )
680        })
681        .map(|message| ConfigIssue {
682            path: key_path(&["settings", "tools"]),
683            message,
684        });
685    let min = min_mars_version
686        .and_then(|raw| parse_min_mars_version(raw).err())
687        .map(|message| ConfigIssue {
688            path: key_path(&["settings", "min_mars_version"]),
689            message,
690        });
691    tools.into_iter().chain(min).collect()
692}
693
694/// A project's `min_mars_version`, read as `requires-mars` is: a bare version means that version
695/// or newer, and a range is accepted. One that does not parse would let an older Mars through
696/// the one key whose job is to stop it, so the file does not load.
697pub fn parse_min_mars_version(raw: &str) -> Result<semver::VersionReq, String> {
698    crate::package::parse_requirement(raw).map_err(|error| {
699        format!("`min_mars_version = \"{raw}\"` is not a version requirement: {error}")
700    })
701}
702
703fn segments(at: &IgnoredPath<'_>) -> Vec<PathSegment> {
704    match at {
705        IgnoredPath::Root => Vec::new(),
706        IgnoredPath::Seq { parent, index } => {
707            let mut out = segments(parent);
708            out.push(PathSegment::Index(*index));
709            out
710        }
711        IgnoredPath::Map { parent, key } => {
712            let mut out = segments(parent);
713            out.push(PathSegment::Key(key.clone()));
714            out
715        }
716        IgnoredPath::Some { parent }
717        | IgnoredPath::NewtypeStruct { parent }
718        | IgnoredPath::NewtypeVariant { parent } => segments(parent),
719    }
720}
721
722/// `agents.a.model-policies[0]`: the dotted table, with list positions in brackets.
723fn table_name(at: &[PathSegment]) -> String {
724    let mut name = String::new();
725    for segment in at {
726        match segment {
727            PathSegment::Key(key) => {
728                if !name.is_empty() {
729                    name.push('.');
730                }
731                name.push_str(key);
732            }
733            PathSegment::Index(index) => name.push_str(&format!("[{index}]")),
734        }
735    }
736    name
737}