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