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