Skip to main content

mars_schema/
upgrade.rs

1//! Pure legacy Mars definition and manifest upgrades to schema v1.
2
3use serde_yaml::{Mapping, Value};
4use toml_edit::{DocumentMut, Item};
5
6use crate::claude;
7use crate::diagnostic::{PathSegment, SchemaDiagnostic, Severity};
8use crate::frontmatter::{Frontmatter, FrontmatterError};
9use crate::harness_overrides::{Moved, move_keys_under};
10use crate::item::DefinitionKind;
11use crate::{
12    agent::{REMOVED_AGENT_FIELDS, REMOVED_AGENT_VALUES},
13    skill,
14};
15
16#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
17pub struct UpgradeResult {
18    pub text: String,
19    /// What the upgrade changed, one note per key it dropped or moved.
20    pub diagnostics: Vec<SchemaDiagnostic>,
21    /// A changed definition whose text was re-rendered rather than edited minimally: the whole
22    /// frontmatter, or a `harness-overrides` block that could not be grown in place.
23    pub fully_rewritten: bool,
24    /// Authored key paths whose values or presence changed.
25    pub edited_paths: Vec<Vec<PathSegment>>,
26}
27
28impl UpgradeResult {
29    pub(crate) fn changed_from(&self, input: &str) -> bool {
30        self.text != input
31    }
32}
33
34#[derive(Debug, thiserror::Error)]
35pub enum UpgradeError {
36    #[error(transparent)]
37    Frontmatter(#[from] FrontmatterError),
38    #[error("failed to parse mars.toml: {0}")]
39    Manifest(#[from] toml_edit::TomlError),
40    #[error("mars.toml at a package root must contain [package]")]
41    MissingPackage,
42    #[error(
43        "`[package.tools]` needs `[package] schema = 1`; older Mars versions ignore it, so a package without a schema cannot carry it"
44    )]
45    PackageToolsNeedSchema,
46}
47
48pub fn upgrade_definition(kind: DefinitionKind, text: &str) -> Result<UpgradeResult, UpgradeError> {
49    rewrite(text, |frontmatter, diagnostics| match kind {
50        DefinitionKind::Agent => upgrade_agent(frontmatter, diagnostics),
51        DefinitionKind::Skill => upgrade_skill(frontmatter, diagnostics),
52    })
53}
54
55/// Apply only what schema 1 removes with a mechanical replacement: the Agent keys that moved
56/// under `harness-overrides`.
57///
58/// `mars migrate` runs this on a schema 1 file it is about to write back, so a file that
59/// carries a key the reader rejects is repaired instead of failing the run. Every reading
60/// caller leaves it off, because an authored schema 1 file is read exactly as written.
61pub fn relocate_removed_fields(
62    kind: DefinitionKind,
63    text: &str,
64) -> Result<UpgradeResult, UpgradeError> {
65    rewrite(text, |frontmatter, notes| {
66        rename_consumer_namespaces(frontmatter, notes);
67        if kind == DefinitionKind::Agent {
68            move_agent_fields(frontmatter, notes);
69        }
70    })
71}
72
73/// `text` with `apply`'s changes to its frontmatter, edited as minimally as the source shape
74/// allows.
75fn rewrite(
76    text: &str,
77    apply: impl FnOnce(&mut Frontmatter, &mut Vec<SchemaDiagnostic>),
78) -> Result<UpgradeResult, UpgradeError> {
79    let original = Frontmatter::parse(text)?;
80    let mut frontmatter = original.clone();
81    let mut diagnostics = Vec::new();
82    apply(&mut frontmatter, &mut diagnostics);
83    if frontmatter.mapping() == original.mapping() {
84        return Ok(UpgradeResult {
85            text: text.to_string(),
86            diagnostics,
87            fully_rewritten: false,
88            edited_paths: Vec::new(),
89        });
90    }
91
92    let edited_paths = changed_mapping_paths(original.mapping(), frontmatter.mapping());
93
94    // The fallback re-renders the frontmatter only. The body is authored prompt text that may be
95    // byte-sensitive (embedded examples, mixed line endings), so it is copied from the input
96    // rather than from the render, which ends every line in LF.
97    let fallback = {
98        let mut rewritten = with_line_ending_of(text, frontmatter.render_frontmatter());
99        rewritten.push_str(original.body());
100        rewritten
101    };
102    let minimally_edited = edit_top_level_blocks(text, original.mapping(), frontmatter.mapping())
103        .and_then(|edited| {
104            Frontmatter::parse(&edited.text)
105                .ok()
106                .filter(|parsed| parsed.mapping() == frontmatter.mapping())
107                .map(|_| edited)
108        });
109    Ok(UpgradeResult {
110        fully_rewritten: minimally_edited
111            .as_ref()
112            .is_none_or(|edited| edited.re_rendered),
113        text: minimally_edited.map_or(fallback, |edited| edited.text),
114        diagnostics,
115        edited_paths,
116    })
117}
118
119/// Convert a `mars.toml` to schema v1.
120///
121/// `prepare` and `mars migrate` run this on a pre-v1 package. It never touches `requires-mars`:
122/// the requirement gates whether a package may be read at all, so only `mars migrate`,
123/// which a human runs on the package they own, adds one (see [`ensure_requires_mars_floor`]).
124pub fn upgrade_manifest(text: &str) -> Result<UpgradeResult, UpgradeError> {
125    let mut document = text.parse::<DocumentMut>()?;
126    let package = document
127        .get_mut("package")
128        .and_then(Item::as_table_mut)
129        .ok_or(UpgradeError::MissingPackage)?;
130    if package.get("schema").and_then(Item::as_integer) == Some(1) {
131        return Ok(UpgradeResult {
132            text: text.to_string(),
133            diagnostics: Vec::new(),
134            fully_rewritten: false,
135            edited_paths: Vec::new(),
136        });
137    }
138    if package.contains_key("tools") {
139        return Err(UpgradeError::PackageToolsNeedSchema);
140    }
141    let mut diagnostics = Vec::new();
142    let mut edited_paths = vec![package_path("schema")];
143    package.insert("schema", toml_edit::value(1));
144    if package.remove("visibility").is_some() {
145        diagnostics.push(removed(&["package", "visibility"], "visibility"));
146        edited_paths.push(package_path("visibility"));
147    }
148    Ok(UpgradeResult {
149        text: with_line_ending_of(text, document.to_string()),
150        diagnostics,
151        fully_rewritten: false,
152        edited_paths,
153    })
154}
155
156/// Adding the `requires-mars` floor to a manifest.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct FloorOutcome {
159    /// The manifest with the key added, or the input when it was not.
160    pub text: String,
161    /// `mars check`'s advice, when the requirement exists and admits a Mars that reads the
162    /// package as pre-v1, or when the manifest has a shape migrate cannot edit minimally.
163    pub warning: Option<String>,
164}
165
166/// Add `requires-mars = ">=0.20.0"` to a manifest that has no requirement.
167///
168/// `mars migrate` runs this on the manifest it is about to write, so a schema v1 package needs
169/// no hand edit. An existing requirement is never rewritten: when it admits a Mars older than
170/// the first release that reads schema 1, [`FloorOutcome::warning`] is `mars check`'s advice and
171/// the value keeps its bytes and comment. A manifest migrate cannot edit minimally (an inline
172/// `[package]` table) comes back unchanged with the same advice, never an error, so an
173/// already-v1 package migrates exactly as it did before this key existed.
174pub fn ensure_requires_mars_floor(text: &str) -> Result<FloorOutcome, UpgradeError> {
175    let mut document = text.parse::<DocumentMut>()?;
176    let package = document
177        .get_mut("package")
178        .ok_or(UpgradeError::MissingPackage)?;
179    let requirement = package
180        .as_table_like()
181        .and_then(|table| table.get("requires-mars"))
182        .and_then(Item::as_str)
183        .map(str::to_owned);
184    if requirement.is_none()
185        && let Some(table) = package.as_table_mut()
186    {
187        table.insert(
188            "requires-mars",
189            toml_edit::value(format!(">={}", crate::package::SCHEMA_1_MARS_FLOOR)),
190        );
191        return Ok(FloorOutcome {
192            text: with_line_ending_of(text, document.to_string()),
193            warning: None,
194        });
195    }
196    Ok(FloorOutcome {
197        text: text.to_string(),
198        warning: crate::package::schema_1_requires_mars_warning(requirement.as_deref()),
199    })
200}
201
202fn package_path(key: &str) -> Vec<PathSegment> {
203    vec![
204        PathSegment::Key("package".to_string()),
205        PathSegment::Key(key.to_string()),
206    ]
207}
208
209/// Whether the file's first line ends in `\r\n`.
210fn is_crlf(text: &str) -> bool {
211    text.find('\n')
212        .is_some_and(|end| text.as_bytes()[..end].ends_with(b"\r"))
213}
214
215/// `written` uses `\n` where the upgrade added lines; a CRLF file stays CRLF.
216fn with_line_ending_of(original: &str, written: String) -> String {
217    if !is_crlf(original) {
218        return written;
219    }
220    let mut out = String::with_capacity(written.len() + written.len() / 16);
221    let mut previous = '\0';
222    for character in written.chars() {
223        if character == '\n' && previous != '\r' {
224            out.push('\r');
225        }
226        out.push(character);
227        previous = character;
228    }
229    out
230}
231
232fn changed_mapping_paths(before: &Mapping, after: &Mapping) -> Vec<Vec<PathSegment>> {
233    let mut keys = before
234        .keys()
235        .chain(after.keys())
236        .filter_map(Value::as_str)
237        .collect::<Vec<_>>();
238    keys.sort_unstable();
239    keys.dedup();
240    keys.into_iter()
241        .filter(|key| {
242            let key = Value::String((*key).to_string());
243            before.get(&key) != after.get(&key)
244        })
245        .map(|key| vec![PathSegment::Key(key.to_string())])
246        .collect()
247}
248
249#[derive(Debug)]
250struct SourceBlock<'a> {
251    key: &'a str,
252    text: &'a str,
253    key_end: usize,
254    start: usize,
255}
256
257/// A frontmatter edited in place, and whether a block had to be re-rendered from its parsed
258/// value, which drops the comments and flow style written inside it.
259struct Edited {
260    text: String,
261    re_rendered: bool,
262}
263
264/// Rewrite only changed top-level blocks. Complex top-level YAML deliberately returns `None` so
265/// the caller has one explicit, verified full-serialization fallback.
266fn edit_top_level_blocks(text: &str, before: &Mapping, after: &Mapping) -> Option<Edited> {
267    let (prefix, yaml, suffix) = frontmatter_source(text)?;
268    let blocks = source_blocks(yaml)?;
269    let before_keys = before
270        .keys()
271        .map(Value::as_str)
272        .collect::<Option<Vec<_>>>()?;
273    if blocks.iter().map(|block| block.key).collect::<Vec<_>>() != before_keys {
274        return None;
275    }
276
277    let render = |key: &str, value: &Value| with_line_ending_of(text, render_block(key, value));
278    let mut output = String::with_capacity(text.len());
279    let mut re_rendered = false;
280    output.push_str(prefix);
281    let first_key_offset = blocks.first().map_or(yaml.len(), |block| block.start);
282    output.push_str(&yaml[..first_key_offset]);
283
284    let mut emitted = Vec::new();
285    for block in blocks {
286        let before_value = before.get(Value::String(block.key.to_string()))?;
287        if let Some(rename) = renamed_key(block.key, before, after) {
288            output.push_str(rename);
289            output.push_str(&block.text[block.key_end..]);
290            emitted.push(rename);
291        } else if let Some(after_value) = after.get(Value::String(block.key.to_string())) {
292            if before_value == after_value {
293                output.push_str(block.text);
294            } else if let Some(edited) = grown_in_place(&block, before_value, after_value)
295                .or_else(|| renamed_in_place(&block, before_value, after_value))
296            {
297                output.push_str(&edited);
298            } else {
299                // Re-rendering a block loses what the author wrote inside it, which only a
300                // `harness-overrides` block can avoid by growing in place, so a file that fell back
301                // here is reported.
302                re_rendered |= block.key == "harness-overrides";
303                output.push_str(&render(block.key, after_value));
304            }
305            emitted.push(block.key);
306        }
307    }
308
309    for (key, value) in after {
310        let key = key.as_str()?;
311        if emitted.contains(&key) {
312            continue;
313        }
314        if !output.ends_with('\n') {
315            output.push_str(&with_line_ending_of(text, "\n".to_owned()));
316        }
317        output.push_str(&render(key, value));
318    }
319    output.push_str(suffix);
320    Some(Edited {
321        text: output,
322        re_rendered,
323    })
324}
325
326/// `block` with the entries `after` adds, appended as text, so the comments and flow style the
327/// author wrote in the entries already there survive. `None` when the block cannot take text that
328/// simply: it is written in flow style, or an entry it has changed.
329fn grown_in_place(block: &SourceBlock<'_>, before: &Value, after: &Value) -> Option<String> {
330    let (Value::Mapping(before), Value::Mapping(after)) = (before, after) else {
331        return None;
332    };
333    if before
334        .iter()
335        .any(|(key, value)| after.get(key) != Some(value))
336    {
337        return None;
338    }
339    let added = after
340        .iter()
341        .filter(|(key, _)| before.get(key).is_none())
342        .collect::<Vec<_>>();
343    let indent = (!added.is_empty()).then(|| child_indent(block)).flatten()?;
344    // The block's text runs up to the next top-level key, so it ends with whatever blank lines and
345    // comments were written above that key; the new entries go before them.
346    let (body, tail) = split_trailing_run(block.text);
347    let mut grown = body.to_string();
348    if !grown.ends_with('\n') {
349        grown.push('\n');
350    }
351    for (key, value) in added {
352        let rendered = render_block(key.as_str()?, value);
353        // The block's own indentation is the author's; serde's two spaces a level become theirs.
354        let indented = rendered
355            .lines()
356            .map(|line| {
357                let depth = line.len() - line.trim_start().len();
358                format!("{}{}", indent.repeat(depth / 2 + 1), line.trim_start())
359            })
360            .collect::<Vec<_>>()
361            .join("\n");
362        grown.push_str(&indented);
363        grown.push('\n');
364    }
365    grown.push_str(tail);
366    Some(with_line_ending_of(block.text, grown))
367}
368
369/// `block` with its host namespace keys renamed where they are written, so the comments, flow
370/// style and quoting around them survive. `None` when `after` is more than the renames of
371/// `before`, or a renamed key is not written as a plain key at the block's own indentation.
372fn renamed_in_place(block: &SourceBlock<'_>, before: &Value, after: &Value) -> Option<String> {
373    let (Value::Mapping(before), Value::Mapping(after)) = (before, after) else {
374        return None;
375    };
376    if before.len() != after.len() {
377        return None;
378    }
379    let mut renames = Vec::new();
380    for ((old, old_value), (new, new_value)) in before.iter().zip(after) {
381        if old_value != new_value {
382            return None;
383        }
384        if old != new {
385            let pair = (old.as_str()?, new.as_str()?);
386            if !crate::harness::RENAMED_CONSUMER_NAMESPACES.contains(&pair) {
387                return None;
388            }
389            renames.push(pair);
390        }
391    }
392    let indent = child_indent(block)?;
393    let mut done = 0;
394    let mut edited = String::with_capacity(block.text.len());
395    for line in block.text.split_inclusive('\n') {
396        let renamed = line.strip_prefix(indent).and_then(|rest| {
397            renames.iter().find_map(|&(old, new)| {
398                let after_key = rest.strip_prefix(old)?;
399                after_key
400                    .trim_start_matches(' ')
401                    .starts_with(':')
402                    .then(|| format!("{indent}{new}{after_key}"))
403            })
404        });
405        match renamed {
406            Some(line) => {
407                done += 1;
408                edited.push_str(&line);
409            }
410            None => edited.push_str(line),
411        }
412    }
413    (done == renames.len()).then_some(edited)
414}
415
416/// `text` split where an appended entry belongs: before the trailing run of blank lines and
417/// comments at the document's left edge, which belong to the key below the block.
418fn split_trailing_run(text: &str) -> (&str, &str) {
419    let mut split = text.len();
420    for line in text.split_inclusive('\n').rev() {
421        let content = line.trim_end_matches(['\r', '\n']);
422        if !content.trim().is_empty() && !content.starts_with('#') {
423            break;
424        }
425        split -= line.len();
426    }
427    text.split_at(split)
428}
429
430/// The indentation of `block`'s own children in its source text, and `None` when it has none to
431/// line up with: a flow mapping, or a value that is not a mapping at all.
432fn child_indent<'a>(block: &'a SourceBlock<'a>) -> Option<&'a str> {
433    let first = block.text.split_inclusive('\n').next()?;
434    let rest = first[block.key_end + 1..].trim_end_matches(['\r', '\n']);
435    if !(rest.trim().is_empty() || rest.trim_start().starts_with('#')) {
436        return None;
437    }
438    for line in block.text.split_inclusive('\n').skip(1) {
439        let content = line.trim_end_matches(['\r', '\n']);
440        if content.trim().is_empty() || content.trim_start().starts_with('#') {
441            continue;
442        }
443        let indent = content.len() - content.trim_start().len();
444        return (indent > 0).then(|| &content[..indent]);
445    }
446    None
447}
448
449fn renamed_key<'a>(old: &str, before: &Mapping, after: &'a Mapping) -> Option<&'a str> {
450    let new = match old {
451        "model_invocable" => "model-invocable",
452        "user_invocable" => "user-invocable",
453        "disallowed_tools" => "disallowed-tools",
454        _ => return None,
455    };
456    if before.contains_key(Value::String(new.to_string())) {
457        return None;
458    }
459    let old_value = before.get(Value::String(old.to_string()))?;
460    (after.get(Value::String(new.to_string())) == Some(old_value)).then_some(new)
461}
462
463fn render_block(key: &str, value: &Value) -> String {
464    let mut mapping = Mapping::new();
465    mapping.insert(Value::String(key.to_string()), value.clone());
466    let yaml = serde_yaml::to_string(&mapping).expect("serializing an upgraded YAML block");
467    yaml.strip_prefix("---\n").unwrap_or(&yaml).to_string()
468}
469
470fn frontmatter_source(text: &str) -> Option<(&str, &str, &str)> {
471    let first_end = text.find('\n').map_or(text.len(), |offset| offset + 1);
472    if text[..first_end]
473        .strip_prefix('\u{feff}')
474        .unwrap_or(&text[..first_end])
475        .trim_end()
476        != "---"
477    {
478        return None;
479    }
480    let mut offset = first_end;
481    for line in text[first_end..].split_inclusive('\n') {
482        if line.trim_end() == "---" {
483            return Some((
484                &text[..first_end],
485                &text[first_end..offset],
486                &text[offset..],
487            ));
488        }
489        offset += line.len();
490    }
491    None
492}
493
494fn source_blocks(yaml: &str) -> Option<Vec<SourceBlock<'_>>> {
495    let mut starts = Vec::new();
496    let mut offset = 0;
497    for line in yaml.split_inclusive('\n') {
498        let content = line.trim_end_matches(['\r', '\n']);
499        if !content.is_empty()
500            && !content.starts_with(char::is_whitespace)
501            && !content.starts_with('#')
502        {
503            let colon = content.find(':')?;
504            let key = &content[..colon];
505            if key.is_empty()
506                || !key
507                    .bytes()
508                    .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
509            {
510                return None;
511            }
512            starts.push((offset, key, colon));
513        }
514        offset += line.len();
515    }
516    let mut blocks = Vec::with_capacity(starts.len());
517    for (index, (start, key, key_end)) in starts.iter().copied().enumerate() {
518        let end = starts
519            .get(index + 1)
520            .map_or(yaml.len(), |(start, _, _)| *start);
521        blocks.push(SourceBlock {
522            key,
523            text: &yaml[start..end],
524            key_end,
525            start,
526        });
527    }
528    Some(blocks)
529}
530
531/// The rules for what only pre-v1 Mars wrote, key by key: the invocability renames, the
532/// discarded Agent fields, the removed values, a scalar `permission` and the removed model-policy
533/// override keys. No foreign dialect defines any of them, so every translation applies them
534/// before its own rules (`lift_frontmatter`), and the legacy upgrade is the same rules plus its
535/// own. A tree is never classified as pre-v1 Mars by finding one: its other keys are read in the
536/// dialect they belong to.
537pub(crate) fn lift_mars_only_keys(
538    fm: &mut Frontmatter,
539    kind: DefinitionKind,
540    notes: &mut Vec<SchemaDiagnostic>,
541) -> bool {
542    let before = fm.mapping().clone();
543    rename_field(fm, "model_invocable", "model-invocable");
544    rename_field(fm, "user_invocable", "user-invocable");
545    if kind == DefinitionKind::Agent {
546        merge_host_set_spellings(fm, "network_allow", "network-allow");
547        merge_host_set_spellings(fm, "network_deny", "network-deny");
548        for field in REMOVED_AGENT_FIELDS.iter().filter(|field| field.discarded) {
549            if fm.remove(field.key).is_some() {
550                notes.push(removed(&[field.key], field.key));
551            }
552        }
553        for removed in REMOVED_AGENT_VALUES {
554            replace_scalar(fm, removed.key, removed.value, removed.replacement);
555        }
556        move_agent_fields(fm, notes);
557        strip_model_policy_overrides(fm, notes);
558    }
559    fm.mapping() != &before
560}
561
562fn upgrade_agent(fm: &mut Frontmatter, diagnostics: &mut Vec<SchemaDiagnostic>) {
563    // Before `move_agent_fields`, so a top-level key lands in the block it names, not beside a
564    // block still written under the old name.
565    rename_consumer_namespaces(fm, diagnostics);
566    upgrade_tools(fm);
567    lift_mars_only_keys(fm, DefinitionKind::Agent, diagnostics);
568    // A pre-v1 file passed unknown keys to every harness; Claude's own keep reaching Claude.
569    claude::translate::move_to_claude_overrides(fm, DefinitionKind::Agent, diagnostics);
570    set_aside_rejected_keys(fm, DefinitionKind::Agent, diagnostics);
571}
572
573fn upgrade_skill(fm: &mut Frontmatter, diagnostics: &mut Vec<SchemaDiagnostic>) {
574    rename_consumer_namespaces(fm, diagnostics);
575    lift_mars_only_keys(fm, DefinitionKind::Skill, diagnostics);
576
577    if let Some(skill_type) = fm.get("type").cloned() {
578        let metadata = fm
579            .get("metadata")
580            .cloned()
581            .unwrap_or_else(|| Value::Mapping(Mapping::new()));
582        if let Value::Mapping(mut metadata) = metadata {
583            let key = Value::String("type".to_string());
584            if !metadata.contains_key(&key) {
585                metadata.insert(key, skill_type);
586                fm.insert("metadata", Value::Mapping(metadata));
587                fm.remove("type");
588            }
589        }
590    }
591
592    if let Some(when) = fm
593        .get("when_to_use")
594        .and_then(Value::as_str)
595        .map(str::to_owned)
596    {
597        let description = match fm.get("description") {
598            Some(Value::String(description)) => Some(format!("{description}\n\n{when}")),
599            None => Some(when),
600            Some(_) => None,
601        };
602        if let Some(description) = description {
603            fm.insert("description", Value::String(description));
604            fm.remove("when_to_use");
605        }
606    }
607
608    for key in skill::tool_keys() {
609        if fm.remove(key).is_some() {
610            diagnostics.push(SchemaDiagnostic::new(
611                "skill.tools-dropped",
612                Severity::Warning,
613                vec![PathSegment::Key(key.to_string())],
614                format!("removed skill key `{key}`; skill tool rules have no v1 meaning"),
615            ));
616        }
617    }
618
619    claude::translate::move_to_claude_overrides(fm, DefinitionKind::Skill, diagnostics);
620    set_aside_rejected_keys(fm, DefinitionKind::Skill, diagnostics);
621}
622
623/// What the rules above could not make schema v1 is dropped, with a warning naming it, so the
624/// upgrade never hands the strict reader a value it rejects. It is not kept under
625/// `harness-overrides.meridian-flow`: Meridian Flow defines one key, `permission`, and `lift_mars_only_keys` writes
626/// it there when it is `read` or `edit`. Anything else in that namespace would not be Meridian Flow's.
627fn set_aside_rejected_keys(
628    fm: &mut Frontmatter,
629    kind: DefinitionKind,
630    diagnostics: &mut Vec<SchemaDiagnostic>,
631) {
632    crate::set_aside::set_aside_rejected_keys(
633        fm,
634        kind,
635        crate::set_aside::Destination::Nowhere,
636        diagnostics,
637    );
638}
639
640fn upgrade_tools(fm: &mut Frontmatter) {
641    rename_field(fm, "disallowed_tools", "disallowed-tools");
642    if let Some(Value::Sequence(entries)) = fm.get("tools").cloned()
643        && entries.iter().all(|entry| entry.as_str().is_some())
644    {
645        let policy = entries
646            .into_iter()
647            .map(|entry| (entry, Value::String("allow".to_string())))
648            .collect();
649        fm.insert("tools", Value::Mapping(policy));
650    }
651
652    let Some(Value::Sequence(disallowed)) = fm.get("disallowed-tools").cloned() else {
653        return;
654    };
655    if !disallowed.iter().all(|entry| entry.as_str().is_some()) {
656        return;
657    }
658    let policy = fm
659        .get("tools")
660        .cloned()
661        .unwrap_or_else(|| Value::Mapping(Mapping::new()));
662    let Value::Mapping(mut policy) = policy else {
663        return;
664    };
665    for entry in disallowed {
666        policy.insert(entry, Value::String("deny".to_string()));
667    }
668    fm.insert("tools", Value::Mapping(policy));
669    fm.remove("disallowed-tools");
670}
671
672/// The Agent keys schema 1 replaced with a `harness-overrides` key: the consumer namespace that
673/// owns it, and the name it takes there.
674///
675/// One conflict rule covers all three: a block already written wins, and its top-level twin is
676/// dropped with a note naming it. `permission` moves only for the values Flow defines; see
677/// [`moves_under_namespace`].
678const MOVED_AGENT_FIELDS: &[(&str, &str, &str)] = &[
679    ("meridian-flow", "permission", "permission"),
680    (
681        "meridian-cli",
682        "resident-rearm-budget",
683        "resident-rearm-budget",
684    ),
685    ("meridian-cli", "meridian-capabilities", "capabilities"),
686];
687
688/// Whether the top-level `key` moves under its consumer namespace. Meridian Flow defines
689/// `read` and `edit` only, so any other `permission` value stays where it is for the reader to report.
690fn moves_under_namespace(fm: &Frontmatter, key: &str) -> bool {
691    key != "permission"
692        || fm
693            .get(key)
694            .and_then(Value::as_str)
695            .is_some_and(|permission| matches!(permission, "read" | "edit"))
696}
697
698/// Move the Agent keys schema 1 replaced with a `harness-overrides` key. An existing block wins,
699/// and the top-level twin it displaces is dropped with a note: the reader would otherwise report
700/// the key `mars migrate` left behind.
701fn move_agent_fields(fm: &mut Frontmatter, notes: &mut Vec<SchemaDiagnostic>) {
702    let mut displaced = Vec::new();
703    for &namespace in crate::harness::RESERVED_CONSUMER_NAMESPACES {
704        let keys = MOVED_AGENT_FIELDS
705            .iter()
706            .filter_map(|(owner, from, to)| {
707                (*owner == namespace && moves_under_namespace(fm, from)).then_some((*from, *to))
708            })
709            .collect::<Vec<_>>();
710        if let Moved::Done {
711            displaced: dropped, ..
712        } = move_keys_under(fm, namespace, &keys)
713        {
714            displaced.extend(dropped.into_iter().map(|(from, to)| (namespace, from, to)));
715        }
716    }
717    for (namespace, from, to) in displaced {
718        notes.push(dropped_twin(
719            &agent_label(fm),
720            vec![PathSegment::Key(from.to_string())],
721            from,
722            namespace,
723            to,
724        ));
725    }
726}
727
728/// Rename `harness-overrides.flow` and `.meridian` to the full host names, in place. When the
729/// block under the new name exists too, the two merge key by key: a key only the old block sets
730/// moves over, and a key both set keeps the new block's value, the old one dropped with a note.
731fn rename_consumer_namespaces(fm: &mut Frontmatter, notes: &mut Vec<SchemaDiagnostic>) {
732    let agent = agent_label(fm);
733    let Some(Value::Mapping(overrides)) = fm.get_mut("harness-overrides") else {
734        return;
735    };
736    for &(old, new) in crate::harness::RENAMED_CONSUMER_NAMESPACES {
737        let old_key = Value::String(old.to_string());
738        let new_key = Value::String(new.to_string());
739        let Some(old_block) = overrides.get(&old_key).cloned() else {
740            continue;
741        };
742        let block_path = vec![
743            PathSegment::Key("harness-overrides".to_string()),
744            PathSegment::Key(old.to_string()),
745        ];
746        let Some(new_block) = overrides.get_mut(&new_key) else {
747            // Rebuilt so the renamed block keeps its place among its siblings.
748            *overrides = std::mem::take(overrides)
749                .into_iter()
750                .map(|(key, value)| {
751                    if key == old_key {
752                        (new_key.clone(), value)
753                    } else {
754                        (key, value)
755                    }
756                })
757                .collect();
758            continue;
759        };
760        match (new_block, old_block) {
761            (Value::Mapping(new_block), Value::Mapping(old_block)) => {
762                let twin = Twin {
763                    agent: &agent,
764                    old,
765                    new,
766                };
767                merge_old_block(new_block, old_block, &twin, &[], notes);
768            }
769            _ => notes.push(SchemaDiagnostic::new(
770                "field.removed",
771                Severity::Warning,
772                block_path,
773                format!(
774                    "dropped `harness-overrides.{old}`; `harness-overrides.{new}` already sets it"
775                ),
776            )),
777        }
778        overrides.remove(&old_key);
779    }
780}
781
782fn agent_label(fm: &Frontmatter) -> String {
783    fm.get("name").and_then(Value::as_str).map_or_else(
784        || "this agent".to_string(),
785        |name| format!("agent `{name}`"),
786    )
787}
788
789/// The two namespace blocks being merged, for naming a dropped key in its note.
790struct Twin<'a> {
791    agent: &'a str,
792    old: &'a str,
793    new: &'a str,
794}
795
796/// Fold `old` into `new` key by key. A key only `old` sets moves over (a non-string key too:
797/// the reader reports it), mappings on both sides merge recursively, and any other clash keeps
798/// the `new` value and notes the dropped one.
799fn merge_old_block(
800    new: &mut Mapping,
801    old: Mapping,
802    twin: &Twin,
803    rel: &[String],
804    notes: &mut Vec<SchemaDiagnostic>,
805) {
806    for (key, value) in old {
807        let name = key
808            .as_str()
809            .map_or_else(|| format!("{key:?}"), str::to_owned);
810        let mut key_rel = rel.to_vec();
811        key_rel.push(name);
812        match new.get_mut(&key) {
813            None => {
814                new.insert(key, value);
815            }
816            Some(existing) if *existing == value => {}
817            Some(Value::Mapping(existing)) if value.is_mapping() => {
818                let Value::Mapping(value) = value else {
819                    unreachable!()
820                };
821                merge_old_block(existing, value, twin, &key_rel, notes);
822            }
823            Some(_) => {
824                let dotted = key_rel.join(".");
825                let mut path = vec![
826                    PathSegment::Key("harness-overrides".to_string()),
827                    PathSegment::Key(twin.old.to_string()),
828                ];
829                path.extend(key_rel.into_iter().map(PathSegment::Key));
830                let dropped = format!("harness-overrides.{}.{dotted}", twin.old);
831                notes.push(dropped_twin(twin.agent, path, &dropped, twin.new, &dotted));
832            }
833        }
834    }
835}
836
837/// The note for a value `dropped` (named as written) because the `namespace` block already sets
838/// `key` (dotted, relative to the block). A dropped `permission` or `capabilities` entry carried
839/// a restriction, which the note names as lost (`field.restriction-lost`, as the set-aside
840/// reports the same loss).
841fn dropped_twin(
842    agent: &str,
843    path: Vec<PathSegment>,
844    dropped: &str,
845    namespace: &str,
846    key: &str,
847) -> SchemaDiagnostic {
848    if key == "permission" || key == "capabilities" || key.starts_with("capabilities.") {
849        return SchemaDiagnostic::new(
850            crate::set_aside::RESTRICTION_LOST,
851            Severity::Warning,
852            path,
853            format!(
854                "{agent} lost the restriction `{key}`: it was dropped, because \
855                 `harness-overrides.{namespace}.{key}` already sets a value, and an override \
856                 written wins"
857            ),
858        );
859    }
860    SchemaDiagnostic::new(
861        "field.removed",
862        Severity::Warning,
863        path,
864        format!("dropped `{dropped}`; `harness-overrides.{namespace}.{key}` already sets it"),
865    )
866}
867
868fn strip_model_policy_overrides(fm: &mut Frontmatter, diagnostics: &mut Vec<SchemaDiagnostic>) {
869    let Some(Value::Sequence(policies)) = fm.get_mut("model-policies") else {
870        return;
871    };
872    for (index, policy) in policies.iter_mut().enumerate() {
873        let Value::Mapping(policy) = policy else {
874            continue;
875        };
876        let Some(Value::Mapping(overrides)) = policy.get_mut(Value::String("override".to_string()))
877        else {
878            continue;
879        };
880        // The legacy effort spellings mean the same here as at the top level.
881        for (old, new) in [("adaptive", "medium"), ("disabled", "none")] {
882            let key = Value::String("effort".to_string());
883            if overrides.get(&key).and_then(Value::as_str) == Some(old) {
884                overrides.insert(key, Value::String(new.to_string()));
885            }
886        }
887        for key in ["autocompact", "autocompact_pct", "harness"] {
888            if overrides.remove(Value::String(key.to_string())).is_some() {
889                diagnostics.push(SchemaDiagnostic::new(
890                    "field.removed",
891                    Severity::Warning,
892                    vec![
893                        PathSegment::Key("model-policies".to_string()),
894                        PathSegment::Index(index),
895                        PathSegment::Key("override".to_string()),
896                        PathSegment::Key(key.to_string()),
897                    ],
898                    format!("removed model policy override key `{key}`"),
899                ));
900            }
901        }
902    }
903}
904
905fn rename_field(fm: &mut Frontmatter, old: &str, new: &str) {
906    let Some(value) = fm.remove(old) else {
907        return;
908    };
909    if fm.get(new).is_none() {
910        fm.insert(new, value);
911    }
912}
913
914/// A host set written under both spellings keeps every host of both: dropping either would
915/// lose a deny. A value that is not a host list or a `{replace: [...]}` map stays where it is, so
916/// the reader reports it.
917fn merge_host_set_spellings(fm: &mut Frontmatter, old: &str, new: &str) {
918    let (Some(old_value), Some(new_value)) = (fm.get(old), fm.get(new)) else {
919        return rename_field(fm, old, new);
920    };
921    let (Some((old_hosts, old_replaces)), Some((mut hosts, new_replaces))) =
922        (host_set_parts(old_value), host_set_parts(new_value))
923    else {
924        return;
925    };
926    for host in old_hosts {
927        if !hosts.contains(&host) {
928            hosts.push(host);
929        }
930    }
931    let merged = if old_replaces || new_replaces {
932        let mut replace = serde_yaml::Mapping::new();
933        replace.insert(Value::String("replace".to_string()), Value::Sequence(hosts));
934        Value::Mapping(replace)
935    } else {
936        Value::Sequence(hosts)
937    };
938    fm.insert(new, merged);
939    fm.remove(old);
940}
941
942fn host_set_parts(value: &Value) -> Option<(Vec<Value>, bool)> {
943    match value {
944        Value::Sequence(hosts) => Some((hosts.clone(), false)),
945        Value::Mapping(map) if map.len() == 1 => map
946            .get("replace")
947            .and_then(Value::as_sequence)
948            .map(|hosts| (hosts.clone(), true)),
949        _ => None,
950    }
951}
952
953fn replace_scalar(fm: &mut Frontmatter, key: &str, old: &str, new: &str) {
954    if fm.get(key).and_then(Value::as_str) == Some(old) {
955        fm.insert(key, Value::String(new.to_string()));
956    }
957}
958
959fn removed(path: &[&str], key: &str) -> SchemaDiagnostic {
960    SchemaDiagnostic::new(
961        "field.removed",
962        Severity::Warning,
963        path.iter()
964            .map(|part| PathSegment::Key((*part).to_string()))
965            .collect(),
966        format!("removed legacy key `{key}`"),
967    )
968}