Skip to main content

mars_schema/hooks/
targets.rs

1//! What each target root takes of a hook: one [`Target`] row per root, holding where its
2//! hooks are placed (the merge file and its trust gate, or the file directory), the events it
3//! accepts, the harness version that table was last checked against, how `[hooks]` is
4//! rendered for it (for a TypeScript harness, its glue, limits and native hook contract), and
5//! what its generated files are called. A new target is one row here; the binary only places
6//! what the row describes. Nothing about a target is kept anywhere else.
7use super::agy;
8use super::typescript::{self, Harness};
9use crate::harness::{self, HarnessId};
10
11/// A hook event of one target and the input field its `matcher` tests.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct Event {
14    pub name: &'static str,
15    /// The input field the matcher tests (`tool_name`, `source`, …). `None` means no field is
16    /// recorded for this event; only the events a generated adapter renders need one.
17    pub matcher: Option<&'static str>,
18    /// Claude Code's default `timeout` for a `command` handler on this event, in
19    /// milliseconds. A generated TypeScript hook applies the Claude row's value so it times
20    /// out as it would on Claude; the other targets' rows carry the common default unread.
21    pub default_timeout_ms: u32,
22}
23
24/// The default of every event but the two below. Claude Code docs, "Hook handler fields",
25/// `timeout`: https://code.claude.com/docs/en/hooks (read 2026-10-28).
26const DEFAULT_TIMEOUT_MS: u32 = 600_000;
27
28impl Event {
29    /// The row with a shorter Claude default. The docs lower it to 30 s on
30    /// `UserPromptSubmit` (and on the `PreModelSwitch`/`PostModelSwitch`, 10 s on
31    /// `MessageDisplay`, which the Claude table below does not list) and give `SessionEnd`
32    /// a 1.5 s budget.
33    const fn timeout_ms(self, default_timeout_ms: u32) -> Self {
34        Self {
35            default_timeout_ms,
36            ..self
37        }
38    }
39
40    /// A tool event: its handlers can carry Claude's `if` filter.
41    pub fn is_tool_event(&self) -> bool {
42        self.matcher == Some("tool_name")
43    }
44}
45
46const fn event(name: &'static str) -> Event {
47    Event {
48        name,
49        matcher: None,
50        default_timeout_ms: DEFAULT_TIMEOUT_MS,
51    }
52}
53
54const fn matched(name: &'static str, field: &'static str) -> Event {
55    Event {
56        name,
57        matcher: Some(field),
58        default_timeout_ms: DEFAULT_TIMEOUT_MS,
59    }
60}
61
62/// The hook config file of a merge target, where its entries are appended.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub struct MergeFile {
65    /// Under the target root.
66    pub file: &'static str,
67    /// The harness skips hooks it has not been told to trust, keyed on their position in
68    /// `file` (Codex): a sync that moves or adds one says so.
69    pub trust_gated: bool,
70}
71
72/// How a target root takes a hook.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum Placement {
75    /// The hook's events are merged into the target's hook config file.
76    Merge(MergeFile),
77    /// The hook is installed as whole files in `dir`, under the target root.
78    File { dir: &'static str },
79    /// Each hook is one entry of the JSON object in the file at `path`, relative to the
80    /// project, keyed by the hook's name: the hook's own events, as the harness reads them, are
81    /// the value. A hook that translates `[hooks]` keeps its runner data in `dir`, beside its
82    /// own directory copy, and never inside it: target sync owns that copy as a whole.
83    Keyed {
84        path: &'static str,
85        dir: &'static str,
86    },
87}
88
89/// How `[hooks]` becomes a target's entries.
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum Rules {
92    /// Claude takes the table as written.
93    Claude,
94    /// Codex's parser: handlers and matchers it cannot run are left out.
95    Codex,
96    /// Generated TypeScript for the harness (`hooks::typescript`).
97    TypeScript(&'static Harness),
98    /// Translated for the harness's own events and answers by a `mars hook run` command
99    /// (`hooks::agy`).
100    Translated(&'static agy::Translation),
101}
102
103/// What a renderer needs of a target: the events it accepts and the rules its parser applies.
104/// The two vary independently: the plugin tree's `hooks.json` is Claude's events under
105/// Codex's rules.
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub struct Profile {
108    /// Every event the target accepts.
109    pub events: &'static [Event],
110    /// The harness version `events` was last checked against; `None` while the rows are
111    /// unchecked.
112    pub verified_against: Option<&'static str>,
113    pub rules: Rules,
114}
115
116impl Profile {
117    /// The profile's row for `name`.
118    pub fn event(&self, name: &str) -> Option<&'static Event> {
119        self.events.iter().find(|e| e.name == name)
120    }
121
122    /// The `[hooks]` events a native event stands for: a translating target's event serves
123    /// others (`agy`'s `PreInvocation` is `UserPromptSubmit`); any other serves itself.
124    pub fn served<'a>(&self, native_event: &'a str) -> Vec<&'a str> {
125        match self.rules {
126            Rules::Translated(translation) => translation.serves(native_event).to_vec(),
127            _ => vec![native_event],
128        }
129    }
130}
131
132/// One target root's hook rules.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub struct Target {
135    pub root: &'static str,
136    pub placement: Placement,
137    pub profile: Profile,
138    /// Events the harness reads that `profile.events` has no row for: they travel only in a
139    /// native hook marked `unchecked`.
140    pub other_events: &'static [&'static str],
141}
142
143/// Where a file-placement target's generated file gets its suffix: the hook name ends in
144/// neither, so a generated file never collides with an authored one.
145const GENERATED_SUFFIX: &str = super::RESERVED_NAME_SUFFIX;
146
147impl Target {
148    /// Whether the harness reads `event` from its hook file; it ignores any other key.
149    pub fn reads(&self, event: &str) -> bool {
150        self.profile.event(event).is_some() || self.other_events.contains(&event)
151    }
152
153    /// The file a merge target appends entries to; `None` for any other placement.
154    pub fn merge_file(&self) -> Option<&MergeFile> {
155        match &self.placement {
156            Placement::Merge(merge) => Some(merge),
157            Placement::File { .. } | Placement::Keyed { .. } => None,
158        }
159    }
160
161    /// The project-relative file whose entries are keyed by hook name; `None` for any other
162    /// placement.
163    pub fn keyed_path(&self) -> Option<&'static str> {
164        match self.placement {
165            Placement::Keyed { path, .. } => Some(path),
166            Placement::Merge(_) | Placement::File { .. } => None,
167        }
168    }
169
170    /// What is wrong with a file target's native hook, if anything. Warning-only: a file
171    /// native hook is otherwise opaque, and the caller words the diagnostic.
172    pub fn native_hook_problem(&self, content: &str) -> Option<&'static str> {
173        match self.profile.rules {
174            Rules::TypeScript(harness) => harness.native_hook_problem(content),
175            _ => None,
176        }
177    }
178
179    /// Whether the target installs whole files rather than merging entries.
180    pub fn is_file(&self) -> bool {
181        matches!(self.placement, Placement::File { .. })
182    }
183
184    /// Whether a hook can own files on the target besides its directory copy: the files of
185    /// a file target, or a keyed target's runner data.
186    pub fn installs_files(&self) -> bool {
187        self.is_file() || self.keyed_path().is_some()
188    }
189
190    /// The path, relative to the target root, of the hook's own native hook file; `None` for a
191    /// merge target, which has no per-hook file.
192    pub fn native_hook_path(&self, hook_name: &str) -> Option<String> {
193        let Placement::File { dir } = self.placement else {
194            return None;
195        };
196        Some(format!("{dir}/mars-{hook_name}.ts"))
197    }
198
199    /// The path, relative to the target root, of the file generated from the hook's
200    /// `[hooks]`; `None` for a merge target.
201    pub fn generated_path(&self, hook_name: &str) -> Option<String> {
202        match self.placement {
203            Placement::File { dir } => Some(format!("{dir}/mars-{hook_name}{GENERATED_SUFFIX}.ts")),
204            Placement::Keyed { dir, .. } => {
205                Some(format!("{dir}/mars-{hook_name}{GENERATED_SUFFIX}.json"))
206            }
207            Placement::Merge(_) => None,
208        }
209    }
210}
211
212const CLAUDE_EVENTS: &[Event] = &[
213    matched("SessionStart", "source"),
214    event("Setup"),
215    event("UserPromptSubmit").timeout_ms(30_000),
216    event("UserPromptExpansion"),
217    matched("PreToolUse", "tool_name"),
218    matched("PermissionRequest", "tool_name"),
219    matched("PermissionDenied", "tool_name"),
220    matched("PostToolUse", "tool_name"),
221    matched("PostToolUseFailure", "tool_name"),
222    event("PostToolBatch"),
223    matched("SubagentStart", "agent_type"),
224    matched("SubagentStop", "agent_type"),
225    event("TaskCreated"),
226    event("TaskCompleted"),
227    event("Stop"),
228    event("StopFailure"),
229    event("TeammateIdle"),
230    matched("PreCompact", "trigger"),
231    matched("PostCompact", "trigger"),
232    event("Elicitation"),
233    event("ElicitationResult"),
234    matched("Notification", "notification_type"),
235    event("ConfigChange"),
236    event("InstructionsLoaded"),
237    event("CwdChanged"),
238    event("FileChanged"),
239    event("WorktreeCreate"),
240    event("WorktreeRemove"),
241    matched("SessionEnd", "reason").timeout_ms(1_500),
242];
243
244// Codex reports `SessionEnd` reason as `other`.
245const CODEX_EVENTS: &[Event] = &[
246    matched("SessionStart", "source"),
247    event("UserPromptSubmit"),
248    matched("PreToolUse", "tool_name"),
249    matched("PermissionRequest", "tool_name"),
250    matched("PostToolUse", "tool_name"),
251    matched("PreCompact", "trigger"),
252    matched("PostCompact", "trigger"),
253    matched("SubagentStart", "agent_type"),
254    matched("SubagentStop", "agent_type"),
255    event("Stop"),
256    matched("SessionEnd", "reason"),
257];
258
259// OpenCode's compaction callback does not identify its trigger.
260const OPENCODE_EVENTS: &[Event] = &[
261    matched("PreToolUse", "tool_name"),
262    matched("PostToolUse", "tool_name"),
263    matched("PostToolUseFailure", "tool_name"),
264    event("UserPromptSubmit"),
265    event("PreCompact"),
266    matched("PermissionRequest", "tool_name"),
267];
268
269const PI_EVENTS: &[Event] = &[
270    matched("PreToolUse", "tool_name"),
271    matched("PostToolUse", "tool_name"),
272    matched("PostToolUseFailure", "tool_name"),
273    event("UserPromptSubmit"),
274    matched("SessionStart", "source"),
275    event("Stop"),
276    matched("PreCompact", "trigger"),
277    matched("PostCompact", "trigger"),
278    matched("SessionEnd", "reason"),
279];
280
281// `agy` reads these six from a plugin's `hooks.json`; the first four take handler objects,
282// the last two `{matcher, hooks}` groups.
283const AGY_EVENTS: &[Event] = &[
284    // The runner gives a SessionStart matcher `startup`, the one source `agy` fires it for.
285    matched("SessionStart", "source"),
286    event("PreInvocation"),
287    event("PostInvocation"),
288    event("Stop"),
289    matched("PreToolUse", "tool_name"),
290    matched("PostToolUse", "tool_name"),
291];
292
293const CLAUDE_VERSION: &str = "Claude Code 2.1.312";
294
295/// What the Claude plugin tree's `hooks/hooks.json` must satisfy: Claude's events under
296/// Codex's handler rules, because Claude, Codex and Grok all read that one file.
297pub const PLUGIN_CLAUDE_TREE: Profile = Profile {
298    events: CLAUDE_EVENTS,
299    verified_against: Some(CLAUDE_VERSION),
300    rules: Rules::Codex,
301};
302
303const CLAUDE: Target = Target {
304    root: ".claude",
305    // Hook commands carry machine-local cache paths, so they belong in the gitignored
306    // `settings.local.json` rather than the committed `settings.json`.
307    placement: Placement::Merge(MergeFile {
308        file: "settings.local.json",
309        trust_gated: false,
310    }),
311    profile: Profile {
312        events: CLAUDE_EVENTS,
313        verified_against: Some(CLAUDE_VERSION),
314        rules: Rules::Claude,
315    },
316    other_events: &[],
317};
318
319const CODEX: Target = Target {
320    root: ".codex",
321    placement: Placement::Merge(MergeFile {
322        file: "hooks.json",
323        trust_gated: true,
324    }),
325    profile: Profile {
326        events: CODEX_EVENTS,
327        verified_against: Some("codex-cli 0.164.0"),
328        rules: Rules::Codex,
329    },
330    other_events: &["PreModelRequest", "PostModelRequest", "Interrupt"],
331};
332
333const OPENCODE: Target = Target {
334    root: ".opencode",
335    placement: Placement::File { dir: "plugins" },
336    profile: Profile {
337        events: OPENCODE_EVENTS,
338        verified_against: Some("OpenCode 2.2.0"),
339        rules: Rules::TypeScript(&typescript::OPENCODE),
340    },
341    other_events: &[],
342};
343
344const PI: Target = Target {
345    root: ".pi",
346    placement: Placement::File { dir: "extensions" },
347    profile: Profile {
348        events: PI_EVENTS,
349        verified_against: Some("Pi 1.4.0"),
350        rules: Rules::TypeScript(&typescript::PI),
351    },
352    other_events: &[],
353};
354
355const AGY: Target = Target {
356    root: ".agy",
357    // `agy` reads `hooks.json` only at the plugin root, one top-level key per hook.
358    placement: Placement::Keyed {
359        path: ".agy/hooks.json",
360        dir: "hooks",
361    },
362    profile: Profile {
363        events: AGY_EVENTS,
364        verified_against: Some("agy 1.5.12"),
365        rules: Rules::Translated(&agy::AGY),
366    },
367    other_events: &[],
368};
369
370/// The hook rules of a harness. A harness with no row here fails to compile.
371fn row(harness: HarnessId) -> &'static Target {
372    match harness {
373        HarnessId::Claude => &CLAUDE,
374        HarnessId::Codex => &CODEX,
375        HarnessId::OpenCode => &OPENCODE,
376        HarnessId::Pi => &PI,
377        HarnessId::Agy => &AGY,
378    }
379}
380
381/// The hook rules of `root`; `None` when it has no hook mechanism.
382pub fn target(root: &str) -> Option<&'static Target> {
383    harness::ALL
384        .iter()
385        .find(|harness| harness.target_dir() == root)
386        .map(|&harness| row(harness))
387}
388
389/// Every target that takes hooks.
390pub fn all() -> impl Iterator<Item = &'static Target> {
391    harness::ALL.iter().map(|&harness| row(harness))
392}
393
394/// Claude's event of that name: the set a `[hooks]` table may declare.
395pub fn claude_event(name: &str) -> Option<&'static Event> {
396    CLAUDE_EVENTS.iter().find(|event| event.name == name)
397}
398
399/// Claude's event names, for a message.
400pub fn claude_event_names() -> String {
401    CLAUDE_EVENTS
402        .iter()
403        .map(|event| event.name)
404        .collect::<Vec<_>>()
405        .join(", ")
406}