mars-schema 0.26.1

Pure schema reader and editor for Mars agent packages
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! A portable hook rendered for one target: finished entries per event, and what was left
//! out. Renderers emit only what the target's parser accepts (D17); they never pass Claude's
//! JSON through blindly.

use std::collections::BTreeMap;

use serde_json::Number;

use super::Tokens;
use super::portable::{Handler, MatcherGroup, NO_COMMAND, PortableHooks};
use super::targets::{self, Profile, Rules};
use crate::ordered::OrderedValue;

/// Something a target does not run. `event` is `None` when the whole target is skipped.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct Skip {
    pub event: Option<String>,
    pub reason: String,
}

/// One profile's rendering of a hook's `[hooks]` table.
#[derive(Debug, Clone, PartialEq)]
pub struct Rendered {
    pub output: Output,
    pub skips: Vec<Skip>,
    /// Events that render, but whose portable answers do not all carry over to the target.
    pub answer_limits: Vec<Skip>,
}

/// What a rendering yields, in the shape the target's placement takes.
#[derive(Debug, Clone, PartialEq)]
pub enum Output {
    /// Finished entries per native event, for a hook config file. An event with nothing left
    /// is absent.
    Merge {
        events: BTreeMap<String, Vec<OrderedValue>>,
        /// Events the target does not list that the hook's `unchecked = true` passed through.
        unchecked_events: Vec<String>,
    },
    /// The text of the one file generated from the table; `None` when nothing is generated.
    File { text: Option<String> },
}

impl Rendered {
    fn skip(&mut self, event: &str, reason: String) {
        self.skips.push(Skip {
            event: Some(event.to_owned()),
            reason,
        });
    }

    /// Whether nothing was rendered.
    pub fn is_empty(&self) -> bool {
        match &self.output {
            Output::Merge { events, .. } => events.is_empty(),
            Output::File { text } => text.is_none(),
        }
    }

    /// The merge shape's events; none for a file.
    pub fn events(&self) -> &BTreeMap<String, Vec<OrderedValue>> {
        static NONE: BTreeMap<String, Vec<OrderedValue>> = BTreeMap::new();
        match &self.output {
            Output::Merge { events, .. } => events,
            Output::File { .. } => &NONE,
        }
    }
}

impl PortableHooks {
    /// This table as `profile` takes it, with `tokens` substituted in every string.
    pub fn render(&self, profile: &Profile, tokens: &Tokens<'_>) -> Rendered {
        // Only Claude takes an event mars does not know (`unchecked`); every other target
        // reports it as skipped.
        let mut events: Vec<_> = self.events().collect();
        let mut unknown = Vec::new();
        if matches!(profile.rules, Rules::Codex | Rules::TypeScript(_)) {
            events.retain(|(event, _)| {
                let known = targets::claude_event(event).is_some();
                if !known {
                    unknown.push(Skip {
                        event: Some((*event).to_owned()),
                        reason: "not an event mars knows, so `unchecked` renders it on Claude only"
                            .into(),
                    });
                }
                known
            });
        }
        let mut rendered = match profile.rules {
            Rules::Claude => render_claude(&events, profile),
            Rules::Codex => render_codex(&events, profile),
            Rules::Withheld { reason } => Rendered {
                output: Output::Merge {
                    events: BTreeMap::new(),
                    unchecked_events: Vec::new(),
                },
                skips: vec![Skip {
                    event: None,
                    reason: reason.into(),
                }],
                answer_limits: Vec::new(),
            },
            Rules::TypeScript(harness) => {
                super::typescript::render(&events, profile, harness, tokens)
            }
        };
        if !unknown.is_empty() {
            // Skips follow the events' sorted order, as the renderers emit them.
            rendered.skips.extend(unknown);
            rendered.skips.sort_by(|a, b| a.event.cmp(&b.event));
        }
        if let Output::Merge { events, .. } = &mut rendered.output {
            for entries in events.values_mut() {
                entries
                    .iter_mut()
                    .for_each(|entry| tokens.substitute_value(entry));
            }
        }
        rendered
    }

    /// Whether `render` yields anything under `profile`.
    pub fn renders_on(&self, profile: &Profile) -> bool {
        !self.render(profile, &Tokens::default()).is_empty()
    }

    /// Events on which a handler sets `if`, though Claude never runs such a handler there.
    pub fn conditions_on_non_tool_events(&self) -> Vec<&str> {
        self.events()
            .filter(|(event, groups)| {
                let tool_event = targets::claude_event(event).is_some_and(|e| e.is_tool_event());
                !tool_event
                    && groups
                        .iter()
                        .flat_map(|group| &group.handlers)
                        .any(|handler| handler.condition.is_some())
            })
            .map(|(event, _)| event)
            .collect()
    }
}

/// Identity: Claude takes the table as written. An event the profile does not list is one
/// the author passed with `unchecked = true`.
fn render_claude(table: &[(&str, &[MatcherGroup])], profile: &Profile) -> Rendered {
    let mut events = BTreeMap::new();
    let mut unchecked_events = Vec::new();
    for &(event, groups) in table {
        if profile.event(event).is_none() {
            unchecked_events.push(event.to_owned());
        }
        events.insert(
            event.to_owned(),
            groups.iter().map(MatcherGroup::to_claude).collect(),
        );
    }
    Rendered {
        output: Output::Merge {
            events,
            unchecked_events,
        },
        skips: Vec::new(),
        answer_limits: Vec::new(),
    }
}

fn render_codex(table: &[(&str, &[MatcherGroup])], profile: &Profile) -> Rendered {
    let mut rendered = Rendered {
        output: Output::Merge {
            events: BTreeMap::new(),
            unchecked_events: Vec::new(),
        },
        skips: Vec::new(),
        answer_limits: Vec::new(),
    };
    let mut rendered_events = BTreeMap::new();
    for &(event, groups) in table {
        let Some(row) = profile.event(event) else {
            rendered.skip(event, "Codex has no such event".into());
            continue;
        };
        let matched = row.matcher.is_some();
        let mut entries = Vec::new();
        for (g, group) in groups.iter().enumerate() {
            if let (true, Some(matcher)) = (matched, &group.matcher)
                && let Err(reason) = codex_matcher(matcher)
            {
                rendered.skip(
                    event,
                    format!(
                        "matcher group {g}: Codex cannot compile matcher `{matcher}`: {reason}"
                    ),
                );
                continue;
            }
            let mut kept = Vec::new();
            for (h, handler) in group.handlers.iter().enumerate() {
                match codex_handler(event, handler) {
                    Ok(handler) => kept.push(handler),
                    Err(reason) => {
                        rendered.skip(event, format!("matcher group {g}, handler {h}: {reason}"))
                    }
                }
            }
            if !kept.is_empty() {
                entries.push(group.to_value(&kept));
            }
        }
        if !entries.is_empty() {
            rendered_events.insert(event.to_owned(), entries);
        }
    }
    rendered.output = Output::Merge {
        events: rendered_events,
        unchecked_events: Vec::new(),
    };
    rendered
}

/// Whether Codex 0.164.0 admits a group's `matcher`. Codex compiles it at discovery, and a
/// group whose matcher fails is skipped (`HookMatcher::new`, codex-rs/hooks/src/engine/
/// matcher.rs; `append_matcher_groups`, discovery.rs L527-541): empty, `*` and plain
/// `A|B` name lists are exact, anything else is a Rust `regex`, which has no look-around or
/// backreferences although Claude's JavaScript regex does. Codex reads the matcher only on
/// the events that have a matcher field (`matcher_pattern_for_event`, events/common.rs).
fn codex_matcher(pattern: &str) -> Result<(), String> {
    use regex_syntax::Error;
    if pattern.is_empty()
        || pattern == "*"
        || pattern
            .chars()
            .all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '|')
    {
        return Ok(());
    }
    regex_syntax::Parser::new()
        .parse(pattern)
        .map(drop)
        .map_err(|error| match error {
            Error::Parse(error) => error.kind().to_string(),
            Error::Translate(error) => error.kind().to_string(),
            other => other.to_string(),
        })
}

/// A handler as Codex 0.164.0 parses it, or why Codex would not run it. Codex rejects its
/// whole `hooks.json` over one handler it cannot parse, so each field Codex types is checked
/// here: `HookHandlerConfig`, codex-rs/config/src/hook_config.rs L180-221; skip rules in
/// codex-rs/hooks/src/engine/discovery.rs L548-695.
fn codex_handler(event: &str, handler: &Handler) -> Result<Handler, String> {
    let extra = |key: &str| handler.extra.get(key);
    let text = |key: &str| match extra(key) {
        None => Ok(None),
        Some(OrderedValue::String(text)) => Ok(Some(text.as_str())),
        Some(_) => Err(format!("`{key}` must be a string for Codex")),
    };
    match handler.kind.as_str() {
        "command" => {
            if handler.command_to_run().is_none() {
                return Err(NO_COMMAND.into());
            }
            text("commandWindows")?;
            match extra("additionalContextLimit") {
                None => {}
                Some(OrderedValue::Number(n)) if n.as_u64().is_some() => {}
                Some(_) => return Err("`additionalContextLimit` must be a whole number".into()),
            }
        }
        "mcp_tool" => {
            if event == "SessionEnd" {
                return Err("Codex runs no `mcp_tool` handler on SessionEnd".into());
            }
            for key in ["server", "tool"] {
                if text(key)?.is_none_or(|value| value.trim().is_empty()) {
                    return Err(format!("an `mcp_tool` handler needs a non-empty `{key}`"));
                }
            }
            if extra("input").is_some_and(|input| !matches!(input, OrderedValue::Object(_))) {
                return Err("`input` must be a table".into());
            }
        }
        "prompt" | "agent" => {
            return Err(format!(
                "Codex parses `{}` handlers but never runs them",
                handler.kind
            ));
        }
        other => {
            return Err(format!(
                "Codex runs `command` and `mcp_tool` handlers, not `{other}`"
            ));
        }
    }
    let mut handler = handler.clone();
    handler.timeout = handler.timeout.as_ref().map(whole_seconds).transpose()?;
    Ok(handler)
}

/// Codex reads `timeout` as an unsigned integer: a fractional one rounds up.
fn whole_seconds(timeout: &Number) -> Result<Number, String> {
    if let Some(problem) = super::portable::timeout_problem(timeout) {
        return Err(problem);
    }
    Ok(match timeout.as_u64() {
        Some(seconds) => seconds.into(),
        None => (timeout.as_f64().unwrap_or(0.0).ceil() as u64).into(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn profile(root: &str) -> Profile {
        targets::target(root).unwrap().profile
    }

    fn hooks(json: &str) -> PortableHooks {
        PortableHooks::from_claude_json(json).unwrap().0
    }

    fn tokens() -> Tokens<'static> {
        Tokens {
            hook_dir: "/p/.codex/hooks/audit",
            hook_target: ".codex",
            ..Default::default()
        }
    }

    const MIXED: &str = r#"{
        "PreToolUse":[{"matcher":"Bash","hooks":[
            {"type":"command","command":"bash ${MARS_HOOK_DIR}/run.sh ${MARS_HOOK_TARGET}",
             "timeout":2.5,"if":"Bash(*tmux*)","onFailure":"block","statusMessage":"m"},
            {"type":"http","url":"https://example.test"},
            {"type":"prompt"}]}],
        "SessionEnd":[{"hooks":[{"type":"mcp_tool","server":"s","tool":"t"},
                                {"type":"command","command":"echo bye"}]}],
        "Notification":[{"hooks":[{"type":"command","command":"echo n"}]}]}"#;

    #[test]
    fn claude_gets_the_table_as_written_with_tokens_substituted() {
        let rendered = hooks(MIXED).render(&profile(".claude"), &tokens());
        assert!(rendered.skips.is_empty());
        let json = serde_json::to_string(&rendered.events()["PreToolUse"][0].to_json()).unwrap();
        assert!(
            json.contains("bash /p/.codex/hooks/audit/run.sh .codex"),
            "{json}"
        );
        assert!(json.contains(r#""timeout":2.5"#));
        assert_eq!(rendered.events().len(), 3);
    }

    #[test]
    fn codex_gets_what_codex_parses_and_reports_the_rest() {
        let rendered = hooks(MIXED).render(&profile(".codex"), &tokens());
        let pre = serde_json::to_string(
            &rendered.events()["PreToolUse"]
                .iter()
                .map(OrderedValue::to_json)
                .collect::<Vec<_>>(),
        )
        .unwrap();
        // The fractional timeout rounds up; `if` and `onFailure` stay (Codex ignores them).
        assert_eq!(
            pre,
            r#"[{"hooks":[{"command":"bash /p/.codex/hooks/audit/run.sh .codex","if":"Bash(*tmux*)","onFailure":"block","statusMessage":"m","timeout":3,"type":"command"}],"matcher":"Bash"}]"#
        );
        // SessionEnd keeps the command and drops the mcp_tool; Notification has no Codex event.
        let end = serde_json::to_string(&rendered.events()["SessionEnd"][0].to_json()).unwrap();
        assert_eq!(
            end,
            r#"{"hooks":[{"command":"echo bye","type":"command"}]}"#
        );
        assert!(!rendered.events().contains_key("Notification"));
        let reasons: Vec<_> = rendered
            .skips
            .iter()
            .map(|s| format!("{}: {}", s.event.as_deref().unwrap(), s.reason))
            .collect();
        assert_eq!(
            reasons,
            [
                "Notification: Codex has no such event",
                "PreToolUse: matcher group 0, handler 1: Codex runs `command` and `mcp_tool` handlers, not `http`",
                "PreToolUse: matcher group 0, handler 2: Codex parses `prompt` handlers but never runs them",
                "SessionEnd: matcher group 0, handler 0: Codex runs no `mcp_tool` handler on SessionEnd",
            ]
        );
    }

    #[test]
    fn codex_skips_a_group_whose_matcher_it_cannot_compile() {
        let table = hooks(
            r#"{"PreToolUse":[
                {"matcher":"^(?!Read).*","hooks":[{"type":"command","command":"a"}]},
                {"matcher":"Bash|Edit","hooks":[{"type":"command","command":"b"}]},
                {"matcher":"mcp__.*","hooks":[{"type":"command","command":"c"}]},
                {"matcher":"*","hooks":[{"type":"command","command":"d"}]}],
               "Stop":[{"matcher":"(?<=x)y","hooks":[{"type":"command","command":"e"}]}]}"#,
        );
        let rendered = table.render(&profile(".codex"), &tokens());
        let commands: Vec<_> = rendered.events()["PreToolUse"]
            .iter()
            .map(|g| {
                g.to_json()["hooks"][0]["command"]
                    .as_str()
                    .unwrap()
                    .to_owned()
            })
            .collect();
        assert_eq!(commands, ["b", "c", "d"]);
        // Codex reads no matcher on Stop, so that group stays.
        assert!(rendered.events().contains_key("Stop"));
        assert_eq!(rendered.skips.len(), 1);
        assert!(
            rendered.skips[0].reason.contains("matcher group 0")
                && rendered.skips[0].reason.contains("look-around"),
            "{:?}",
            rendered.skips
        );
        // Claude takes all of it.
        assert_eq!(
            table.render(&profile(".claude"), &tokens()).events()["PreToolUse"].len(),
            4
        );
    }

    #[test]
    fn a_group_with_no_handler_left_is_left_out() {
        let rendered = hooks(r#"{"Stop":[{"hooks":[{"type":"http","url":"u"}]}]}"#)
            .render(&profile(".codex"), &tokens());
        assert!(rendered.is_empty());
        assert_eq!(rendered.skips.len(), 1);
    }

    #[test]
    fn cursor_renders_nothing_and_says_why() {
        let cursor = hooks(MIXED).render(&profile(".cursor"), &tokens());
        assert!(cursor.is_empty());
        assert_eq!(cursor.skips.len(), 1);
        assert_eq!(cursor.skips[0].event, None);
    }

    #[test]
    fn if_on_a_non_tool_event_is_named() {
        let table = hooks(
            r#"{"PreToolUse":[{"hooks":[{"type":"command","command":"x","if":"Bash(*)"}]}],
                "Stop":[{"hooks":[{"type":"command","command":"x","if":"Bash(*)"}]}]}"#,
        );
        assert_eq!(table.conditions_on_non_tool_events(), ["Stop"]);
    }
}