mars-schema 0.41.3

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
//! The class guard for translated definitions. After a foreign definition is translated, whatever the
//! strict v1 reader would still reject is set aside, so a package its
//! consumer cannot edit never fails for it. Only an authored schema-v1 file is refused for its
//! fields.
//!
//! - A key Mars lowers itself (`LoweredField`, `skill::LOWERED_KEYS`) is never moved: native lowering would keep Mars's
//!   value and drop the override. A mapping or list loses only its rejected entries; a scalar, or
//!   a container the reader rejects as a whole, is dropped.
//! - A host set (`network-allow`, `network-deny`) loses only its rejected entries too, though
//!   Mars does not lower it: moving the whole list under `harness-overrides` would drop its valid
//!   hosts, and a lost deny host widens the agent.
//! - Any other rejected key is moved under `harness-overrides.<harness>` when a harness could
//!   read it, and dropped when none could.
//! - Losing a restriction (a `deny` or `ask` tool entry, `permission`, `sandbox`, `approval`,
//!   `network`, `network-deny`) is
//!   one of the changes like any other, with its own code ([`RESTRICTION_LOST`]) that names the
//!   agent. It is marked `lost`, and a sync reports it with the install that wrote the file
//!   (`Prepared::lost_restrictions`).
//! - A top-level `effort`, `mode` or `harness` that is not a string restricts nothing, so it is an
//!   ordinary change ([`EXECUTION_IGNORED`]) that is listed once; `mars check` also prints it
//!   (`Prepared::ignored_execution_fields`). A non-string `sandbox`,
//!   `approval` or `network` stays a lost restriction, with the allowed values added.

use std::cmp::Ordering;

use serde_yaml::Value;

use crate::HarnessId;
use crate::agent::LoweredField;
use crate::diagnostic::{PathSegment, SchemaDiagnostic, Severity};
use crate::frontmatter::Frontmatter;
use crate::harness_overrides::{Moved, move_keys_under};
use crate::item::DefinitionKind;
use crate::skill;

/// Keys whose errors cannot be cured by moving them: the file's identity, and the block moves go
/// to.
const KEPT_KEYS: &[&str] = &["name", "description", "harness-overrides"];

/// The code of the change that records a lost restriction.
pub(crate) const RESTRICTION_LOST: &str = "field.restriction-lost";

/// The code of the change that records an execution field that restricts nothing (`effort`,
/// `harness`, `mode`) written as something other than a string and ignored for it.
pub(crate) const EXECUTION_IGNORED: &str = "field.execution-ignored";

/// Execution fields (in a profile, or in a model policy's `override`) and what each accepts.
fn execution_allowed(key: &str) -> Option<String> {
    use crate::agent::{ApprovalMode, EffortRequest, SandboxMode};
    use crate::network::NetworkPolicy;
    Some(
        match key {
            "harness" => return Some(crate::harness::names()),
            "mode" => "primary, subagent",
            "effort" => EffortRequest::ALLOWED,
            "approval" => ApprovalMode::ALLOWED,
            "sandbox" => SandboxMode::ALLOWED,
            "network" => NetworkPolicy::ALLOWED,
            _ => return None,
        }
        .to_owned(),
    )
}

/// Keys that restrict what an agent may do; losing one widens the agent.
const RESTRICTION_KEYS: &[&str] = &[
    "permission",
    "sandbox",
    "approval",
    "network",
    "network-deny",
    "tools",
    "disallowed-tools",
];

/// Lists whose valid entries stay in place when one entry is rejected.
const HOST_SET_KEYS: &[&str] = &["network-allow", "network-deny"];

/// Where a rejected key goes.
#[derive(Clone, Copy)]
pub(crate) enum Destination<'a> {
    /// Under `harness-overrides.<name>`.
    Overrides(&'a str),
    /// Nowhere: the source has no harness whose keys these are.
    Nowhere,
}

impl Destination<'_> {
    /// The destination for a foreign dialect's keys: the harness that reads that dialect.
    pub(crate) fn for_dialect(dialect: crate::dialect::Dialect) -> Destination<'static> {
        use crate::dialect::Dialect;
        match dialect {
            Dialect::Claude => Destination::Overrides(HarnessId::Claude.as_str()),
            Dialect::Codex => Destination::Overrides(HarnessId::Codex.as_str()),
            Dialect::OpenCode => Destination::Overrides(HarnessId::OpenCode.as_str()),
            Dialect::AgentSkills | Dialect::Cursor | Dialect::MarsNative => Destination::Nowhere,
        }
    }
}

/// What the strict reader refused: the path (its first segment is the key) and what it said.
struct Rejection {
    path: Vec<PathSegment>,
    why: String,
}

/// The keys of `fm` the strict reader rejects with an error, in file order, each with its
/// rejections.
fn rejected_keys(kind: DefinitionKind, fm: &Frontmatter) -> Vec<(String, Vec<Rejection>)> {
    let errors = crate::read::field_diagnostics(kind, fm)
        .into_iter()
        .filter(|diagnostic| {
            diagnostic.is_error()
                && diagnostic.code != "field.required"
                && !diagnostic.code.starts_with("yaml.")
        })
        .filter(|diagnostic| matches!(diagnostic.path.first(), Some(PathSegment::Key(_))))
        .collect::<Vec<_>>();
    fm.keys()
        .into_iter()
        .filter(|key| !KEPT_KEYS.contains(&key.as_str()))
        .filter_map(|key| {
            let own = errors
                .iter()
                .filter(|diagnostic| matches!(diagnostic.path.first(), Some(PathSegment::Key(first)) if *first == key))
                .map(|diagnostic| Rejection {
                    path: diagnostic.path.clone(),
                    why: diagnostic.message.clone(),
                })
                .collect::<Vec<_>>();
            (!own.is_empty()).then_some((key, own))
        })
        .collect()
}

fn path_text(path: &[PathSegment]) -> String {
    path.iter()
        .map(|segment| match segment {
            PathSegment::Key(key) => key.clone(),
            PathSegment::Index(index) => index.to_string(),
        })
        .collect::<Vec<_>>()
        .join(".")
}

fn compare_paths(a: &[PathSegment], b: &[PathSegment]) -> Ordering {
    for (left, right) in a.iter().zip(b) {
        let order = match (left, right) {
            (PathSegment::Key(left), PathSegment::Key(right)) => left.cmp(right),
            (PathSegment::Index(left), PathSegment::Index(right)) => left.cmp(right),
            (PathSegment::Key(_), PathSegment::Index(_)) => Ordering::Less,
            (PathSegment::Index(_), PathSegment::Key(_)) => Ordering::Greater,
        };
        if order != Ordering::Equal {
            return order;
        }
    }
    a.len().cmp(&b.len())
}

/// Remove the entry at `path` below `value`, and return it.
fn remove_at(value: &mut Value, path: &[PathSegment]) -> Option<Value> {
    match path {
        [] => None,
        [last] => match (value, last) {
            (Value::Mapping(mapping), PathSegment::Key(key)) => mapping.remove(key.as_str()),
            (Value::Sequence(sequence), PathSegment::Index(index)) if *index < sequence.len() => {
                Some(sequence.remove(*index))
            }
            _ => None,
        },
        [first, rest @ ..] => {
            let child = match (value, first) {
                (Value::Mapping(mapping), PathSegment::Key(key)) => mapping.get_mut(key.as_str()),
                (Value::Sequence(sequence), PathSegment::Index(index)) => sequence.get_mut(*index),
                _ => None,
            }?;
            remove_at(child, rest)
        }
    }
}

/// Drop the rejected entries of the mapping or list at `fm[key]` and keep the rest. Returns the
/// entries removed with their values, or `None` when `key` holds neither or an entry cannot be
/// found; `fm` is untouched then. A container left empty goes too.
fn drop_entries(
    fm: &mut Frontmatter,
    key: &str,
    rejections: &[Rejection],
) -> Option<Vec<(Vec<PathSegment>, Value)>> {
    let mut value = fm.get(key)?.clone();
    if !matches!(value, Value::Mapping(_) | Value::Sequence(_)) {
        return None;
    }
    let mut paths = rejections
        .iter()
        .map(|rejection| rejection.path.clone())
        .collect::<Vec<_>>();
    // Deepest and highest-index first, so a removal never moves an entry still to come.
    paths.sort_by(|a, b| compare_paths(b, a));
    paths.dedup();
    let mut removed = Vec::new();
    for path in paths {
        if path.len() < 2 {
            return None;
        }
        let entry = remove_at(&mut value, &path[1..])?;
        removed.push((path, entry));
    }
    let emptied = match &value {
        Value::Mapping(mapping) => mapping.is_empty(),
        Value::Sequence(sequence) => sequence.is_empty(),
        _ => false,
    };
    if emptied {
        fm.remove(key);
    } else {
        fm.insert(key, value);
    }
    Some(removed)
}

/// The key of a model policy override named by `path` (`model-policies.<n>.override.<key>`).
fn policy_override_key(path: &[PathSegment]) -> Option<&str> {
    match path {
        [
            PathSegment::Key(policies),
            PathSegment::Index(_),
            PathSegment::Key(overrides),
            PathSegment::Key(key),
        ] if policies == "model-policies" && overrides == "override" => Some(key),
        _ => None,
    }
}

/// What was lost, when a restriction was: a `deny` or `ask` tool entry (or a tool-flag `false`),
/// an entry of `disallowed-tools`, a `network-deny` host, or a whole restriction key.
fn restriction_lost(path: &[PathSegment], removed: &Value) -> Option<String> {
    if let Some(key) = policy_override_key(path) {
        return matches!(key, "sandbox" | "approval" | "network")
            .then(|| format!("`{}`", path_text(path)));
    }
    let Some(PathSegment::Key(key)) = path.first() else {
        return None;
    };
    if path.len() == 1 {
        return RESTRICTION_KEYS
            .contains(&key.as_str())
            .then(|| format!("`{key}`"));
    }
    let restricting = match key.as_str() {
        "tools" => {
            matches!(removed.as_str(), Some("deny" | "ask")) || *removed == Value::Bool(false)
        }
        "disallowed-tools" | "network-deny" => true,
        _ => false,
    };
    let value = match removed {
        Value::String(text) => text.clone(),
        other => crate::ordered::plain(other),
    };
    restricting.then(|| match key.as_str() {
        "tools" => format!("`{}: {value}`", path_text(path)),
        "network-deny" => format!("`network-deny: {value}`"),
        _ => format!("`{}`", path_text(path)),
    })
}

/// The reader's reason, except for a `permission` map: the reader's advice is about Flow's scalar
/// `permission`, and a map is OpenCode's format.
fn reason(key: &str, value: Option<&Value>, destination: Destination<'_>, read: &str) -> String {
    if key != "permission" || !matches!(value, Some(Value::Mapping(_))) {
        return read.to_owned();
    }
    match destination {
        Destination::Overrides(_) => "`permission` as a map is OpenCode's format; declare \
             `dialect = \"open-code\"` on this dependency so Mars reads it"
            .to_owned(),
        Destination::Nowhere => "`permission` as a map is OpenCode's format; put it under \
             `harness-overrides.opencode.permission`"
            .to_owned(),
    }
}

/// Reports what the guard did: a change per piece set aside, coded [`RESTRICTION_LOST`] when it
/// was a restriction and [`EXECUTION_IGNORED`] for a non-string `effort`, `mode` or `harness`.
struct Report<'a> {
    agent: String,
    changes: &'a mut Vec<SchemaDiagnostic>,
}

impl Report<'_> {
    /// `lost` is what a restriction-losing set-aside took away, if it did; `what` says what
    /// happened to the rejected piece, `why` is the reader's reason.
    fn note(
        &mut self,
        path: &[PathSegment],
        value: &Value,
        lost: Option<String>,
        what: &str,
        why: &str,
    ) {
        let shown = path_text(path);
        // Only a top-level execution field written as a non-string, or one a model policy's
        // `override` takes; a nested key of the same name (`tools.effort`) is an ordinary set-aside.
        let (allowed, why_ignored) = match (path, policy_override_key(path)) {
            (_, Some(key @ ("effort" | "sandbox" | "approval" | "network"))) => {
                (execution_allowed(key), "not valid here")
            }
            ([PathSegment::Key(key)], None) if !value.is_string() => {
                (execution_allowed(key), "not a string")
            }
            _ => (None, ""),
        };
        let allowed = allowed.map(|allowed| match allowed.rsplit_once(", ") {
            Some((rest, last)) => format!("{rest} or {last}"),
            None => allowed.clone(),
        });
        let (code, message) = match (lost, allowed) {
            (Some(lost), allowed) => (
                RESTRICTION_LOST,
                format!(
                    "{} lost the restriction {lost}: {what}. Schema v1 does not accept it ({why}){}",
                    self.agent,
                    allowed.map_or(String::new(), |allowed| format!("; use {allowed}")),
                ),
            ),
            (None, Some(allowed)) => (
                EXECUTION_IGNORED,
                format!(
                    "{}: `{shown}: {}` ignored ({why_ignored}); use {allowed}",
                    self.agent,
                    crate::ordered::plain(value),
                ),
            ),
            (None, None) => (
                "field.set-aside",
                format!("`{shown}` is not valid in schema v1 ({why}); {what}"),
            ),
        };
        let change = SchemaDiagnostic::new(code, Severity::Warning, path.to_vec(), message);
        self.changes.push(if code == RESTRICTION_LOST {
            change.losing()
        } else {
            change
        });
    }
}

/// Drop each model policy `override` key the reader rejects and keep the rest of the list, when
/// those are all that it rejects. `rejections` ends empty if they were, else is left as it was:
/// anything but an override key takes the whole `model-policies` key.
fn drop_policy_overrides(
    fm: &mut Frontmatter,
    rejections: &mut Vec<Rejection>,
    report: &mut Report<'_>,
    changed: &mut bool,
) {
    if !rejections
        .iter()
        .all(|rejection| policy_override_key(&rejection.path).is_some())
    {
        return;
    }
    let Some(removed) = drop_entries(fm, "model-policies", rejections) else {
        return;
    };
    *changed = true;
    for (path, entry) in removed {
        let why = rejections
            .iter()
            .find(|rejection| rejection.path == path)
            .map_or("", |rejection| rejection.why.as_str());
        let lost = restriction_lost(&path, &entry);
        let what = "that override was dropped and the rest of the rule is kept";
        report.note(&path, &entry, lost, what, why);
    }
    rejections.clear();
}

/// Set aside every key of `fm` the strict reader rejects. Returns whether the frontmatter
/// changed. When `harness-overrides` or the destination entry is not a mapping the keys stay,
/// and the reader reports them.
pub(crate) fn set_aside_rejected_keys(
    fm: &mut Frontmatter,
    kind: DefinitionKind,
    destination: Destination<'_>,
    changes: &mut Vec<SchemaDiagnostic>,
) -> bool {
    let rejected = rejected_keys(kind, fm);
    if rejected.is_empty() {
        return false;
    }
    let mut report = Report {
        agent: match fm.get("name").and_then(Value::as_str) {
            Some(name) => format!("agent `{name}`"),
            None => "this agent".to_owned(),
        },
        changes,
    };
    let mut changed = false;
    let mut movable = Vec::new();
    for (key, mut rejections) in rejected {
        if key == "model-policies" {
            drop_policy_overrides(fm, &mut rejections, &mut report, &mut changed);
            if rejections.is_empty() {
                continue;
            }
        }
        let reserved = match kind {
            DefinitionKind::Agent => LoweredField::reserves(&key),
            DefinitionKind::Skill => skill::LOWERED_KEYS.contains(&key.as_str()),
        };
        let whole_key = rejections.iter().any(|rejection| rejection.path.len() == 1);
        if (reserved || HOST_SET_KEYS.contains(&key.as_str()))
            && !whole_key
            && let Some(removed) = drop_entries(fm, &key, &rejections)
        {
            changed = true;
            for (path, entry) in removed {
                let why = rejections
                    .iter()
                    .find(|rejection| rejection.path == path)
                    .map_or("", |rejection| rejection.why.as_str());
                let lost = restriction_lost(&path, &entry);
                let what = format!("that entry was dropped and the rest of `{key}` is kept");
                report.note(&path, &entry, lost, &what, why);
            }
            continue;
        }
        let why = reason(&key, fm.get(&key), destination, &rejections[0].why);
        if reserved || matches!(destination, Destination::Nowhere) {
            let removed = fm.remove(&key).unwrap_or(Value::Null);
            changed = true;
            let path = vec![PathSegment::Key(key.clone())];
            let lost = restriction_lost(&path, &removed);
            let what = if reserved {
                format!(
                    "it was dropped, because Mars lowers `{key}` itself and an override would not carry it"
                )
            } else {
                "it was dropped, because no harness reads it".to_owned()
            };
            report.note(&path, &removed, lost, &what, &why);
        } else {
            let value = fm.get(&key).cloned().unwrap_or(Value::Null);
            movable.push((key, why, value));
        }
    }
    if let Destination::Overrides(harness) = destination
        && !movable.is_empty()
    {
        let keys = movable
            .iter()
            .map(|(key, _, _)| (key.as_str(), key.as_str()))
            .collect::<Vec<_>>();
        if let Moved::Done { moved, displaced } = move_keys_under(fm, harness, &keys) {
            changed = true;
            for (key, why, value) in &movable {
                let what = if moved.contains(&key.as_str()) {
                    format!(
                        "it was moved under `harness-overrides.{harness}`, which Mars does not enforce"
                    )
                } else if displaced.iter().any(|(from, _)| *from == key.as_str()) {
                    format!("it was dropped, `harness-overrides.{harness}.{key}` already sets it")
                } else {
                    continue;
                };
                let path = vec![PathSegment::Key(key.clone())];
                // A restriction moved under an override is no longer enforced by Mars.
                let lost = RESTRICTION_KEYS
                    .contains(&key.as_str())
                    .then(|| format!("`{key}`"));
                report.note(&path, value, lost, &what, why);
            }
        }
    }
    changed
}