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