1use 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::keys;
12use crate::tool_policy;
13
14#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
15pub struct UpgradeResult {
16 pub text: String,
17 pub diagnostics: Vec<SchemaDiagnostic>,
19 pub fully_rewritten: bool,
22 pub edited_paths: Vec<Vec<PathSegment>>,
24}
25
26impl UpgradeResult {
27 pub(crate) fn changed_from(&self, input: &str) -> bool {
28 self.text != input
29 }
30}
31
32#[derive(Debug, thiserror::Error)]
33pub enum UpgradeError {
34 #[error(transparent)]
35 Frontmatter(#[from] FrontmatterError),
36 #[error("failed to parse mars.toml: {0}")]
37 Manifest(#[from] toml_edit::TomlError),
38 #[error("mars.toml at a package root must contain [package]")]
39 MissingPackage,
40 #[error(
41 "`[package.tools]` needs `[package] schema = 1`; older Mars versions ignore it, so a package without a schema cannot carry it"
42 )]
43 PackageToolsNeedSchema,
44}
45
46pub(crate) type Fold = fn(&mut Frontmatter, &mut Vec<SchemaDiagnostic>) -> bool;
48
49pub(crate) struct PreV1 {
55 pub agent_dropped: &'static [&'static str],
57 pub renamed: &'static [(&'static str, &'static str)],
59 pub agent_host_sets: &'static [(&'static str, &'static str)],
61 pub agent_moved: &'static [(&'static str, &'static str, &'static str)],
64 pub agent_moved_maps: &'static [(&'static str, &'static str)],
68 pub agent_values: &'static [(&'static str, &'static str, &'static str)],
70 pub skill_tool_keys: &'static [&'static str],
74 pub skill_folded: &'static [(&'static str, Fold)],
76 pub skill_dropped: &'static [&'static str],
78 pub policy_override_dropped: &'static [&'static str],
80 pub package_dropped: &'static [&'static str],
82 pub namespaces: &'static [(&'static str, &'static str)],
84}
85
86pub(crate) const PRE_V1: PreV1 = PreV1 {
87 agent_dropped: &[
88 "fanout",
89 "models",
90 "mcp-tools",
91 "autocompact",
92 "autocompact_pct",
93 ],
94 renamed: &[
95 ("model_invocable", "model-invocable"),
96 ("user_invocable", "user-invocable"),
97 ],
98 agent_host_sets: &[
99 ("network_allow", "network-allow"),
100 ("network_deny", "network-deny"),
101 ],
102 agent_moved: &[
103 ("meridian-flow", "permission", "permission"),
104 (
105 "meridian-cli",
106 "resident-rearm-budget",
107 "resident-rearm-budget",
108 ),
109 ("meridian-cli", "meridian-capabilities", "capabilities"),
110 ],
111 agent_moved_maps: &[("opencode", "permission")],
112 agent_values: &[
113 ("approval", "yolo", "never"),
114 ("effort", "adaptive", "medium"),
115 ("effort", "disabled", "none"),
116 ],
117 skill_tool_keys: &["tools", "allowed-tools", "allowed_tools"],
118 skill_folded: &[
119 ("type", fold_type),
120 ("when_to_use", fold_when_to_use),
121 ("disable-model-invocation", fold_disable_model_invocation),
122 ],
123 skill_dropped: &["invocation", "allow_implicit_invocation"],
124 policy_override_dropped: &["autocompact", "autocompact_pct", "harness"],
125 package_dropped: &["visibility"],
126 namespaces: &[("flow", "meridian-flow"), ("meridian", "meridian-cli")],
127};
128
129impl PreV1 {
130 pub(crate) fn key(&self, kind: DefinitionKind, key: &str) -> bool {
132 if self.renamed.iter().any(|(old, _)| *old == key) {
133 return true;
134 }
135 match kind {
136 DefinitionKind::Agent => {
137 self.agent_dropped.contains(&key)
138 || self.agent_host_sets.iter().any(|(old, _)| *old == key)
139 || tool_policy::DISALLOWED_SPELLINGS.contains(&key)
140 || self.agent_moved.iter().any(|(_, moved, _)| *moved == key)
141 || self.agent_moved_maps.iter().any(|(_, moved)| *moved == key)
142 }
143 DefinitionKind::Skill => {
144 crate::skill::tool_keys().any(|known| known == key)
145 || self.skill_folded.iter().any(|(known, _)| *known == key)
146 || self.skill_dropped.contains(&key)
147 }
148 }
149 }
150
151 pub(crate) fn value(&self, key: &str, value: &str) -> bool {
153 self.agent_values
154 .iter()
155 .any(|(known, old, _)| *known == key && *old == value)
156 }
157
158 pub(crate) fn namespace(&self, old: &str) -> bool {
159 self.namespaces.iter().any(|(known, _)| *known == old)
160 }
161}
162
163pub(crate) fn pre_v1_key(path: Vec<PathSegment>, key: &str) -> SchemaDiagnostic {
165 SchemaDiagnostic::new(
166 "field.removed",
167 Severity::Error,
168 path,
169 format!("`{key}` is a pre-v1 key; `mars migrate` upgrades this file"),
170 )
171}
172
173pub(crate) fn pre_v1_value(path: Vec<PathSegment>, key: &str, value: &str) -> SchemaDiagnostic {
175 SchemaDiagnostic::new(
176 "field.removed",
177 Severity::Error,
178 path,
179 format!("`{key}: {value}` is a pre-v1 value; `mars migrate` upgrades this file"),
180 )
181}
182
183pub fn upgrade_definition(kind: DefinitionKind, text: &str) -> Result<UpgradeResult, UpgradeError> {
184 rewrite(text, |frontmatter, diagnostics| match kind {
185 DefinitionKind::Agent => upgrade_agent(frontmatter, diagnostics),
186 DefinitionKind::Skill => upgrade_skill(frontmatter, diagnostics),
187 })
188}
189
190pub fn migrate_definition(kind: DefinitionKind, text: &str) -> Result<UpgradeResult, UpgradeError> {
196 rewrite(text, |frontmatter, notes| {
197 convert_pre_v1(frontmatter, kind, notes);
198 crate::set_aside::set_aside_rejected_keys(
199 frontmatter,
200 kind,
201 crate::set_aside::Destination::Nowhere,
202 crate::set_aside::Reach::PreV1Keys,
203 notes,
204 );
205 })
206}
207
208fn rewrite(
211 text: &str,
212 apply: impl FnOnce(&mut Frontmatter, &mut Vec<SchemaDiagnostic>),
213) -> Result<UpgradeResult, UpgradeError> {
214 let original = Frontmatter::parse(text)?;
215 let mut frontmatter = original.clone();
216 let mut diagnostics = Vec::new();
217 apply(&mut frontmatter, &mut diagnostics);
218 if frontmatter.mapping() == original.mapping() {
219 return Ok(UpgradeResult {
220 text: text.to_string(),
221 diagnostics,
222 fully_rewritten: false,
223 edited_paths: Vec::new(),
224 });
225 }
226
227 let edited_paths = changed_mapping_paths(original.mapping(), frontmatter.mapping());
228
229 let fallback = {
233 let mut rewritten = with_line_ending_of(text, frontmatter.render_frontmatter());
234 rewritten.push_str(original.body());
235 rewritten
236 };
237 let minimally_edited = edit_top_level_blocks(text, original.mapping(), frontmatter.mapping())
238 .and_then(|edited| {
239 Frontmatter::parse(&edited.text)
240 .ok()
241 .filter(|parsed| parsed.mapping() == frontmatter.mapping())
242 .map(|_| edited)
243 });
244 Ok(UpgradeResult {
245 fully_rewritten: minimally_edited
246 .as_ref()
247 .is_none_or(|edited| edited.re_rendered),
248 text: minimally_edited.map_or(fallback, |edited| edited.text),
249 diagnostics,
250 edited_paths,
251 })
252}
253
254pub fn upgrade_manifest(text: &str) -> Result<UpgradeResult, UpgradeError> {
260 let mut document = text.parse::<DocumentMut>()?;
261 let package = document
262 .get_mut("package")
263 .and_then(Item::as_table_mut)
264 .ok_or(UpgradeError::MissingPackage)?;
265 let mut diagnostics = Vec::new();
266 let mut edited_paths = Vec::new();
267 if package.get("schema").and_then(Item::as_integer) != Some(1) {
268 if package.contains_key("tools") {
269 return Err(UpgradeError::PackageToolsNeedSchema);
270 }
271 package.insert("schema", toml_edit::value(1));
272 edited_paths.push(package_path("schema"));
273 }
274 for &key in PRE_V1.package_dropped {
275 if package.remove(key).is_some() {
276 diagnostics.push(removed(&["package", key], key));
277 edited_paths.push(package_path(key));
278 }
279 }
280 if edited_paths.is_empty() {
281 return Ok(UpgradeResult {
282 text: text.to_string(),
283 diagnostics,
284 fully_rewritten: false,
285 edited_paths,
286 });
287 }
288 Ok(UpgradeResult {
289 text: with_line_ending_of(text, document.to_string()),
290 diagnostics,
291 fully_rewritten: false,
292 edited_paths,
293 })
294}
295
296#[derive(Debug, Clone, PartialEq, Eq)]
298pub struct FloorOutcome {
299 pub text: String,
301 pub warning: Option<String>,
304}
305
306pub fn ensure_requires_mars_floor(
316 text: &str,
317 floor: Option<&keys::Floor>,
318) -> Result<FloorOutcome, UpgradeError> {
319 let mut document = text.parse::<DocumentMut>()?;
320 let package = document
321 .get_mut("package")
322 .ok_or(UpgradeError::MissingPackage)?;
323 let Some(floor) = floor else {
324 return Ok(FloorOutcome {
325 text: text.to_string(),
326 warning: None,
327 });
328 };
329 let requirement = package
330 .as_table_like()
331 .and_then(|table| table.get("requires-mars"))
332 .and_then(Item::as_str)
333 .map(str::to_owned);
334 if requirement.is_none()
335 && let Some(table) = package.as_table_mut()
336 {
337 table.insert("requires-mars", toml_edit::value(floor.requirement()));
338 return Ok(FloorOutcome {
339 text: with_line_ending_of(text, document.to_string()),
340 warning: None,
341 });
342 }
343 Ok(FloorOutcome {
344 text: text.to_string(),
345 warning: crate::package::requires_mars_shortfall(requirement.as_deref(), floor),
346 })
347}
348
349fn package_path(key: &str) -> Vec<PathSegment> {
350 vec![
351 PathSegment::Key("package".to_string()),
352 PathSegment::Key(key.to_string()),
353 ]
354}
355
356fn is_crlf(text: &str) -> bool {
358 text.find('\n')
359 .is_some_and(|end| text.as_bytes()[..end].ends_with(b"\r"))
360}
361
362fn with_line_ending_of(original: &str, written: String) -> String {
364 if !is_crlf(original) {
365 return written;
366 }
367 let mut out = String::with_capacity(written.len() + written.len() / 16);
368 let mut previous = '\0';
369 for character in written.chars() {
370 if character == '\n' && previous != '\r' {
371 out.push('\r');
372 }
373 out.push(character);
374 previous = character;
375 }
376 out
377}
378
379fn changed_mapping_paths(before: &Mapping, after: &Mapping) -> Vec<Vec<PathSegment>> {
380 let mut keys = before
381 .keys()
382 .chain(after.keys())
383 .filter_map(Value::as_str)
384 .collect::<Vec<_>>();
385 keys.sort_unstable();
386 keys.dedup();
387 keys.into_iter()
388 .filter(|key| {
389 let key = Value::String((*key).to_string());
390 before.get(&key) != after.get(&key)
391 })
392 .map(|key| vec![PathSegment::Key(key.to_string())])
393 .collect()
394}
395
396#[derive(Debug)]
397struct SourceBlock<'a> {
398 key: &'a str,
399 text: &'a str,
400 key_end: usize,
401 start: usize,
402}
403
404struct Edited {
407 text: String,
408 re_rendered: bool,
409}
410
411fn edit_top_level_blocks(text: &str, before: &Mapping, after: &Mapping) -> Option<Edited> {
414 let (prefix, yaml, suffix) = frontmatter_source(text)?;
415 let blocks = source_blocks(yaml)?;
416 let before_keys = before
417 .keys()
418 .map(Value::as_str)
419 .collect::<Option<Vec<_>>>()?;
420 if blocks.iter().map(|block| block.key).collect::<Vec<_>>() != before_keys {
421 return None;
422 }
423
424 let render = |key: &str, value: &Value| with_line_ending_of(text, render_block(key, value));
425 let mut output = String::with_capacity(text.len());
426 let mut re_rendered = false;
427 output.push_str(prefix);
428 let first_key_offset = blocks.first().map_or(yaml.len(), |block| block.start);
429 output.push_str(&yaml[..first_key_offset]);
430
431 let mut emitted = Vec::new();
432 for block in blocks {
433 let before_value = before.get(Value::String(block.key.to_string()))?;
434 if let Some(rename) = renamed_key(block.key, before, after) {
435 output.push_str(rename);
436 output.push_str(&block.text[block.key_end..]);
437 emitted.push(rename);
438 } else if let Some(after_value) = after.get(Value::String(block.key.to_string())) {
439 if before_value == after_value {
440 output.push_str(block.text);
441 } else if let Some(edited) = grown_in_place(&block, before_value, after_value)
442 .or_else(|| renamed_in_place(&block, before_value, after_value))
443 {
444 output.push_str(&edited);
445 } else {
446 re_rendered |= block.key == "harness-overrides";
450 output.push_str(&render(block.key, after_value));
451 }
452 emitted.push(block.key);
453 }
454 }
455
456 for (key, value) in after {
457 let key = key.as_str()?;
458 if emitted.contains(&key) {
459 continue;
460 }
461 if !output.ends_with('\n') {
462 output.push_str(&with_line_ending_of(text, "\n".to_owned()));
463 }
464 output.push_str(&render(key, value));
465 }
466 output.push_str(suffix);
467 Some(Edited {
468 text: output,
469 re_rendered,
470 })
471}
472
473fn grown_in_place(block: &SourceBlock<'_>, before: &Value, after: &Value) -> Option<String> {
477 let (Value::Mapping(before), Value::Mapping(after)) = (before, after) else {
478 return None;
479 };
480 if before
481 .iter()
482 .any(|(key, value)| after.get(key) != Some(value))
483 {
484 return None;
485 }
486 let added = after
487 .iter()
488 .filter(|(key, _)| before.get(key).is_none())
489 .collect::<Vec<_>>();
490 let indent = (!added.is_empty()).then(|| child_indent(block)).flatten()?;
491 let (body, tail) = split_trailing_run(block.text);
494 let mut grown = body.to_string();
495 if !grown.ends_with('\n') {
496 grown.push('\n');
497 }
498 for (key, value) in added {
499 let rendered = render_block(key.as_str()?, value);
500 let indented = rendered
502 .lines()
503 .map(|line| {
504 let depth = line.len() - line.trim_start().len();
505 format!("{}{}", indent.repeat(depth / 2 + 1), line.trim_start())
506 })
507 .collect::<Vec<_>>()
508 .join("\n");
509 grown.push_str(&indented);
510 grown.push('\n');
511 }
512 grown.push_str(tail);
513 Some(with_line_ending_of(block.text, grown))
514}
515
516fn renamed_in_place(block: &SourceBlock<'_>, before: &Value, after: &Value) -> Option<String> {
520 let (Value::Mapping(before), Value::Mapping(after)) = (before, after) else {
521 return None;
522 };
523 if before.len() != after.len() {
524 return None;
525 }
526 let mut renames = Vec::new();
527 for ((old, old_value), (new, new_value)) in before.iter().zip(after) {
528 if old_value != new_value {
529 return None;
530 }
531 if old != new {
532 let pair = (old.as_str()?, new.as_str()?);
533 if !PRE_V1.namespaces.contains(&pair) {
534 return None;
535 }
536 renames.push(pair);
537 }
538 }
539 let indent = child_indent(block)?;
540 let mut done = 0;
541 let mut edited = String::with_capacity(block.text.len());
542 for line in block.text.split_inclusive('\n') {
543 let renamed = line.strip_prefix(indent).and_then(|rest| {
544 renames.iter().find_map(|&(old, new)| {
545 let after_key = rest.strip_prefix(old)?;
546 after_key
547 .trim_start_matches(' ')
548 .starts_with(':')
549 .then(|| format!("{indent}{new}{after_key}"))
550 })
551 });
552 match renamed {
553 Some(line) => {
554 done += 1;
555 edited.push_str(&line);
556 }
557 None => edited.push_str(line),
558 }
559 }
560 (done == renames.len()).then_some(edited)
561}
562
563fn split_trailing_run(text: &str) -> (&str, &str) {
566 let mut split = text.len();
567 for line in text.split_inclusive('\n').rev() {
568 let content = line.trim_end_matches(['\r', '\n']);
569 if !content.trim().is_empty() && !content.starts_with('#') {
570 break;
571 }
572 split -= line.len();
573 }
574 text.split_at(split)
575}
576
577fn child_indent<'a>(block: &'a SourceBlock<'a>) -> Option<&'a str> {
580 let first = block.text.split_inclusive('\n').next()?;
581 let rest = first[block.key_end + 1..].trim_end_matches(['\r', '\n']);
582 if !(rest.trim().is_empty() || rest.trim_start().starts_with('#')) {
583 return None;
584 }
585 for line in block.text.split_inclusive('\n').skip(1) {
586 let content = line.trim_end_matches(['\r', '\n']);
587 if content.trim().is_empty() || content.trim_start().starts_with('#') {
588 continue;
589 }
590 let indent = content.len() - content.trim_start().len();
591 return (indent > 0).then(|| &content[..indent]);
592 }
593 None
594}
595
596fn renamed_key<'a>(old: &str, before: &Mapping, after: &'a Mapping) -> Option<&'a str> {
597 let new = PRE_V1
598 .renamed
599 .iter()
600 .find_map(|&(known, new)| (known == old).then_some(new))?;
601 if before.contains_key(Value::String(new.to_string())) {
602 return None;
603 }
604 let old_value = before.get(Value::String(old.to_string()))?;
605 (after.get(Value::String(new.to_string())) == Some(old_value)).then_some(new)
606}
607
608fn render_block(key: &str, value: &Value) -> String {
609 let mut mapping = Mapping::new();
610 mapping.insert(Value::String(key.to_string()), value.clone());
611 let yaml = serde_yaml::to_string(&mapping).expect("serializing an upgraded YAML block");
612 yaml.strip_prefix("---\n").unwrap_or(&yaml).to_string()
613}
614
615fn frontmatter_source(text: &str) -> Option<(&str, &str, &str)> {
616 let first_end = text.find('\n').map_or(text.len(), |offset| offset + 1);
617 if text[..first_end]
618 .strip_prefix('\u{feff}')
619 .unwrap_or(&text[..first_end])
620 .trim_end()
621 != "---"
622 {
623 return None;
624 }
625 let mut offset = first_end;
626 for line in text[first_end..].split_inclusive('\n') {
627 if line.trim_end() == "---" {
628 return Some((
629 &text[..first_end],
630 &text[first_end..offset],
631 &text[offset..],
632 ));
633 }
634 offset += line.len();
635 }
636 None
637}
638
639fn source_blocks(yaml: &str) -> Option<Vec<SourceBlock<'_>>> {
640 let mut starts = Vec::new();
641 let mut offset = 0;
642 for line in yaml.split_inclusive('\n') {
643 let content = line.trim_end_matches(['\r', '\n']);
644 if !content.is_empty()
645 && !content.starts_with(char::is_whitespace)
646 && !content.starts_with('#')
647 {
648 let colon = content.find(':')?;
649 let key = &content[..colon];
650 if key.is_empty()
651 || !key
652 .bytes()
653 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
654 {
655 return None;
656 }
657 starts.push((offset, key, colon));
658 }
659 offset += line.len();
660 }
661 let mut blocks = Vec::with_capacity(starts.len());
662 for (index, (start, key, key_end)) in starts.iter().copied().enumerate() {
663 let end = starts
664 .get(index + 1)
665 .map_or(yaml.len(), |(start, _, _)| *start);
666 blocks.push(SourceBlock {
667 key,
668 text: &yaml[start..end],
669 key_end,
670 start,
671 });
672 }
673 Some(blocks)
674}
675
676pub(crate) fn lift_mars_only_keys(
683 fm: &mut Frontmatter,
684 kind: DefinitionKind,
685 notes: &mut Vec<SchemaDiagnostic>,
686) -> bool {
687 let before = fm.mapping().clone();
688 for &(old, new) in PRE_V1.renamed {
689 rename_invocability(fm, old, new, notes);
690 }
691 if kind == DefinitionKind::Agent {
692 for &(old, new) in PRE_V1.agent_host_sets {
693 merge_host_set_spellings(fm, old, new);
694 }
695 for &key in PRE_V1.agent_dropped {
696 if fm.remove(key).is_some() {
697 notes.push(removed(&[key], key));
698 }
699 }
700 for &(key, old, new) in PRE_V1.agent_values {
701 replace_scalar(fm, key, old, new);
702 }
703 move_agent_fields(fm, notes);
704 strip_model_policy_overrides(fm, notes);
705 }
706 fm.mapping() != &before
707}
708
709fn convert_pre_v1(fm: &mut Frontmatter, kind: DefinitionKind, notes: &mut Vec<SchemaDiagnostic>) {
711 rename_consumer_namespaces(fm, notes);
714 match kind {
715 DefinitionKind::Agent => {
716 fold_deny_lists(fm);
717 lift_mars_only_keys(fm, kind, notes);
718 move_map_fields(fm, notes);
719 }
720 DefinitionKind::Skill => {
721 lift_mars_only_keys(fm, kind, notes);
722 for &(_, fold) in PRE_V1.skill_folded {
723 fold(fm, notes);
724 }
725 for &key in PRE_V1.skill_dropped {
726 if fm.remove(key).is_some() {
727 notes.push(removed(&[key], key));
728 }
729 }
730 for key in crate::skill::tool_keys() {
731 if fm.remove(key).is_some() {
732 notes.push(SchemaDiagnostic::new(
733 "skill.tools-dropped",
734 Severity::Warning,
735 vec![PathSegment::Key(key.to_string())],
736 format!("removed skill key `{key}`; skill tool rules have no v1 meaning"),
737 ));
738 }
739 }
740 }
741 }
742}
743
744fn upgrade_agent(fm: &mut Frontmatter, diagnostics: &mut Vec<SchemaDiagnostic>) {
745 tools_list_to_allow(fm);
748 convert_pre_v1(fm, DefinitionKind::Agent, diagnostics);
749 claude::translate::move_to_claude_overrides(fm, DefinitionKind::Agent, diagnostics);
751 set_aside_rejected_keys(fm, DefinitionKind::Agent, diagnostics);
752}
753
754fn upgrade_skill(fm: &mut Frontmatter, diagnostics: &mut Vec<SchemaDiagnostic>) {
755 convert_pre_v1(fm, DefinitionKind::Skill, diagnostics);
756 claude::translate::move_to_claude_overrides(fm, DefinitionKind::Skill, diagnostics);
757 set_aside_rejected_keys(fm, DefinitionKind::Skill, diagnostics);
758}
759
760fn fold_type(fm: &mut Frontmatter, _notes: &mut Vec<SchemaDiagnostic>) -> bool {
762 let Some(skill_type) = fm.get("type").cloned() else {
763 return false;
764 };
765 let metadata = fm
766 .get("metadata")
767 .cloned()
768 .unwrap_or_else(|| Value::Mapping(Mapping::new()));
769 let Value::Mapping(mut metadata) = metadata else {
770 return false;
771 };
772 let key = Value::String("type".to_string());
773 if metadata.contains_key(&key) {
774 return false;
775 }
776 metadata.insert(key, skill_type);
777 fm.insert("metadata", Value::Mapping(metadata));
778 fm.remove("type");
779 true
780}
781
782fn fold_when_to_use(fm: &mut Frontmatter, _notes: &mut Vec<SchemaDiagnostic>) -> bool {
784 let Some(when) = fm
785 .get("when_to_use")
786 .and_then(Value::as_str)
787 .map(str::to_owned)
788 else {
789 return false;
790 };
791 let description = match fm.get("description") {
792 Some(Value::String(description)) => format!("{description}\n\n{when}"),
793 None => when,
794 Some(_) => return false,
795 };
796 fm.insert("description", Value::String(description));
797 fm.remove("when_to_use");
798 true
799}
800
801pub(crate) fn fold_disable_model_invocation(
805 fm: &mut Frontmatter,
806 notes: &mut Vec<SchemaDiagnostic>,
807) -> bool {
808 let Some(disable) = fm.remove("disable-model-invocation") else {
809 return false;
810 };
811 if disable.as_bool() != Some(true) {
812 return true;
813 }
814 match crate::invocability::find_invocability_field(fm, "model-invocable") {
815 None => fm.insert("model-invocable", Value::Bool(false)),
816 Some(field) if field.value == Value::Bool(true) => {
817 fm.insert(&field.consumed_key, Value::Bool(false));
818 notes.push(conflicting_duplicate(
819 "disable-model-invocation",
820 &disable,
821 &field.consumed_key,
822 &field.value,
823 ));
824 }
825 Some(_) => {}
826 }
827 true
828}
829
830fn set_aside_rejected_keys(
835 fm: &mut Frontmatter,
836 kind: DefinitionKind,
837 diagnostics: &mut Vec<SchemaDiagnostic>,
838) {
839 crate::set_aside::set_aside_rejected_keys(
840 fm,
841 kind,
842 crate::set_aside::Destination::Nowhere,
843 crate::set_aside::Reach::Everything,
844 diagnostics,
845 );
846}
847
848fn tools_list_to_allow(fm: &mut Frontmatter) {
850 if let Some(Value::Sequence(entries)) = fm.get("tools").cloned()
851 && entries.iter().all(|entry| entry.as_str().is_some())
852 {
853 let policy = entries
854 .into_iter()
855 .map(|entry| (entry, Value::String("allow".to_string())))
856 .collect();
857 fm.insert("tools", Value::Mapping(policy));
858 }
859}
860
861fn fold_deny_lists(fm: &mut Frontmatter) {
864 for key in tool_policy::DISALLOWED_SPELLINGS {
865 let Some(Value::Sequence(disallowed)) = fm.get(key).cloned() else {
866 continue;
867 };
868 if !disallowed.iter().all(|entry| entry.as_str().is_some()) {
869 continue;
870 }
871 let Value::Mapping(mut policy) = fm
872 .get("tools")
873 .cloned()
874 .unwrap_or_else(|| Value::Mapping(Mapping::new()))
875 else {
876 return;
877 };
878 for entry in disallowed {
879 policy.insert(entry, Value::String("deny".to_string()));
880 }
881 fm.insert("tools", Value::Mapping(policy));
882 fm.remove(key);
883 }
884}
885
886fn moves_under_namespace(fm: &Frontmatter, key: &str) -> bool {
889 key != "permission"
890 || fm
891 .get(key)
892 .and_then(Value::as_str)
893 .is_some_and(|permission| matches!(permission, "read" | "edit"))
894}
895
896fn move_agent_fields(fm: &mut Frontmatter, notes: &mut Vec<SchemaDiagnostic>) {
900 for &(namespace, from, to) in PRE_V1.agent_moved {
901 if moves_under_namespace(fm, from) {
902 move_one(fm, namespace, from, to, notes);
903 }
904 }
905}
906
907fn move_map_fields(fm: &mut Frontmatter, notes: &mut Vec<SchemaDiagnostic>) {
909 for &(namespace, key) in PRE_V1.agent_moved_maps {
910 if matches!(fm.get(key), Some(Value::Mapping(_))) {
911 move_one(fm, namespace, key, key, notes);
912 }
913 }
914}
915
916fn move_one(
917 fm: &mut Frontmatter,
918 namespace: &str,
919 from: &str,
920 to: &str,
921 notes: &mut Vec<SchemaDiagnostic>,
922) {
923 if let Moved::Done { displaced, .. } = move_keys_under(fm, namespace, &[(from, to)])
924 && !displaced.is_empty()
925 {
926 notes.push(dropped_twin(
927 &agent_label(fm),
928 vec![PathSegment::Key(from.to_string())],
929 from,
930 namespace,
931 to,
932 ));
933 }
934}
935
936fn rename_consumer_namespaces(fm: &mut Frontmatter, notes: &mut Vec<SchemaDiagnostic>) {
940 let agent = agent_label(fm);
941 let Some(Value::Mapping(overrides)) = fm.get_mut("harness-overrides") else {
942 return;
943 };
944 for &(old, new) in PRE_V1.namespaces {
945 let old_key = Value::String(old.to_string());
946 let new_key = Value::String(new.to_string());
947 let Some(old_block) = overrides.get(&old_key).cloned() else {
948 continue;
949 };
950 let block_path = vec![
951 PathSegment::Key("harness-overrides".to_string()),
952 PathSegment::Key(old.to_string()),
953 ];
954 let Some(new_block) = overrides.get_mut(&new_key) else {
955 *overrides = std::mem::take(overrides)
957 .into_iter()
958 .map(|(key, value)| {
959 if key == old_key {
960 (new_key.clone(), value)
961 } else {
962 (key, value)
963 }
964 })
965 .collect();
966 continue;
967 };
968 match (new_block, old_block) {
969 (Value::Mapping(new_block), Value::Mapping(old_block)) => {
970 let twin = Twin {
971 agent: &agent,
972 old,
973 new,
974 };
975 merge_old_block(new_block, old_block, &twin, &[], notes);
976 }
977 _ => notes.push(SchemaDiagnostic::new(
978 "field.removed",
979 Severity::Warning,
980 block_path,
981 format!(
982 "dropped `harness-overrides.{old}`; `harness-overrides.{new}` already sets it"
983 ),
984 )),
985 }
986 overrides.remove(&old_key);
987 }
988}
989
990fn agent_label(fm: &Frontmatter) -> String {
991 fm.get("name").and_then(Value::as_str).map_or_else(
992 || "this agent".to_string(),
993 |name| format!("agent `{name}`"),
994 )
995}
996
997struct Twin<'a> {
999 agent: &'a str,
1000 old: &'a str,
1001 new: &'a str,
1002}
1003
1004fn merge_old_block(
1008 new: &mut Mapping,
1009 old: Mapping,
1010 twin: &Twin,
1011 rel: &[String],
1012 notes: &mut Vec<SchemaDiagnostic>,
1013) {
1014 for (key, value) in old {
1015 let name = key
1016 .as_str()
1017 .map_or_else(|| format!("{key:?}"), str::to_owned);
1018 let mut key_rel = rel.to_vec();
1019 key_rel.push(name);
1020 match new.get_mut(&key) {
1021 None => {
1022 new.insert(key, value);
1023 }
1024 Some(existing) if *existing == value => {}
1025 Some(Value::Mapping(existing)) if value.is_mapping() => {
1026 let Value::Mapping(value) = value else {
1027 unreachable!()
1028 };
1029 merge_old_block(existing, value, twin, &key_rel, notes);
1030 }
1031 Some(_) => {
1032 let dotted = key_rel.join(".");
1033 let mut path = vec![
1034 PathSegment::Key("harness-overrides".to_string()),
1035 PathSegment::Key(twin.old.to_string()),
1036 ];
1037 path.extend(key_rel.into_iter().map(PathSegment::Key));
1038 let dropped = format!("harness-overrides.{}.{dotted}", twin.old);
1039 notes.push(dropped_twin(twin.agent, path, &dropped, twin.new, &dotted));
1040 }
1041 }
1042 }
1043}
1044
1045fn dropped_twin(
1050 agent: &str,
1051 path: Vec<PathSegment>,
1052 dropped: &str,
1053 namespace: &str,
1054 key: &str,
1055) -> SchemaDiagnostic {
1056 if key == "permission" || key == "capabilities" || key.starts_with("capabilities.") {
1057 return SchemaDiagnostic::new(
1058 crate::set_aside::RESTRICTION_LOST,
1059 Severity::Warning,
1060 path,
1061 format!(
1062 "{agent} lost the restriction `{key}`: it was dropped, because \
1063 `harness-overrides.{namespace}.{key}` already sets a value, and an override \
1064 written wins"
1065 ),
1066 );
1067 }
1068 SchemaDiagnostic::new(
1069 "field.removed",
1070 Severity::Warning,
1071 path,
1072 format!("dropped `{dropped}`; `harness-overrides.{namespace}.{key}` already sets it"),
1073 )
1074}
1075
1076fn strip_model_policy_overrides(fm: &mut Frontmatter, diagnostics: &mut Vec<SchemaDiagnostic>) {
1077 let Some(Value::Sequence(policies)) = fm.get_mut("model-policies") else {
1078 return;
1079 };
1080 for (index, policy) in policies.iter_mut().enumerate() {
1081 let Value::Mapping(policy) = policy else {
1082 continue;
1083 };
1084 let Some(Value::Mapping(overrides)) = policy.get_mut(Value::String("override".to_string()))
1085 else {
1086 continue;
1087 };
1088 for &(key, old, new) in PRE_V1.agent_values {
1090 let key = Value::String(key.to_string());
1091 if overrides.get(&key).and_then(Value::as_str) == Some(old) {
1092 overrides.insert(key, Value::String(new.to_string()));
1093 }
1094 }
1095 for &key in PRE_V1.policy_override_dropped {
1096 if overrides.remove(Value::String(key.to_string())).is_some() {
1097 diagnostics.push(SchemaDiagnostic::new(
1098 "field.removed",
1099 Severity::Warning,
1100 vec![
1101 PathSegment::Key("model-policies".to_string()),
1102 PathSegment::Index(index),
1103 PathSegment::Key("override".to_string()),
1104 PathSegment::Key(key.to_string()),
1105 ],
1106 format!("removed model policy override key `{key}`"),
1107 ));
1108 }
1109 }
1110 }
1111}
1112
1113fn rename_field(fm: &mut Frontmatter, old: &str, new: &str) {
1114 let Some(value) = fm.remove(old) else {
1115 return;
1116 };
1117 if fm.get(new).is_none() {
1118 fm.insert(new, value);
1119 }
1120}
1121
1122fn rename_invocability(
1125 fm: &mut Frontmatter,
1126 old: &str,
1127 new: &str,
1128 notes: &mut Vec<SchemaDiagnostic>,
1129) {
1130 let (Some(old_value), Some(new_value)) = (fm.get(old).cloned(), fm.get(new).cloned()) else {
1131 return rename_field(fm, old, new);
1132 };
1133 fm.remove(old);
1134 if old_value != new_value
1135 && (old_value == Value::Bool(false) || new_value == Value::Bool(false))
1136 {
1137 fm.insert(new, Value::Bool(false));
1138 notes.push(conflicting_duplicate(old, &old_value, new, &new_value));
1139 }
1140}
1141
1142fn conflicting_duplicate(
1144 first: &str,
1145 first_value: &Value,
1146 second: &str,
1147 second_value: &Value,
1148) -> SchemaDiagnostic {
1149 SchemaDiagnostic::new(
1150 "field.removed",
1151 Severity::Warning,
1152 vec![PathSegment::Key(first.to_string())],
1153 format!(
1154 "`{first}: {}` conflicts with `{second}: {}`; kept `false`, the value that restricts",
1155 crate::ordered::plain(first_value),
1156 crate::ordered::plain(second_value),
1157 ),
1158 )
1159}
1160
1161fn merge_host_set_spellings(fm: &mut Frontmatter, old: &str, new: &str) {
1165 let (Some(old_value), Some(new_value)) = (fm.get(old), fm.get(new)) else {
1166 return rename_field(fm, old, new);
1167 };
1168 let (Some((old_hosts, old_replaces)), Some((mut hosts, new_replaces))) =
1169 (host_set_parts(old_value), host_set_parts(new_value))
1170 else {
1171 return;
1172 };
1173 for host in old_hosts {
1174 if !hosts.contains(&host) {
1175 hosts.push(host);
1176 }
1177 }
1178 let merged = if old_replaces || new_replaces {
1179 let mut replace = serde_yaml::Mapping::new();
1180 replace.insert(Value::String("replace".to_string()), Value::Sequence(hosts));
1181 Value::Mapping(replace)
1182 } else {
1183 Value::Sequence(hosts)
1184 };
1185 fm.insert(new, merged);
1186 fm.remove(old);
1187}
1188
1189fn host_set_parts(value: &Value) -> Option<(Vec<Value>, bool)> {
1190 match value {
1191 Value::Sequence(hosts) => Some((hosts.clone(), false)),
1192 Value::Mapping(map) if map.len() == 1 => map
1193 .get("replace")
1194 .and_then(Value::as_sequence)
1195 .map(|hosts| (hosts.clone(), true)),
1196 _ => None,
1197 }
1198}
1199
1200fn replace_scalar(fm: &mut Frontmatter, key: &str, old: &str, new: &str) {
1201 if fm.get(key).and_then(Value::as_str) == Some(old) {
1202 fm.insert(key, Value::String(new.to_string()));
1203 }
1204}
1205
1206fn removed(path: &[&str], key: &str) -> SchemaDiagnostic {
1207 SchemaDiagnostic::new(
1208 "field.removed",
1209 Severity::Warning,
1210 path.iter()
1211 .map(|part| PathSegment::Key((*part).to_string()))
1212 .collect(),
1213 format!("removed legacy key `{key}`"),
1214 )
1215}
1216
1217#[cfg(test)]
1218mod tests {
1219 use super::*;
1220
1221 fn sample_value(key: &str) -> &'static str {
1223 match key {
1224 "permission" => "read",
1225 "resident-rearm-budget" => "3",
1226 "meridian-capabilities" => "{spawn: true}",
1227 "network_allow" | "network_deny" => "[example.com]",
1228 _ if tool_policy::DISALLOWED_SPELLINGS.contains(&key) => "[Bash]",
1229 _ => "x",
1230 }
1231 }
1232
1233 fn rows() -> Vec<(String, &'static str, String)> {
1235 const AGENT: &str = "agents/a.md";
1236 const SKILL: &str = "skills/s/SKILL.md";
1237 let agent = |field: String| format!("---\nname: a\ndescription: d\n{field}\n---\nbody\n");
1238 let skill = |field: String| format!("---\nname: s\ndescription: d\n{field}\n---\nbody\n");
1239 let line = |key: &str| format!("{key}: {}", sample_value(key));
1240 let mut rows = Vec::new();
1241 for key in PRE_V1.agent_dropped {
1242 rows.push((format!("agent_dropped {key}"), AGENT, agent(line(key))));
1243 }
1244 for (key, _) in PRE_V1.renamed {
1245 rows.push((
1246 format!("renamed {key}"),
1247 AGENT,
1248 agent(format!("{key}: true")),
1249 ));
1250 rows.push((
1251 format!("renamed {key}"),
1252 SKILL,
1253 skill(format!("{key}: true")),
1254 ));
1255 }
1256 for (key, _) in PRE_V1.agent_host_sets {
1257 rows.push((format!("agent_host_sets {key}"), AGENT, agent(line(key))));
1258 }
1259 for key in tool_policy::DISALLOWED_SPELLINGS {
1260 rows.push((format!("disallowed {key}"), AGENT, agent(line(key))));
1261 }
1262 for (_, key, _) in PRE_V1.agent_moved {
1263 rows.push((format!("agent_moved {key}"), AGENT, agent(line(key))));
1264 }
1265 for (namespace, key) in PRE_V1.agent_moved_maps {
1266 rows.push((
1267 format!("agent_moved_maps {namespace} {key}"),
1268 AGENT,
1269 agent(format!("{key}: {{bash: deny}}")),
1270 ));
1271 }
1272 for (key, old, _) in PRE_V1.agent_values {
1273 let policy = format!(
1274 "model-policies:\n - match: {{alias: fast}}\n override:\n {key}: {old}"
1275 );
1276 rows.push((
1277 format!("agent_values {key}: {old}"),
1278 AGENT,
1279 agent(format!("{key}: {old}")),
1280 ));
1281 rows.push((
1282 format!("agent_values {key}: {old} in a policy override"),
1283 AGENT,
1284 agent(policy),
1285 ));
1286 }
1287 for key in crate::skill::tool_keys() {
1288 rows.push((format!("skill tool {key}"), SKILL, skill(line(key))));
1289 }
1290 for (key, _) in PRE_V1.skill_folded {
1291 rows.push((format!("skill_folded {key}"), SKILL, skill(line(key))));
1292 }
1293 for key in PRE_V1.skill_dropped {
1294 rows.push((format!("skill_dropped {key}"), SKILL, skill(line(key))));
1295 }
1296 for key in PRE_V1.policy_override_dropped {
1297 let policy = format!(
1298 "model-policies:\n - match: {{alias: fast}}\n override:\n effort: low\n {key}: {}",
1299 sample_value(key)
1300 );
1301 rows.push((
1302 format!("policy_override_dropped {key}"),
1303 AGENT,
1304 agent(policy),
1305 ));
1306 }
1307 for (old, _) in PRE_V1.namespaces {
1308 let overrides = format!("harness-overrides:\n {old}:\n permission: read");
1309 rows.push((format!("namespaces {old}"), AGENT, agent(overrides)));
1310 }
1311 for key in PRE_V1.package_dropped {
1312 let manifest = format!(
1313 "[package]\nname = \"p\"\nversion = \"0.1.0\"\nschema = 1\n{key} = \"x\"\n"
1314 );
1315 rows.push((format!("package_dropped {key}"), "mars.toml", manifest));
1316 }
1317 rows
1318 }
1319
1320 fn migrate_with_notes(path: &str, text: &str) -> UpgradeResult {
1321 match path {
1322 "mars.toml" => upgrade_manifest(text).unwrap(),
1323 "agents/a.md" => migrate_definition(DefinitionKind::Agent, text).unwrap(),
1324 _ => migrate_definition(DefinitionKind::Skill, text).unwrap(),
1325 }
1326 }
1327
1328 fn migrate(path: &str, text: &str) -> String {
1329 migrate_with_notes(path, text).text
1330 }
1331
1332 fn errors(path: &str, text: &str) -> Vec<String> {
1333 crate::read::read(path, text)
1334 .unwrap()
1335 .diagnostics()
1336 .iter()
1337 .filter(|diagnostic| diagnostic.is_error())
1338 .map(|diagnostic| format!("{}: {}", diagnostic.code, diagnostic.message()))
1339 .collect()
1340 }
1341
1342 #[test]
1345 fn the_reader_refuses_what_migrate_converts() {
1346 for (row, path, text) in rows() {
1347 let refused = errors(path, &text);
1348 assert!(!refused.is_empty(), "{row}: the reader accepts\n{text}");
1349 for error in &refused {
1350 assert!(
1351 error.starts_with("field.removed: ")
1352 && error.ends_with("; `mars migrate` upgrades this file")
1353 && (error.contains(" is a pre-v1 key;")
1354 || error.contains(" is a pre-v1 value;")),
1355 "{row}: the reader refuses it for another reason: {error}"
1356 );
1357 }
1358 let result = migrate_with_notes(path, &text);
1359 let migrated = result.text.clone();
1360 assert_ne!(migrated, text, "{row}: migrate leaves the file as it is");
1361 assert!(
1364 result
1365 .diagnostics
1366 .iter()
1367 .all(|note| note.code != crate::set_aside::RESTRICTION_LOST),
1368 "{row}: migrate drops a restriction: {:?}",
1369 result.diagnostics
1370 );
1371 assert_eq!(
1372 errors(path, &migrated),
1373 Vec::<String>::new(),
1374 "{row}: still refused after migrate\n{migrated}"
1375 );
1376 assert_eq!(migrate(path, &migrated), migrated, "{row}: not idempotent");
1377 }
1378 }
1379
1380 #[test]
1383 fn migrate_leaves_a_file_without_a_pre_v1_key() {
1384 let agent = "---\nname: a\ndescription: d\nmodel: opus\ncolor: red\ntools:\n read: allow\n bash: deny\nharness-overrides:\n claude:\n x: 1\nsandbox: bogus\n---\nbody\n";
1385 assert_eq!(migrate("agents/a.md", agent), agent);
1386 let list = "---\nname: a\ndescription: d\ntools: [Read, Grep]\nmodel-policies:\n - match: {alias: fast}\n override:\n approval: never\n effort: low\n---\nbody\n";
1389 assert_eq!(migrate("agents/a.md", list), list);
1390 assert!(
1391 errors("agents/a.md", list)
1392 .iter()
1393 .all(|error| error.starts_with("tools.list-form: "))
1394 );
1395 let skill = "---\nname: s\ndescription: d\nmodel-invocable: false\ncolor: red\n---\nbody\n";
1396 assert_eq!(migrate("skills/s/SKILL.md", skill), skill);
1397 let manifest = "[package]\nname = \"p\"\nversion = \"0.1.0\"\nschema = 1\nfuture = 1\n";
1398 assert_eq!(migrate("mars.toml", manifest), manifest);
1399 }
1400}