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    /// Keys set at the top of the file before appending (Cursor's `version`).
68    pub top_level: &'static [(&'static str, i64)],
69    /// The harness skips hooks it has not been told to trust, keyed on their position in
70    /// `file` (Codex): a sync that moves or adds one says so.
71    pub trust_gated: bool,
72}
73
74/// How a target root takes a hook.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum Placement {
77    /// The hook's events are merged into the target's hook config file.
78    Merge(MergeFile),
79    /// The hook is installed as whole files in `dir`, under the target root.
80    File { dir: &'static str },
81    /// Each hook is one entry of the JSON object in the file at `path`, relative to the
82    /// project, keyed by the hook's name: the hook's own events, as the harness reads them, are
83    /// the value. A hook that translates `[hooks]` keeps its runner data in `dir`, beside its
84    /// own directory copy, and never inside it: target sync owns that copy as a whole.
85    Keyed {
86        path: &'static str,
87        dir: &'static str,
88    },
89}
90
91/// How `[hooks]` becomes a target's entries.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub enum Rules {
94    /// Claude takes the table as written.
95    Claude,
96    /// Codex's parser: handlers and matchers it cannot run are left out.
97    Codex,
98    /// Generated TypeScript for the harness (`hooks::typescript`).
99    TypeScript(&'static Harness),
100    /// Translated for the harness's own events and answers by a `mars hook run` command
101    /// (`hooks::agy`).
102    Translated(&'static agy::Translation),
103    /// Nothing is rendered for the target, as a whole; `reason` says why.
104    Withheld { reason: &'static str },
105}
106
107/// What a renderer needs of a target: the events it accepts and the rules its parser applies.
108/// The two vary independently: the plugin tree's `hooks.json` is Claude's events under
109/// Codex's rules.
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub struct Profile {
112    /// Every event the target accepts.
113    pub events: &'static [Event],
114    /// The harness version `events` was last checked against; `None` while the rows are
115    /// unchecked.
116    pub verified_against: Option<&'static str>,
117    pub rules: Rules,
118}
119
120impl Profile {
121    /// The profile's row for `name`.
122    pub fn event(&self, name: &str) -> Option<&'static Event> {
123        self.events.iter().find(|e| e.name == name)
124    }
125
126    /// The `[hooks]` events a native event stands for: a translating target's event serves
127    /// others (`agy`'s `PreInvocation` is `UserPromptSubmit`); any other serves itself.
128    pub fn served<'a>(&self, native_event: &'a str) -> Vec<&'a str> {
129        match self.rules {
130            Rules::Translated(translation) => translation.serves(native_event).to_vec(),
131            _ => vec![native_event],
132        }
133    }
134
135    /// Whether the rules render `[hooks]` at all.
136    pub fn renders(&self) -> bool {
137        !matches!(self.rules, Rules::Withheld { .. })
138    }
139}
140
141/// One target root's hook rules.
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub struct Target {
144    pub root: &'static str,
145    pub placement: Placement,
146    pub profile: Profile,
147    /// Events the harness reads that `profile.events` has no row for: they travel only in a
148    /// native hook marked `unchecked`.
149    pub other_events: &'static [&'static str],
150}
151
152/// Where a file-placement target's generated file gets its suffix: the hook name ends in
153/// neither, so a generated file never collides with an authored one.
154const GENERATED_SUFFIX: &str = super::RESERVED_NAME_SUFFIX;
155
156impl Target {
157    /// Whether the harness reads `event` from its hook file; it ignores any other key.
158    pub fn reads(&self, event: &str) -> bool {
159        self.profile.event(event).is_some() || self.other_events.contains(&event)
160    }
161
162    /// The file a merge target appends entries to; `None` for any other placement.
163    pub fn merge_file(&self) -> Option<&MergeFile> {
164        match &self.placement {
165            Placement::Merge(merge) => Some(merge),
166            Placement::File { .. } | Placement::Keyed { .. } => None,
167        }
168    }
169
170    /// The project-relative file whose entries are keyed by hook name; `None` for any other
171    /// placement.
172    pub fn keyed_path(&self) -> Option<&'static str> {
173        match self.placement {
174            Placement::Keyed { path, .. } => Some(path),
175            Placement::Merge(_) | Placement::File { .. } => None,
176        }
177    }
178
179    /// What is wrong with a file target's native hook, if anything. Warning-only: a file
180    /// native hook is otherwise opaque, and the caller words the diagnostic.
181    pub fn native_hook_problem(&self, content: &str) -> Option<&'static str> {
182        match self.profile.rules {
183            Rules::TypeScript(harness) => harness.native_hook_problem(content),
184            _ => None,
185        }
186    }
187
188    /// Whether the target installs whole files rather than merging entries.
189    pub fn is_file(&self) -> bool {
190        matches!(self.placement, Placement::File { .. })
191    }
192
193    /// Whether a hook can own files on the target besides its directory copy: the files of
194    /// a file target, or a keyed target's runner data.
195    pub fn installs_files(&self) -> bool {
196        self.is_file() || self.keyed_path().is_some()
197    }
198
199    /// The path, relative to the target root, of the hook's own native hook file; `None` for a
200    /// merge target, which has no per-hook file.
201    pub fn native_hook_path(&self, hook_name: &str) -> Option<String> {
202        let Placement::File { dir } = self.placement else {
203            return None;
204        };
205        Some(format!("{dir}/mars-{hook_name}.ts"))
206    }
207
208    /// The path, relative to the target root, of the file generated from the hook's
209    /// `[hooks]`; `None` for a merge target.
210    pub fn generated_path(&self, hook_name: &str) -> Option<String> {
211        match self.placement {
212            Placement::File { dir } => Some(format!("{dir}/mars-{hook_name}{GENERATED_SUFFIX}.ts")),
213            Placement::Keyed { dir, .. } => {
214                Some(format!("{dir}/mars-{hook_name}{GENERATED_SUFFIX}.json"))
215            }
216            Placement::Merge(_) => None,
217        }
218    }
219}
220
221const CLAUDE_EVENTS: &[Event] = &[
222    matched("SessionStart", "source"),
223    event("Setup"),
224    event("UserPromptSubmit").timeout_ms(30_000),
225    event("UserPromptExpansion"),
226    matched("PreToolUse", "tool_name"),
227    matched("PermissionRequest", "tool_name"),
228    matched("PermissionDenied", "tool_name"),
229    matched("PostToolUse", "tool_name"),
230    matched("PostToolUseFailure", "tool_name"),
231    event("PostToolBatch"),
232    matched("SubagentStart", "agent_type"),
233    matched("SubagentStop", "agent_type"),
234    event("TaskCreated"),
235    event("TaskCompleted"),
236    event("Stop"),
237    event("StopFailure"),
238    event("TeammateIdle"),
239    matched("PreCompact", "trigger"),
240    matched("PostCompact", "trigger"),
241    event("Elicitation"),
242    event("ElicitationResult"),
243    matched("Notification", "notification_type"),
244    event("ConfigChange"),
245    event("InstructionsLoaded"),
246    event("CwdChanged"),
247    event("FileChanged"),
248    event("WorktreeCreate"),
249    event("WorktreeRemove"),
250    matched("SessionEnd", "reason").timeout_ms(1_500),
251];
252
253// Codex reports `SessionEnd` reason as `other`.
254const CODEX_EVENTS: &[Event] = &[
255    matched("SessionStart", "source"),
256    event("UserPromptSubmit"),
257    matched("PreToolUse", "tool_name"),
258    matched("PermissionRequest", "tool_name"),
259    matched("PostToolUse", "tool_name"),
260    matched("PreCompact", "trigger"),
261    matched("PostCompact", "trigger"),
262    matched("SubagentStart", "agent_type"),
263    matched("SubagentStop", "agent_type"),
264    event("Stop"),
265    matched("SessionEnd", "reason"),
266];
267
268const CURSOR_EVENTS: &[Event] = &[
269    event("beforeShellExecution"),
270    event("beforeMCPExecution"),
271    event("afterShellExecution"),
272    event("afterMCPExecution"),
273    event("beforeReadFile"),
274    event("afterFileEdit"),
275    event("beforeTabFileRead"),
276    event("afterTabFileEdit"),
277    event("stop"),
278    event("beforeSubmitPrompt"),
279    event("afterAgentResponse"),
280    event("afterAgentThought"),
281    event("sessionStart"),
282    event("sessionEnd"),
283    event("preCompact"),
284    event("subagentStart"),
285    event("subagentStop"),
286    event("preToolUse"),
287    event("postToolUse"),
288    event("postToolUseFailure"),
289    event("workspaceOpen"),
290];
291
292// OpenCode's compaction callback does not identify its trigger.
293const OPENCODE_EVENTS: &[Event] = &[
294    matched("PreToolUse", "tool_name"),
295    matched("PostToolUse", "tool_name"),
296    matched("PostToolUseFailure", "tool_name"),
297    event("UserPromptSubmit"),
298    event("PreCompact"),
299    matched("PermissionRequest", "tool_name"),
300];
301
302const PI_EVENTS: &[Event] = &[
303    matched("PreToolUse", "tool_name"),
304    matched("PostToolUse", "tool_name"),
305    matched("PostToolUseFailure", "tool_name"),
306    event("UserPromptSubmit"),
307    matched("SessionStart", "source"),
308    event("Stop"),
309    matched("PreCompact", "trigger"),
310    matched("PostCompact", "trigger"),
311    matched("SessionEnd", "reason"),
312];
313
314// `agy` reads these six from a plugin's `hooks.json`; the first four take handler objects,
315// the last two `{matcher, hooks}` groups.
316const AGY_EVENTS: &[Event] = &[
317    // The runner gives a SessionStart matcher `startup`, the one source `agy` fires it for.
318    matched("SessionStart", "source"),
319    event("PreInvocation"),
320    event("PostInvocation"),
321    event("Stop"),
322    matched("PreToolUse", "tool_name"),
323    matched("PostToolUse", "tool_name"),
324];
325
326const CLAUDE_VERSION: &str = "Claude Code 2.1.312";
327
328/// What the Claude plugin tree's `hooks/hooks.json` must satisfy: Claude's events under
329/// Codex's handler rules, because Claude, Codex and Grok all read that one file.
330pub const PLUGIN_CLAUDE_TREE: Profile = Profile {
331    events: CLAUDE_EVENTS,
332    verified_against: Some(CLAUDE_VERSION),
333    rules: Rules::Codex,
334};
335
336const CLAUDE: Target = Target {
337    root: ".claude",
338    // Hook commands carry machine-local cache paths, so they belong in the gitignored
339    // `settings.local.json` rather than the committed `settings.json`.
340    placement: Placement::Merge(MergeFile {
341        file: "settings.local.json",
342        top_level: &[],
343        trust_gated: false,
344    }),
345    profile: Profile {
346        events: CLAUDE_EVENTS,
347        verified_against: Some(CLAUDE_VERSION),
348        rules: Rules::Claude,
349    },
350    other_events: &[],
351};
352
353const CODEX: Target = Target {
354    root: ".codex",
355    placement: Placement::Merge(MergeFile {
356        file: "hooks.json",
357        top_level: &[],
358        trust_gated: true,
359    }),
360    profile: Profile {
361        events: CODEX_EVENTS,
362        verified_against: Some("codex-cli 0.164.0"),
363        rules: Rules::Codex,
364    },
365    other_events: &["PreModelRequest", "PostModelRequest", "Interrupt"],
366};
367
368const CURSOR: Target = Target {
369    root: ".cursor",
370    // Cursor's `hooks.json` is a flat entry array and requires the version wrapper.
371    placement: Placement::Merge(MergeFile {
372        file: "hooks.json",
373        top_level: &[("version", 1)],
374        trust_gated: false,
375    }),
376    profile: Profile {
377        events: CURSOR_EVENTS,
378        verified_against: Some("cursor-agent 2026.07.16"),
379        rules: Rules::Withheld {
380            reason: "mars renders no generated hooks for Cursor before 0.26",
381        },
382    },
383    other_events: &[],
384};
385
386const OPENCODE: Target = Target {
387    root: ".opencode",
388    placement: Placement::File { dir: "plugins" },
389    profile: Profile {
390        events: OPENCODE_EVENTS,
391        verified_against: Some("OpenCode 2.2.0"),
392        rules: Rules::TypeScript(&typescript::OPENCODE),
393    },
394    other_events: &[],
395};
396
397const PI: Target = Target {
398    root: ".pi",
399    placement: Placement::File { dir: "extensions" },
400    profile: Profile {
401        events: PI_EVENTS,
402        verified_against: Some("Pi 1.4.0"),
403        rules: Rules::TypeScript(&typescript::PI),
404    },
405    other_events: &[],
406};
407
408const AGY: Target = Target {
409    root: ".agy",
410    // `agy` reads `hooks.json` only at the plugin root, one top-level key per hook.
411    placement: Placement::Keyed {
412        path: ".agy/hooks.json",
413        dir: "hooks",
414    },
415    profile: Profile {
416        events: AGY_EVENTS,
417        verified_against: Some("agy 1.5.12"),
418        rules: Rules::Translated(&agy::AGY),
419    },
420    other_events: &[],
421};
422
423/// The hook rules of a harness. A harness with no row here fails to compile.
424fn row(harness: HarnessId) -> &'static Target {
425    match harness {
426        HarnessId::Claude => &CLAUDE,
427        HarnessId::Codex => &CODEX,
428        HarnessId::OpenCode => &OPENCODE,
429        HarnessId::Cursor => &CURSOR,
430        HarnessId::Pi => &PI,
431        HarnessId::Agy => &AGY,
432    }
433}
434
435/// The hook rules of `root`; `None` when it has no hook mechanism.
436pub fn target(root: &str) -> Option<&'static Target> {
437    harness::ALL
438        .iter()
439        .find(|harness| harness.target_dir() == root)
440        .map(|&harness| row(harness))
441}
442
443/// Every target that takes hooks.
444pub fn all() -> impl Iterator<Item = &'static Target> {
445    harness::ALL.iter().map(|&harness| row(harness))
446}
447
448/// Claude's event of that name: the set a `[hooks]` table may declare.
449pub fn claude_event(name: &str) -> Option<&'static Event> {
450    CLAUDE_EVENTS.iter().find(|event| event.name == name)
451}
452
453/// Claude's event names, for a message.
454pub fn claude_event_names() -> String {
455    CLAUDE_EVENTS
456        .iter()
457        .map(|event| event.name)
458        .collect::<Vec<_>>()
459        .join(", ")
460}