Skip to main content

mars_schema/hooks/
render.rs

1//! A portable hook rendered for one target: finished entries per event, and what was left
2//! out. Renderers emit only what the target's parser accepts; they never pass Claude's
3//! JSON through blindly.
4
5use std::collections::BTreeMap;
6
7use serde_json::Number;
8
9use super::Tokens;
10use super::portable::{Handler, MatcherGroup, NO_COMMAND, PortableHooks};
11use super::targets::{self, Profile, Rules};
12use crate::harness::HarnessId;
13use crate::ordered::OrderedValue;
14
15/// Something a target does not run. `event` is `None` when the whole target is skipped.
16#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
17pub struct Skip {
18    pub event: Option<String>,
19    pub reason: String,
20}
21
22/// One profile's rendering of a hook's `[hooks]` table.
23#[derive(Debug, Clone, PartialEq)]
24pub struct Rendered {
25    pub output: Output,
26    pub skips: Vec<Skip>,
27    /// Events that render, but whose portable answers do not all carry over to the target.
28    pub answer_limits: Vec<Skip>,
29}
30
31/// What a rendering yields, in the shape the target's placement takes.
32#[derive(Debug, Clone, PartialEq)]
33pub enum Output {
34    /// Finished entries per native event, for a hook config file. An event with nothing left
35    /// is absent.
36    Merge {
37        events: BTreeMap<String, Vec<OrderedValue>>,
38        /// Events the target does not list that the hook's `unchecked = true` passed through.
39        unchecked_events: Vec<String>,
40    },
41    /// The text of the one file generated from the table; `None` when nothing is generated.
42    File { text: Option<String> },
43    /// Finished entries per native event for a keyed hook file, and the data file the
44    /// entries' runner reads; `None` when nothing renders.
45    Keyed {
46        events: BTreeMap<String, Vec<OrderedValue>>,
47        data_file: Option<String>,
48    },
49}
50
51impl Rendered {
52    fn skip(&mut self, event: &str, reason: String) {
53        self.skips.push(Skip {
54            event: Some(event.to_owned()),
55            reason,
56        });
57    }
58
59    /// Whether nothing was rendered.
60    pub fn is_empty(&self) -> bool {
61        match &self.output {
62            Output::Merge { events, .. } | Output::Keyed { events, .. } => events.is_empty(),
63            Output::File { text } => text.is_none(),
64        }
65    }
66
67    /// The merge shape's events; none for a file.
68    pub fn events(&self) -> &BTreeMap<String, Vec<OrderedValue>> {
69        static NONE: BTreeMap<String, Vec<OrderedValue>> = BTreeMap::new();
70        match &self.output {
71            Output::Merge { events, .. } | Output::Keyed { events, .. } => events,
72            Output::File { .. } => &NONE,
73        }
74    }
75}
76
77impl PortableHooks {
78    /// This table as `profile` takes it, with `tokens` substituted in every string.
79    pub fn render(&self, profile: &Profile, tokens: &Tokens<'_>) -> Rendered {
80        // Only Claude takes an event mars does not know (`unchecked`); every other target
81        // reports it as skipped.
82        let mut events: Vec<_> = self.events().collect();
83        let mut unknown = Vec::new();
84        if matches!(
85            profile.rules,
86            Rules::Codex | Rules::TypeScript(_) | Rules::Translated(_)
87        ) {
88            events.retain(|(event, _)| {
89                let known = targets::claude_event(event).is_some();
90                if !known {
91                    unknown.push(Skip {
92                        event: Some((*event).to_owned()),
93                        reason: "not an event mars knows, so `unchecked` renders it on Claude only"
94                            .into(),
95                    });
96                }
97                known
98            });
99        }
100        let mut rendered = match profile.rules {
101            Rules::Claude => render_claude(&events, profile),
102            Rules::Codex => render_codex(&events, profile),
103            Rules::Withheld { reason } => Rendered {
104                output: Output::Merge {
105                    events: BTreeMap::new(),
106                    unchecked_events: Vec::new(),
107                },
108                skips: vec![Skip {
109                    event: None,
110                    reason: reason.into(),
111                }],
112                answer_limits: Vec::new(),
113            },
114            Rules::TypeScript(harness) => {
115                super::typescript::render(&events, profile, harness, tokens)
116            }
117            Rules::Translated(translation) => {
118                super::agy::render(&events, profile, translation, tokens, cfg!(windows))
119            }
120        };
121        if !unknown.is_empty() {
122            // Skips follow the events' sorted order, as the renderers emit them.
123            rendered.skips.extend(unknown);
124            rendered.skips.sort_by(|a, b| a.event.cmp(&b.event));
125        }
126        if let Output::Merge { events, .. } = &mut rendered.output {
127            for entries in events.values_mut() {
128                entries
129                    .iter_mut()
130                    .for_each(|entry| tokens.substitute_value(entry));
131            }
132        }
133        rendered
134    }
135
136    /// Whether `render` yields anything under `profile`.
137    pub fn renders_on(&self, profile: &Profile) -> bool {
138        !self.render(profile, &Tokens::default()).is_empty()
139    }
140
141    /// Events on which a handler sets `if`, though Claude never runs such a handler there.
142    pub fn conditions_on_non_tool_events(&self) -> Vec<&str> {
143        self.events()
144            .filter(|(event, groups)| {
145                let tool_event = targets::claude_event(event).is_some_and(|e| e.is_tool_event());
146                !tool_event
147                    && groups
148                        .iter()
149                        .flat_map(|group| &group.handlers)
150                        .any(|handler| handler.condition.is_some())
151            })
152            .map(|(event, _)| event)
153            .collect()
154    }
155}
156
157/// Identity: Claude takes the table as written. An event the profile does not list is one
158/// the author passed with `unchecked = true`.
159fn render_claude(table: &[(&str, &[MatcherGroup])], profile: &Profile) -> Rendered {
160    let mut events = BTreeMap::new();
161    let mut unchecked_events = Vec::new();
162    for &(event, groups) in table {
163        if profile.event(event).is_none() {
164            unchecked_events.push(event.to_owned());
165        }
166        events.insert(
167            event.to_owned(),
168            groups.iter().map(MatcherGroup::to_claude).collect(),
169        );
170    }
171    Rendered {
172        output: Output::Merge {
173            events,
174            unchecked_events,
175        },
176        skips: Vec::new(),
177        answer_limits: Vec::new(),
178    }
179}
180
181fn render_codex(table: &[(&str, &[MatcherGroup])], profile: &Profile) -> Rendered {
182    let mut rendered = Rendered {
183        output: Output::Merge {
184            events: BTreeMap::new(),
185            unchecked_events: Vec::new(),
186        },
187        skips: Vec::new(),
188        answer_limits: Vec::new(),
189    };
190    let mut rendered_events = BTreeMap::new();
191    for &(event, groups) in table {
192        let Some(row) = profile.event(event) else {
193            rendered.skip(
194                event,
195                format!("{} has no such event", HarnessId::Codex.display_name()),
196            );
197            continue;
198        };
199        let matched = row.matcher.is_some();
200        let mut entries = Vec::new();
201        for (g, group) in groups.iter().enumerate() {
202            if let (true, Some(matcher)) = (matched, &group.matcher)
203                && let Err(reason) = codex_matcher(matcher)
204            {
205                rendered.skip(
206                    event,
207                    format!(
208                        "matcher group {g}: Codex cannot compile matcher `{matcher}`: {reason}"
209                    ),
210                );
211                continue;
212            }
213            let mut kept = Vec::new();
214            for (h, handler) in group.handlers.iter().enumerate() {
215                match codex_handler(event, handler) {
216                    Ok(handler) => kept.push(handler),
217                    Err(reason) => {
218                        rendered.skip(event, format!("matcher group {g}, handler {h}: {reason}"))
219                    }
220                }
221            }
222            if !kept.is_empty() {
223                entries.push(group.to_value(&kept));
224            }
225        }
226        if !entries.is_empty() {
227            rendered_events.insert(event.to_owned(), entries);
228        }
229    }
230    rendered.output = Output::Merge {
231        events: rendered_events,
232        unchecked_events: Vec::new(),
233    };
234    rendered
235}
236
237/// Whether Codex 0.164.0 admits a group's `matcher`. Codex compiles it at discovery, and a
238/// group whose matcher fails is skipped (`HookMatcher::new`, codex-rs/hooks/src/engine/
239/// matcher.rs; `append_matcher_groups`, discovery.rs L527-541): empty, `*` and plain
240/// `A|B` name lists are exact, anything else is a Rust `regex`, which has no look-around or
241/// backreferences although Claude's JavaScript regex does. Codex reads the matcher only on
242/// the events that have a matcher field (`matcher_pattern_for_event`, events/common.rs).
243fn codex_matcher(pattern: &str) -> Result<(), String> {
244    if pattern.is_empty()
245        || pattern == "*"
246        || pattern
247            .chars()
248            .all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '|')
249    {
250        return Ok(());
251    }
252    regex_problem(pattern)
253}
254
255/// Why a Rust `regex` cannot compile `pattern`, which Claude's JavaScript regex may: no
256/// look-around, no backreferences.
257pub(super) fn regex_problem(pattern: &str) -> Result<(), String> {
258    use regex_syntax::Error;
259    regex_syntax::Parser::new()
260        .parse(pattern)
261        .map(drop)
262        .map_err(|error| match error {
263            Error::Parse(error) => error.kind().to_string(),
264            Error::Translate(error) => error.kind().to_string(),
265            other => other.to_string(),
266        })
267}
268
269/// A handler as Codex 0.164.0 parses it, or why Codex would not run it. Codex rejects its
270/// whole `hooks.json` over one handler it cannot parse, so each field Codex types is checked
271/// here: `HookHandlerConfig`, codex-rs/config/src/hook_config.rs L180-221; skip rules in
272/// codex-rs/hooks/src/engine/discovery.rs L548-695.
273fn codex_handler(event: &str, handler: &Handler) -> Result<Handler, String> {
274    let extra = |key: &str| handler.extra.get(key);
275    let text = |key: &str| match extra(key) {
276        None => Ok(None),
277        Some(OrderedValue::String(text)) => Ok(Some(text.as_str())),
278        Some(_) => Err(format!("`{key}` must be a string for Codex")),
279    };
280    match handler.kind.as_str() {
281        "command" => {
282            if handler.command_to_run().is_none() {
283                return Err(NO_COMMAND.into());
284            }
285            text("commandWindows")?;
286            match extra("additionalContextLimit") {
287                None => {}
288                Some(OrderedValue::Number(n)) if n.as_u64().is_some() => {}
289                Some(_) => return Err("`additionalContextLimit` must be a whole number".into()),
290            }
291        }
292        "mcp_tool" => {
293            if event == "SessionEnd" {
294                return Err("Codex runs no `mcp_tool` handler on SessionEnd".into());
295            }
296            for key in ["server", "tool"] {
297                if text(key)?.is_none_or(|value| value.trim().is_empty()) {
298                    return Err(format!("an `mcp_tool` handler needs a non-empty `{key}`"));
299                }
300            }
301            if extra("input").is_some_and(|input| !matches!(input, OrderedValue::Object(_))) {
302                return Err("`input` must be a table".into());
303            }
304        }
305        "prompt" | "agent" => {
306            return Err(format!(
307                "Codex parses `{}` handlers but never runs them",
308                handler.kind
309            ));
310        }
311        other => {
312            return Err(format!(
313                "Codex runs `command` and `mcp_tool` handlers, not `{other}`"
314            ));
315        }
316    }
317    let mut handler = handler.clone();
318    handler.timeout = handler.timeout.as_ref().map(whole_seconds).transpose()?;
319    Ok(handler)
320}
321
322/// Codex reads `timeout` as an unsigned integer: a fractional one rounds up.
323fn whole_seconds(timeout: &Number) -> Result<Number, String> {
324    if let Some(problem) = super::portable::timeout_problem(timeout) {
325        return Err(problem);
326    }
327    Ok(match timeout.as_u64() {
328        Some(seconds) => seconds.into(),
329        None => (timeout.as_f64().unwrap_or(0.0).ceil() as u64).into(),
330    })
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336
337    fn profile(root: &str) -> Profile {
338        targets::target(root).unwrap().profile
339    }
340
341    fn hooks(json: &str) -> PortableHooks {
342        PortableHooks::from_claude_json(json).unwrap().0
343    }
344
345    fn tokens() -> Tokens<'static> {
346        Tokens {
347            hook_dir: "/p/.codex/hooks/audit",
348            hook_target: ".codex",
349            ..Default::default()
350        }
351    }
352
353    const MIXED: &str = r#"{
354        "PreToolUse":[{"matcher":"Bash","hooks":[
355            {"type":"command","command":"bash ${MARS_HOOK_DIR}/run.sh ${MARS_HOOK_TARGET}",
356             "timeout":2.5,"if":"Bash(*tmux*)","onFailure":"block","statusMessage":"m"},
357            {"type":"http","url":"https://example.test"},
358            {"type":"prompt"}]}],
359        "SessionEnd":[{"hooks":[{"type":"mcp_tool","server":"s","tool":"t"},
360                                {"type":"command","command":"echo bye"}]}],
361        "Notification":[{"hooks":[{"type":"command","command":"echo n"}]}]}"#;
362
363    #[test]
364    fn claude_gets_the_table_as_written_with_tokens_substituted() {
365        let rendered = hooks(MIXED).render(&profile(".claude"), &tokens());
366        assert!(rendered.skips.is_empty());
367        let json = serde_json::to_string(&rendered.events()["PreToolUse"][0].to_json()).unwrap();
368        assert!(
369            json.contains("bash /p/.codex/hooks/audit/run.sh .codex"),
370            "{json}"
371        );
372        assert!(json.contains(r#""timeout":2.5"#));
373        assert_eq!(rendered.events().len(), 3);
374    }
375
376    #[test]
377    fn codex_gets_what_codex_parses_and_reports_the_rest() {
378        let rendered = hooks(MIXED).render(&profile(".codex"), &tokens());
379        let pre = serde_json::to_string(
380            &rendered.events()["PreToolUse"]
381                .iter()
382                .map(OrderedValue::to_json)
383                .collect::<Vec<_>>(),
384        )
385        .unwrap();
386        // The fractional timeout rounds up; `if` and `onFailure` stay (Codex ignores them).
387        assert_eq!(
388            pre,
389            r#"[{"hooks":[{"command":"bash /p/.codex/hooks/audit/run.sh .codex","if":"Bash(*tmux*)","onFailure":"block","statusMessage":"m","timeout":3,"type":"command"}],"matcher":"Bash"}]"#
390        );
391        // SessionEnd keeps the command and drops the mcp_tool; Notification has no Codex event.
392        let end = serde_json::to_string(&rendered.events()["SessionEnd"][0].to_json()).unwrap();
393        assert_eq!(
394            end,
395            r#"{"hooks":[{"command":"echo bye","type":"command"}]}"#
396        );
397        assert!(!rendered.events().contains_key("Notification"));
398        let reasons: Vec<_> = rendered
399            .skips
400            .iter()
401            .map(|s| format!("{}: {}", s.event.as_deref().unwrap(), s.reason))
402            .collect();
403        assert_eq!(
404            reasons,
405            [
406                "Notification: Codex has no such event",
407                "PreToolUse: matcher group 0, handler 1: Codex runs `command` and `mcp_tool` handlers, not `http`",
408                "PreToolUse: matcher group 0, handler 2: Codex parses `prompt` handlers but never runs them",
409                "SessionEnd: matcher group 0, handler 0: Codex runs no `mcp_tool` handler on SessionEnd",
410            ]
411        );
412    }
413
414    #[test]
415    fn codex_skips_a_group_whose_matcher_it_cannot_compile() {
416        let table = hooks(
417            r#"{"PreToolUse":[
418                {"matcher":"^(?!Read).*","hooks":[{"type":"command","command":"a"}]},
419                {"matcher":"Bash|Edit","hooks":[{"type":"command","command":"b"}]},
420                {"matcher":"mcp__.*","hooks":[{"type":"command","command":"c"}]},
421                {"matcher":"*","hooks":[{"type":"command","command":"d"}]}],
422               "Stop":[{"matcher":"(?<=x)y","hooks":[{"type":"command","command":"e"}]}]}"#,
423        );
424        let rendered = table.render(&profile(".codex"), &tokens());
425        let commands: Vec<_> = rendered.events()["PreToolUse"]
426            .iter()
427            .map(|g| {
428                g.to_json()["hooks"][0]["command"]
429                    .as_str()
430                    .unwrap()
431                    .to_owned()
432            })
433            .collect();
434        assert_eq!(commands, ["b", "c", "d"]);
435        // Codex reads no matcher on Stop, so that group stays.
436        assert!(rendered.events().contains_key("Stop"));
437        assert_eq!(rendered.skips.len(), 1);
438        assert!(
439            rendered.skips[0].reason.contains("matcher group 0")
440                && rendered.skips[0].reason.contains("look-around"),
441            "{:?}",
442            rendered.skips
443        );
444        // Claude takes all of it.
445        assert_eq!(
446            table.render(&profile(".claude"), &tokens()).events()["PreToolUse"].len(),
447            4
448        );
449    }
450
451    #[test]
452    fn a_group_with_no_handler_left_is_left_out() {
453        let rendered = hooks(r#"{"Stop":[{"hooks":[{"type":"http","url":"u"}]}]}"#)
454            .render(&profile(".codex"), &tokens());
455        assert!(rendered.is_empty());
456        assert_eq!(rendered.skips.len(), 1);
457    }
458
459    #[test]
460    fn cursor_renders_nothing_and_says_why() {
461        let cursor = hooks(MIXED).render(&profile(".cursor"), &tokens());
462        assert!(cursor.is_empty());
463        assert_eq!(cursor.skips.len(), 1);
464        assert_eq!(cursor.skips[0].event, None);
465    }
466
467    #[test]
468    fn if_on_a_non_tool_event_is_named() {
469        let table = hooks(
470            r#"{"PreToolUse":[{"hooks":[{"type":"command","command":"x","if":"Bash(*)"}]}],
471                "Stop":[{"hooks":[{"type":"command","command":"x","if":"Bash(*)"}]}]}"#,
472        );
473        assert_eq!(table.conditions_on_non_tool_events(), ["Stop"]);
474    }
475}