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;
const KEPT_KEYS: &[&str] = &["name", "description", "harness-overrides"];
pub(crate) const RESTRICTION_LOST: &str = "field.restriction-lost";
pub(crate) const EXECUTION_IGNORED: &str = "field.execution-ignored";
fn execution_allowed(key: &str) -> Option<&'static str> {
use crate::agent::{ApprovalMode, EffortLevel, SandboxMode};
use crate::network::NetworkPolicy;
Some(match key {
"harness" => "claude, codex, opencode, cursor, pi",
"mode" => "primary, subagent",
"effort" => EffortLevel::ALLOWED,
"approval" => ApprovalMode::ALLOWED,
"sandbox" => SandboxMode::ALLOWED,
"network" => NetworkPolicy::ALLOWED,
_ => return None,
})
}
const RESTRICTION_KEYS: &[&str] = &[
"permission",
"sandbox",
"approval",
"network",
"network-deny",
"tools",
"disallowed-tools",
];
const HOST_SET_KEYS: &[&str] = &["network-allow", "network-deny"];
#[derive(Clone, Copy)]
pub(crate) enum Destination<'a> {
Overrides(&'a str),
Nowhere,
}
impl Destination<'_> {
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::Cursor => Destination::Overrides(HarnessId::Cursor.as_str()),
Dialect::AgentSkills | Dialect::MarsNative => Destination::Nowhere,
}
}
}
struct Rejection {
path: Vec<PathSegment>,
why: String,
}
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())
}
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)
}
}
}
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<_>>();
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)
}
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,
}
}
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)),
})
}
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(),
}
}
struct Report<'a> {
agent: String,
changes: &'a mut Vec<SchemaDiagnostic>,
}
impl Report<'_> {
fn note(
&mut self,
path: &[PathSegment],
value: &Value,
lost: Option<String>,
what: &str,
why: &str,
) {
let shown = path_text(path);
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.to_owned(),
});
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}"),
),
};
self.changes.push(SchemaDiagnostic::new(
code,
Severity::Warning,
path.to_vec(),
message,
));
}
}
fn drop_policy_overrides(
fm: &mut Frontmatter,
kind: DefinitionKind,
rejections: &mut Vec<Rejection>,
report: &mut Report<'_>,
changed: &mut bool,
) {
while !rejections.is_empty()
&& rejections
.iter()
.all(|rejection| policy_override_key(&rejection.path).is_some())
{
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 = rejected_keys(kind, fm)
.into_iter()
.find(|(key, _)| key == "model-policies")
.map_or_else(Vec::new, |(_, next)| next);
}
}
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, kind, &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())];
let lost = RESTRICTION_KEYS
.contains(&key.as_str())
.then(|| format!("`{key}`"));
report.note(&path, value, lost, &what, why);
}
}
}
changed
}