Skip to main content

mars_schema/
harness.rs

1//! Stable harness identifiers and authored-name parsing.
2
3use std::fmt;
4
5use serde::{Deserialize, Serialize};
6
7use crate::agent::EffortLevel;
8use crate::tool_natives;
9
10/// Declares [`HarnessId`] and [`ALL`] from one list, so a variant cannot be left out of `ALL`.
11macro_rules! harnesses {
12    ($($(#[$meta:meta])* $variant:ident),* $(,)?) => {
13        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
14        #[serde(rename_all = "snake_case")]
15        pub enum HarnessId {
16            $($(#[$meta])* $variant),*
17        }
18
19        /// Every harness, in the order error messages list them. A new variant is added here and
20        /// to [`HarnessId::as_str`], [`Host::spec`] and the hook row (`hooks::targets::row`),
21        /// which the compiler enforces.
22        pub const ALL: &[HarnessId] = &[$(HarnessId::$variant),*];
23    };
24}
25
26harnesses! {
27    Claude,
28    Codex,
29    Pi,
30    #[serde(rename = "opencode")]
31    OpenCode,
32    Cursor,
33    Agy,
34}
35
36impl HarnessId {
37    pub const fn as_str(self) -> &'static str {
38        match self {
39            Self::Claude => "claude",
40            Self::Codex => "codex",
41            Self::Pi => "pi",
42            Self::OpenCode => "opencode",
43            Self::Cursor => "cursor",
44            Self::Agy => "agy",
45        }
46    }
47}
48
49impl HarnessId {
50    /// The harness's native directory in a project (`.claude`).
51    pub fn target_dir(self) -> String {
52        format!(".{}", self.as_str())
53    }
54
55    pub fn display_name(self) -> &'static str {
56        Host::Harness(self).spec().display_name
57    }
58}
59
60impl fmt::Display for HarnessId {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        f.write_str(self.as_str())
63    }
64}
65
66/// Where a tool policy is lowered to: a harness Mars writes files for, or Meridian Flow, which
67/// is a consumer of the result and not a harness.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum Host {
70    Harness(HarnessId),
71    MeridianFlow,
72}
73
74impl From<HarnessId> for Host {
75    fn from(harness: HarnessId) -> Self {
76        Self::Harness(harness)
77    }
78}
79
80impl Host {
81    /// Every harness in [`ALL`]'s order, then Meridian Flow.
82    pub const ALL: &'static [Host; ALL.len() + 1] = &{
83        let mut hosts = [Host::MeridianFlow; ALL.len() + 1];
84        let mut i = 0;
85        while i < ALL.len() {
86            hosts[i] = Host::Harness(ALL[i]);
87            i += 1;
88        }
89        hosts
90    };
91
92    pub const fn as_str(self) -> &'static str {
93        match self {
94            Self::Harness(harness) => harness.as_str(),
95            Self::MeridianFlow => "meridian-flow",
96        }
97    }
98
99    pub fn parse(name: &str) -> Option<Self> {
100        Self::ALL.iter().copied().find(|host| host.as_str() == name)
101    }
102}
103
104/// How a host spells an MCP ref in a tool list.
105#[derive(Clone, Copy)]
106pub(crate) enum McpNaming {
107    /// Claude's `mcp__server__tool`, which cannot scope one tool across servers.
108    Claude,
109    /// A name built from the server and tool segments.
110    Format(fn(server: &str, tool: &str) -> String),
111    /// The host has no name for an MCP tool, for the reason given.
112    NoName(&'static str),
113    /// `agy` gives every agent every MCP server whatever its tool list says, so no name is
114    /// written and a rule that restricts MCP is reported lost.
115    Ungated,
116    /// Flow reaches MCP through connection tools that take the server as an argument.
117    ConnectionTools,
118}
119
120/// The facts the schema crate holds about one host. Each is read by one projection, so a new
121/// host adds a row here and nothing else in this crate.
122pub(crate) struct HostSpec {
123    pub display_name: &'static str,
124    /// The native name each capability becomes.
125    pub tools: tool_natives::Table,
126    /// Whether a tool name can be narrowed to a pattern. A harness spells the scope in the
127    /// permission name (`Bash(git push *)`); Flow's tools and `agy`'s `tools` names take no
128    /// scope.
129    pub scopes_patterns: bool,
130    pub mcp: McpNaming,
131    /// The effort levels the host takes, or `None` for any. The caller passes the levels a
132    /// probe-backed harness's slugs list.
133    pub effort: Option<&'static [EffortLevel]>,
134}
135
136use EffortLevel::{High, Low, Max, Medium, XHigh};
137
138/// Claude Code 2.1.325 `--effort` help: low, medium, high, xhigh, max.
139const CLAUDE: HostSpec = HostSpec {
140    display_name: "Claude",
141    tools: tool_natives::CLAUDE,
142    scopes_patterns: true,
143    mcp: McpNaming::Claude,
144    effort: Some(&[Low, Medium, High, XHigh, Max]),
145};
146
147/// Codex 0.167.0 `exec -c model_reasoning_effort=…` sends any value unchecked; the API rejected
148/// `minimal` on gpt-5.6-luna and listed none, low, medium, high, xhigh, max. models.dev decides
149/// per model: Codex's own presets (`codex debug models`) list low..max, plus `ultra` on six, and
150/// never `none`, and models.dev lacks `ultra`, `gpt-reserve` and `codex-auto-review`.
151const CODEX: HostSpec = HostSpec {
152    display_name: "Codex",
153    tools: tool_natives::CODEX,
154    scopes_patterns: true,
155    mcp: McpNaming::NoName("Codex per-tool MCP gating lives in server config, not the tool list"),
156    effort: Some(&EffortLevel::LADDER),
157};
158
159/// Pi 1.5.0 `--thinking` help: off, minimal, low, medium, high, xhigh, max (`none` is `off`).
160const PI: HostSpec = HostSpec {
161    display_name: "Pi",
162    tools: tool_natives::PI,
163    scopes_patterns: true,
164    mcp: McpNaming::NoName("Harness has no MCP tool surface"),
165    effort: Some(&EffortLevel::LADDER),
166};
167
168/// OpenCode 2.3.0 decodes models.dev `reasoning_options` itself (the string is in its binary).
169const OPENCODE: HostSpec = HostSpec {
170    display_name: "OpenCode",
171    tools: tool_natives::OPENCODE,
172    scopes_patterns: true,
173    mcp: McpNaming::Format(|server, tool| format!("{server}_{tool}")),
174    effort: None,
175};
176
177const CURSOR: HostSpec = HostSpec {
178    display_name: "Cursor",
179    tools: tool_natives::CURSOR,
180    scopes_patterns: true,
181    mcp: McpNaming::Format(|server, tool| format!("Mcp({server}:{tool})")),
182    effort: None,
183};
184
185/// `agy models` 1.5.12.
186const AGY: HostSpec = HostSpec {
187    display_name: "Antigravity",
188    tools: tool_natives::AGY,
189    scopes_patterns: false,
190    mcp: McpNaming::Ungated,
191    effort: None,
192};
193
194/// meridian-runtime `src/gateway/domain/types.ts:63` (`REASONING_EFFORTS`), per Flow's gateway
195/// lead.
196const FLOW: HostSpec = HostSpec {
197    display_name: "Meridian Flow",
198    tools: tool_natives::FLOW,
199    scopes_patterns: false,
200    mcp: McpNaming::ConnectionTools,
201    effort: Some(&[EffortLevel::None, Low, Medium, High, Max]),
202};
203
204impl Host {
205    pub(crate) fn spec(self) -> &'static HostSpec {
206        match self {
207            Self::Harness(HarnessId::Claude) => &CLAUDE,
208            Self::Harness(HarnessId::Codex) => &CODEX,
209            Self::Harness(HarnessId::Pi) => &PI,
210            Self::Harness(HarnessId::OpenCode) => &OPENCODE,
211            Self::Harness(HarnessId::Cursor) => &CURSOR,
212            Self::Harness(HarnessId::Agy) => &AGY,
213            Self::MeridianFlow => &FLOW,
214        }
215    }
216}
217
218impl Serialize for Host {
219    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
220        serializer.serialize_str(self.as_str())
221    }
222}
223
224/// The harness names in `ALL`'s order, as error messages list them.
225pub fn names() -> String {
226    ALL.iter()
227        .map(|harness| harness.as_str())
228        .collect::<Vec<_>>()
229        .join(", ")
230}
231
232/// Consumer namespaces under `harness-overrides` that are not harnesses: the consumer
233/// owns the block's contents, and Mars only keeps it. Each is the host's full name: Meridian
234/// Flow's is `meridian-flow`, the Meridian CLI's is `meridian-cli`.
235pub(crate) const RESERVED_CONSUMER_NAMESPACES: &[&str] = &["meridian-flow", "meridian-cli"];
236
237pub fn parse(name: &str) -> Option<HarnessId> {
238    let normalized = name.trim().to_ascii_lowercase();
239    ALL.iter()
240        .copied()
241        .find(|harness| harness.as_str() == normalized)
242}
243
244pub fn normalize_name(name: &str) -> Option<String> {
245    parse(name).map(|id| id.as_str().to_owned())
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251
252    #[test]
253    fn parse_and_normalize_are_case_insensitive() {
254        assert_eq!(parse("OpenCode"), Some(HarnessId::OpenCode));
255        assert_eq!(normalize_name(" OpenCode "), Some("opencode".to_string()));
256        assert_eq!(parse("gemini"), None);
257    }
258
259    #[test]
260    fn serde_names_round_trip_registry_names() {
261        for &harness in ALL {
262            let json = serde_json::to_string(&harness).unwrap();
263            assert_eq!(json, format!("\"{}\"", harness.as_str()));
264            assert_eq!(serde_json::from_str::<HarnessId>(&json).unwrap(), harness);
265        }
266        assert!(serde_json::from_str::<HarnessId>("\"open_code\"").is_err());
267    }
268}