Skip to main content

mars_schema/hooks/
agy.rs

1//! `[hooks]` translated for Antigravity's `agy`, which reads `hooks.json` and runs shell
2//! commands on its own events with its own payloads and replies.
3//!
4//! Mars writes, per hook, a data file (`hooks/mars-<name>.hooks.json`, beside the hook's
5//! directory, which the file names in `dir`) holding the surviving Claude matcher groups as the
6//! TypeScript targets' literal holds them and the Claude events each `agy` event serves, and
7//! one `hooks.json` handler per `agy` event, which runs `mars hook run` on that file. The
8//! runner (`src/hook_run`) turns `agy`'s payload into Claude's, applies
9//! Claude's matcher, `if`, exit-code and answer rules, and answers in `agy`'s form. This
10//! module is the rendering side; what the runner reads is [`DATA_VERSION`] of the file.
11
12use std::collections::BTreeMap;
13
14use serde_json::{Value, json};
15
16use super::portable::MatcherGroup;
17use super::render::{self, Output, Rendered, Skip};
18use super::targets::{self, Profile};
19use super::typescript::{GroupRules, surviving_groups};
20use super::{HOOK_DIR_TOKEN, Tokens};
21use crate::harness::HarnessId;
22
23/// The data file's format version. Under Meridian the file's writer (the `mars` of whatever
24/// venv ran the sync) and its reader (the `mars` bundled with the `meridian` on `PATH`) are
25/// different installs, so the runner reads every version from 1 up to its own: a bump keeps
26/// every older shape readable, and its release notes say to upgrade the `meridian` on `PATH`
27/// before syncing with the new `mars`. A newer version is settled by the hook's failure rule.
28pub const DATA_VERSION: u64 = 1;
29
30/// The `--harness` the runner is invoked with.
31pub const RUNNER_HARNESS: &str = "agy";
32
33/// Claude events whose answer can block the action: only these honour `onFailure = "block"`.
34/// The same set as `BLOCKING` in `typescript/core.ts`.
35pub const BLOCKING: &[&str] = &["PreToolUse", "UserPromptSubmit", "Stop"];
36
37/// One `agy` event and the Claude events it serves.
38#[derive(Debug, PartialEq, Eq)]
39struct Mapping {
40    agy: &'static str,
41    claude: &'static [&'static str],
42}
43
44/// How `agy` takes `[hooks]`: the event map, what has no `agy` event, and what an event
45/// maps only approximately.
46#[derive(Debug, PartialEq, Eq)]
47pub struct Translation {
48    events: &'static [Mapping],
49    unsupported_events: &'static [(&'static str, &'static str)],
50    /// Rendered Claude events whose answers or firing do not all carry over, with what.
51    answer_limits: &'static [(&'static str, &'static str)],
52}
53
54pub(super) const AGY: Translation = Translation {
55    events: &[
56        Mapping {
57            agy: "PreToolUse",
58            claude: &["PreToolUse"],
59        },
60        Mapping {
61            agy: "PostToolUse",
62            claude: &["PostToolUse", "PostToolUseFailure"],
63        },
64        Mapping {
65            agy: "SessionStart",
66            claude: &["SessionStart"],
67        },
68        Mapping {
69            agy: "Stop",
70            claude: &["Stop"],
71        },
72        Mapping {
73            agy: "PreInvocation",
74            claude: &["UserPromptSubmit"],
75        },
76    ],
77    unsupported_events: &[
78        (
79            "SessionEnd",
80            "agy has no session-end event (its Stop fires at the end of each turn)",
81        ),
82        (
83            "PermissionRequest",
84            "agy has no permission hook: a PreToolUse `ask` answer is its only way to prompt",
85        ),
86    ],
87    answer_limits: &[
88        (
89            "PreToolUse",
90            "an `additionalContext` answer is dropped, and `updatedInput` replaces top-level keys only (a deleted key cannot be expressed)",
91        ),
92        (
93            "PostToolUse",
94            "agy passes no tool output and reads no answer from the hook: `block` and context answers are dropped",
95        ),
96        (
97            "PostToolUseFailure",
98            "agy passes no tool output and reads no answer from the hook: `block` and context answers are dropped",
99        ),
100        (
101            "SessionStart",
102            "agy fires it once per conversation and not on resume, so a `source` matcher only ever sees `startup`",
103        ),
104        (
105            "UserPromptSubmit",
106            "agy has no prompt event: the hook runs on its PreInvocation event when that is the first of a user prompt, which recurred at each prompt and only there in a probe",
107        ),
108    ],
109};
110
111impl Translation {
112    fn maps(&self, claude_event: &str) -> bool {
113        self.events.iter().any(|m| m.claude.contains(&claude_event))
114    }
115
116    /// The Claude events `agy`'s `agy_event` serves.
117    pub fn serves(&self, agy_event: &str) -> &'static [&'static str] {
118        self.events
119            .iter()
120            .find(|m| m.agy == agy_event)
121            .map_or(&[], |m| m.claude)
122    }
123}
124
125/// Claude's tool names and the `agy` tools each stands for. Every `agy` name is in the
126/// `agy` row of `tool_natives`, which a test pins. `Edit` takes `write_to_file` too, as the
127/// `edit` capability does, but a payload's tool resolves to `Write` first ([`claude_tool`]).
128const TOOLS: &[(&str, &[&str])] = &[
129    ("Bash", &["run_command"]),
130    ("Read", &["read_file"]),
131    ("Write", &["write_to_file"]),
132    (
133        "Edit",
134        &[
135            "replace_file_content",
136            "multi_replace_file_content",
137            "write_to_file",
138        ],
139    ),
140    ("Glob", &["find_by_name"]),
141    ("Grep", &["grep_search"]),
142    ("WebSearch", &["search_web"]),
143];
144
145/// Claude's tool input keys and the argument names `agy` has been seen to use. `Path` and
146/// `CommandLine` are observed payloads; the others are
147/// names from `agy`'s tool schemas that no probe has shown a payload for.
148const ARGS: &[(&str, &[&str])] = &[
149    ("command", &["CommandLine"]),
150    ("file_path", &["Path", "TargetFile", "AbsolutePath"]),
151    ("content", &["CodeContent"]),
152    ("old_string", &["TargetContent"]),
153    ("new_string", &["ReplacementContent"]),
154];
155
156/// The Claude tool name for one of `agy`'s tools; `None` for a tool Claude has no name for.
157pub fn claude_tool(agy_tool: &str) -> Option<&'static str> {
158    TOOLS
159        .iter()
160        .find(|(_, agy)| agy.contains(&agy_tool))
161        .map(|(claude, _)| *claude)
162}
163
164/// The `agy` tools a Claude tool name stands for.
165pub fn agy_tools(claude_tool: &str) -> &'static [&'static str] {
166    TOOLS
167        .iter()
168        .find(|(claude, _)| *claude == claude_tool)
169        .map_or(&[], |(_, agy)| agy)
170}
171
172/// The Claude input key for an `agy` argument name.
173pub fn claude_arg(agy_arg: &str) -> Option<&'static str> {
174    ARGS.iter()
175        .find(|(_, agy)| agy.contains(&agy_arg))
176        .map(|(claude, _)| *claude)
177}
178
179/// The `agy` argument names a Claude input key goes by, most likely first.
180pub fn agy_args(claude_arg: &str) -> &'static [&'static str] {
181    ARGS.iter()
182        .find(|(claude, _)| *claude == claude_arg)
183        .map_or(&[], |(_, agy)| agy)
184}
185
186/// Claude's matcher as a list of plain names (`A|B`, `A,B`), or `None` when it is a regular
187/// expression. The runner (`src/hook_run`) matches by the same rule.
188pub fn plain_names(pattern: &str) -> Option<Vec<&str>> {
189    (!pattern.is_empty()
190        && pattern
191            .chars()
192            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | ' ' | ',' | '|' | '-')))
193    .then(|| pattern.split(['|', ',']).map(str::trim).collect::<Vec<_>>())
194}
195
196/// Why the runner could not evaluate a Claude matcher: it compiles anything but a plain
197/// name list as a Rust `regex`, which Claude's JavaScript regex is not.
198fn matcher_problem(pattern: &str) -> Option<String> {
199    if pattern.is_empty() || pattern == "*" || plain_names(pattern).is_some() {
200        return None;
201    }
202    render::regex_problem(pattern)
203        .err()
204        .map(|reason| format!("`mars hook run` cannot compile matcher `{pattern}`: {reason}"))
205}
206
207/// The `agy` matcher for a tool event: the `agy` names of every Claude tool the groups
208/// match when all of them match plain names, else `*` (the runner applies Claude's matcher
209/// either way).
210fn agy_matcher(claude_events: &[(&str, Vec<Value>)]) -> String {
211    let mut names = Vec::new();
212    for (_, groups) in claude_events {
213        for group in groups {
214            let Some(pattern) = group["matcher"]
215                .as_str()
216                .filter(|m| !m.is_empty() && *m != "*")
217            else {
218                return "*".into();
219            };
220            let Some(plain) = plain_names(pattern) else {
221                return "*".into();
222            };
223            for name in plain {
224                let tools = agy_tools(name);
225                if tools.is_empty() {
226                    return "*".into();
227                }
228                names.extend(tools.iter().copied());
229            }
230        }
231    }
232    names.sort_unstable();
233    names.dedup();
234    names.join("|")
235}
236
237/// The seconds `agy` waits for the runner: the runner runs a group's handlers in sequence,
238/// each up to its own timeout (an `async` handler none), and `agy` must outlast the last
239/// kill so the runner can answer.
240fn runner_timeout(claude_events: &[(&str, Vec<Value>)]) -> u64 {
241    let total: f64 = claude_events
242        .iter()
243        .flat_map(|(_, groups)| groups)
244        .flat_map(|group| group["handlers"].as_array().into_iter().flatten())
245        .filter_map(|handler| handler["timeout"].as_f64())
246        .sum();
247    total.ceil() as u64 + 1
248}
249
250/// Whether a handler of the served events asks to block when the hook itself fails.
251fn blocks_on_failure(claude_events: &[(&str, Vec<Value>)]) -> bool {
252    claude_events
253        .iter()
254        .filter(|(event, _)| BLOCKING.contains(event))
255        .flat_map(|(_, groups)| groups)
256        .flat_map(|group| group["handlers"].as_array().into_iter().flatten())
257        .any(|handler| handler["onFailure"] == "block")
258}
259
260/// The command `agy` runs for one event: `mars` run by `command` (its program, then the words
261/// before `mars`'s own arguments), behind a guard that settles a missing program by the
262/// hook's failure rule (exit 1 blocks the call, exit 0 with no output leaves it alone).
263/// Without the guard a missing program exits 127, which `agy` reads as a block. `data` is
264/// relative to `.agy/`, where `agy` runs it.
265pub fn runner_command(
266    command: &[String],
267    agy_event: &str,
268    data: &str,
269    block: bool,
270    windows: bool,
271) -> String {
272    let (program, prefix) = command
273        .split_first()
274        .map_or(("", &[][..]), |(p, r)| (p.as_str(), r));
275    let on_failure = if block { "block" } else { "continue" };
276    let args = format!(
277        "hook run --harness {RUNNER_HARNESS} --event {agy_event} --on-failure {on_failure}"
278    );
279    if windows {
280        // `agy` runs `cmd /c` there. Untested: no Windows machine has run it.
281        let data = data.replace('/', "\\");
282        let prefix: String = prefix.iter().map(|word| format!(" \"{word}\"")).collect();
283        // `if exist` finds a path, `where` a name on `PATH`.
284        let found = if program.contains(['\\', '/']) {
285            format!("if exist \"{program}\"")
286        } else {
287            format!("where /q \"{program}\" & if not errorlevel 1")
288        };
289        format!(
290            "{found} (\"{program}\"{prefix} {args} \"{data}\") else (exit /b {})",
291            u8::from(block)
292        )
293    } else {
294        let quote = |text: &str| format!("'{}'", text.replace('\'', r"'\''"));
295        let prefix: String = prefix
296            .iter()
297            .map(|word| format!(" {}", quote(word)))
298            .collect();
299        // As on Windows, a path is tested as a file and a name looked up on `PATH`: dash's
300        // `command -v` accepts any existing path, and `-x` a directory.
301        let found = if program.contains('/') {
302            "[ -f \"$m\" ] && [ -x \"$m\" ]"
303        } else {
304            "command -v \"$m\" >/dev/null"
305        };
306        format!(
307            "m={}; {found} || {{ echo \"mars hook: $m not found; run mars sync\" >&2; exit {}; }}; exec \"$m\"{prefix} {args} {}",
308            quote(program),
309            u8::from(block),
310            quote(data)
311        )
312    }
313}
314
315/// `table` (the events Claude knows) translated for `agy`, with `tokens` substituted.
316/// `${MARS_HOOK_DIR}` stays in the data file: the runner resolves it from the file's `dir`
317/// (the hook's directory relative to `.agy/`), so the file holds no machine path.
318pub(super) fn render(
319    table: &[(&str, &[MatcherGroup])],
320    profile: &Profile,
321    translation: &Translation,
322    tokens: &Tokens<'_>,
323    windows: bool,
324) -> Rendered {
325    let mut skips = Vec::new();
326    let mut answer_limits = Vec::new();
327    let mut skip = |event: &str, reason: String| {
328        skips.push(Skip {
329            event: Some(event.to_owned()),
330            reason,
331        })
332    };
333    let deferred = Tokens {
334        hook_dir: HOOK_DIR_TOKEN,
335        ..*tokens
336    };
337    for &(event, _) in table {
338        if !translation.maps(event) {
339            let reason = translation
340                .unsupported_events
341                .iter()
342                .find(|(name, _)| *name == event)
343                .map_or_else(
344                    || format!("{} has no such event", HarnessId::Agy.display_name()),
345                    |(_, reason)| (*reason).to_owned(),
346                );
347            skip(event, reason);
348        }
349    }
350    let mut entries = BTreeMap::new();
351    let mut serves = serde_json::Map::new();
352    let mut by_claude = serde_json::Map::new();
353    for mapping in translation.events {
354        let row = profile
355            .event(mapping.agy)
356            .expect("every mapped agy event has a row");
357        let mut kept: Vec<(&str, Vec<Value>)> = Vec::new();
358        for &claude_name in mapping.claude {
359            let Some((_, groups)) = table.iter().find(|(event, _)| *event == claude_name) else {
360                continue;
361            };
362            let claude = targets::claude_event(claude_name).expect("Claude's event");
363            let groups = surviving_groups(
364                claude_name,
365                groups,
366                claude,
367                &GroupRules {
368                    harness_name: HarnessId::Agy.display_name(),
369                    supplies_matcher: row.matcher.is_some(),
370                    tokens: &deferred,
371                    matcher_problem: &matcher_problem,
372                },
373                &mut skip,
374            );
375            if groups.is_empty() {
376                continue;
377            }
378            if let Some((_, limit)) = translation
379                .answer_limits
380                .iter()
381                .find(|(name, _)| *name == claude_name)
382            {
383                answer_limits.push(Skip {
384                    event: Some(claude_name.to_owned()),
385                    reason: (*limit).to_owned(),
386                });
387            }
388            kept.push((claude_name, groups));
389        }
390        if kept.is_empty() {
391            continue;
392        }
393        let command = runner_command(
394            tokens.mars_command,
395            mapping.agy,
396            tokens.generated_file,
397            blocks_on_failure(&kept),
398            windows,
399        );
400        let handler = json!({
401            "type": "command",
402            "command": command,
403            "timeout": runner_timeout(&kept),
404        });
405        let entry = if row.is_tool_event() {
406            json!({"matcher": agy_matcher(&kept), "hooks": [handler]})
407        } else {
408            handler
409        };
410        entries.insert(
411            mapping.agy.to_owned(),
412            vec![serde_json::from_value(entry).expect("a JSON value is an ordered value")],
413        );
414        serves.insert(
415            mapping.agy.to_owned(),
416            kept.iter().map(|(event, _)| *event).collect(),
417        );
418        for (claude_name, groups) in kept {
419            by_claude.insert(claude_name.to_owned(), Value::Array(groups));
420        }
421    }
422    let data_file = (!entries.is_empty()).then(|| {
423        let data = json!({
424            "version": DATA_VERSION,
425            "name": tokens.hook_name,
426            "dir": tokens.hook_dir,
427            "verified": profile.verified_against,
428            "serves": serves,
429            "events": by_claude,
430        });
431        serde_json::to_string_pretty(&data).expect("a JSON value serializes") + "\n"
432    });
433    Rendered {
434        output: Output::Keyed {
435            events: entries,
436            data_file,
437        },
438        skips,
439        answer_limits,
440    }
441}
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446    use crate::HarnessId;
447    use crate::tool_natives::lookup;
448
449    /// Every `agy` tool the table names is one the `agy` row of `tool_natives` knows, so a
450    /// tool renamed there cannot silently stop matching here.
451    #[test]
452    fn every_agy_tool_is_in_the_native_tool_table() {
453        let known: Vec<&str> = crate::tool_names::canonical_capabilities()
454            .filter_map(|capability| lookup(capability, HarnessId::Agy))
455            .flat_map(|native| native.native_tools().iter().copied())
456            .collect();
457        for (claude, tools) in TOOLS {
458            for tool in *tools {
459                assert!(
460                    known.contains(tool),
461                    "{claude}: `{tool}` is not an agy tool"
462                );
463            }
464        }
465    }
466}