Skip to main content

tuff_core/
hook_settings.rs

1//! Hook registrations inside a harness's settings file.
2//!
3//! This is the one piece of adapter logic that is genuinely per-harness,
4//! and until it lived here every adapter crate carried its own copy of it.
5//! The copies drifted: a dedupe bug had to be fixed four times at once
6//! (tuff#83), and each crate spelled the same validation error a little
7//! differently. What actually differs between harnesses is the *shape* of
8//! the file, captured by [`HookSettingsShape`]; the merge and the removal
9//! are the same algorithm over either shape.
10
11use std::path::Path;
12
13use serde::Serialize;
14
15use crate::error::{Result, TuffError};
16use crate::lockfile::ManagedHook;
17
18/// How a harness lays out the hook registrations in its settings file.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
20#[serde(rename_all = "lowercase")]
21pub enum HookSettingsShape {
22    /// Claude Code's shape, shared by Open Agents and Codex: every event
23    /// holds groups, and every group holds typed hook entries.
24    ///
25    /// ```json
26    /// {"hooks": {"PreToolUse": [{"hooks": [{"type": "command", "command": "sh …"}]}]}}
27    /// ```
28    Grouped,
29    /// Cursor's shape: every event holds the entries directly, and the
30    /// file carries a `version` beside `hooks`.
31    ///
32    /// ```json
33    /// {"version": 1, "hooks": {"preToolUse": [{"command": "sh …"}]}}
34    /// ```
35    Flat,
36}
37
38/// The `version` a flat settings file declares.
39const FLAT_SETTINGS_VERSION: u64 = 1;
40
41impl HookSettingsShape {
42    /// The settings a harness starts from when the file does not exist.
43    fn empty_settings(self) -> serde_json::Value {
44        match self {
45            Self::Grouped => serde_json::json!({}),
46            Self::Flat => serde_json::json!({"version": FLAT_SETTINGS_VERSION}),
47        }
48    }
49
50    /// The keys a hooks-only fragment may carry beside `hooks`.
51    fn extra_fragment_keys(self) -> &'static [&'static str] {
52        match self {
53            Self::Grouped => &[],
54            Self::Flat => &["version"],
55        }
56    }
57
58    /// The fragment that registers one command under one native event.
59    pub fn command_fragment(self, native_event: &str, command: &str) -> serde_json::Value {
60        match self {
61            Self::Grouped => serde_json::json!({
62                "hooks": {
63                    native_event: [{
64                        "hooks": [{"type": "command", "command": command}]
65                    }]
66                }
67            }),
68            Self::Flat => serde_json::json!({
69                "version": FLAT_SETTINGS_VERSION,
70                "hooks": {native_event: [{"command": command}]}
71            }),
72        }
73    }
74
75    /// Refuse anything that is not a hooks-only fragment. A whole settings
76    /// file pasted in by mistake would otherwise be merged key by key into
77    /// the harness's real one.
78    pub fn validate_fragment(self, fragment: &serde_json::Value) -> Result<()> {
79        let object = fragment
80            .as_object()
81            .ok_or_else(|| TuffError::usage("--hook-file fragment must be a JSON object"))?;
82        if !object.contains_key("hooks") {
83            return Err(TuffError::usage(
84                "--hook-file fragment must contain a top-level 'hooks' object",
85            ));
86        }
87        let allowed = self.extra_fragment_keys();
88        if object
89            .keys()
90            .any(|key| key != "hooks" && !allowed.contains(&key.as_str()))
91        {
92            return Err(TuffError::usage(match self {
93                Self::Grouped => {
94                    "--hook-file must be a hooks-only fragment, not a full settings file"
95                }
96                Self::Flat => "--hook-file must contain only 'hooks' and optional 'version'",
97            }));
98        }
99        if !fragment["hooks"].is_object() {
100            return Err(TuffError::usage(
101                "--hook-file field 'hooks' must be an object",
102            ));
103        }
104        Ok(())
105    }
106
107    /// Merge a hooks-only fragment into the harness's settings file, given
108    /// the bytes it holds now, and return the bytes it should hold next.
109    ///
110    /// Everything the user already has is kept. `tuff add` is re-runnable
111    /// and a pack may be installed over an existing install, so a group the
112    /// event already registers is not appended again; the harness would
113    /// otherwise run that hook once per copy.
114    pub fn merge_fragment(
115        self,
116        settings_relpath: &str,
117        existing: Option<&[u8]>,
118        fragment: &serde_json::Value,
119    ) -> Result<Vec<u8>> {
120        self.validate_fragment(fragment)?;
121        let mut settings = match existing {
122            Some(bytes) if !bytes.is_empty() => serde_json::from_slice(bytes)?,
123            _ => self.empty_settings(),
124        };
125        let settings_object = settings.as_object_mut().ok_or_else(|| {
126            TuffError::corrupt(format!("{settings_relpath} must be a JSON object"))
127        })?;
128        if self == Self::Flat {
129            settings_object
130                .entry("version")
131                .or_insert_with(|| serde_json::json!(FLAT_SETTINGS_VERSION));
132        }
133        let fragment_hooks = fragment["hooks"]
134            .as_object()
135            .expect("validated hooks object");
136        let settings_hooks = settings_object
137            .entry("hooks")
138            .or_insert_with(|| serde_json::json!({}))
139            .as_object_mut()
140            .ok_or_else(|| {
141                TuffError::corrupt(format!(
142                    "{settings_relpath} field 'hooks' must be an object"
143                ))
144            })?;
145        for (event, additions) in fragment_hooks {
146            let additions = additions.as_array().ok_or_else(|| {
147                TuffError::usage(format!("--hook-file hooks.{event} must be an array"))
148            })?;
149            let groups = settings_hooks
150                .entry(event.clone())
151                .or_insert_with(|| serde_json::json!([]))
152                .as_array_mut()
153                .ok_or_else(|| {
154                    TuffError::corrupt(format!("{settings_relpath} hooks.{event} must be an array"))
155                })?;
156            extend_hook_groups(groups, additions);
157        }
158        Ok(serde_json::to_string_pretty(&settings)?.into_bytes())
159    }
160}
161
162/// Append hook groups that this event does not already register.
163pub fn extend_hook_groups(existing: &mut Vec<serde_json::Value>, additions: &[serde_json::Value]) {
164    for addition in additions {
165        if !existing.iter().any(|group| group == addition) {
166            existing.push(addition.clone());
167        }
168    }
169}
170
171/// Take Tuff's registrations back out of the harness's settings file,
172/// leaving everything else in it alone.
173///
174/// The registrations are matched by command, the way the lockfile records
175/// them, so this needs no shape: a grouped entry is found inside its
176/// group's `hooks`, a flat entry is the group itself, and a group or an
177/// event left empty is pruned so the file reads as if Tuff had never
178/// written to it.
179///
180/// Returns whether the file was rewritten, so the caller can say so.
181pub fn remove_registrations(
182    settings_relpath: &str,
183    repo_root: &Path,
184    managed_hooks: &[ManagedHook],
185) -> Result<bool> {
186    if managed_hooks.is_empty() {
187        return Ok(false);
188    }
189    let settings_path = repo_root.join(settings_relpath);
190    if !settings_path.is_file() {
191        return Ok(false);
192    }
193    let existing = std::fs::read(&settings_path)?;
194    let Some(updated) = without_registrations(settings_relpath, &existing, managed_hooks)? else {
195        return Ok(false);
196    };
197    std::fs::write(&settings_path, updated)?;
198    Ok(true)
199}
200
201/// `remove_registrations` on a settings file's bytes: the bytes it should
202/// hold without the registrations, or `None` when it has no `hooks` object
203/// to take them from.
204pub fn without_registrations(
205    settings_relpath: &str,
206    existing: &[u8],
207    managed_hooks: &[ManagedHook],
208) -> Result<Option<Vec<u8>>> {
209    let mut settings: serde_json::Value = serde_json::from_slice(existing)?;
210    let Some(hooks) = settings
211        .get_mut("hooks")
212        .and_then(|hooks| hooks.as_object_mut())
213    else {
214        return Ok(None);
215    };
216    let mut empty_events = Vec::new();
217    for (event, groups) in hooks.iter_mut() {
218        let Some(groups) = groups.as_array_mut() else {
219            continue;
220        };
221        let registered: Vec<&str> = managed_hooks
222            .iter()
223            .filter(|hook| hook.settings_path == settings_relpath && hook.event == *event)
224            .map(|hook| hook.command.as_str())
225            .collect();
226        let is_registered = |entry: &serde_json::Value| {
227            entry
228                .get("command")
229                .and_then(serde_json::Value::as_str)
230                .is_some_and(|command| registered.contains(&command))
231        };
232        for group in groups.iter_mut() {
233            if let Some(entries) = group
234                .get_mut("hooks")
235                .and_then(|value| value.as_array_mut())
236            {
237                entries.retain(|entry| !is_registered(entry));
238            }
239        }
240        groups.retain(
241            |group| match group.get("hooks").and_then(|value| value.as_array()) {
242                Some(entries) => !entries.is_empty(),
243                None => !is_registered(group),
244            },
245        );
246        if groups.is_empty() {
247            empty_events.push(event.clone());
248        }
249    }
250    for event in empty_events {
251        hooks.remove(&event);
252    }
253    Ok(Some(
254        (serde_json::to_string_pretty(&settings)? + "\n").into_bytes(),
255    ))
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261
262    fn managed(settings_path: &str, event: &str, command: &str) -> ManagedHook {
263        ManagedHook {
264            settings_path: settings_path.to_string(),
265            event: event.to_string(),
266            canonical_event: None,
267            command: command.to_string(),
268            baseline_hash: String::new(),
269        }
270    }
271
272    #[test]
273    fn a_grouped_fragment_registers_a_typed_entry_inside_a_group() {
274        let fragment = HookSettingsShape::Grouped.command_fragment("PreToolUse", "sh run.sh");
275        assert_eq!(
276            fragment,
277            serde_json::json!({
278                "hooks": {"PreToolUse": [{"hooks": [{"type": "command", "command": "sh run.sh"}]}]}
279            })
280        );
281    }
282
283    #[test]
284    fn a_flat_fragment_registers_the_entry_directly_and_declares_a_version() {
285        let fragment = HookSettingsShape::Flat.command_fragment("preToolUse", "sh run.sh");
286        assert_eq!(
287            fragment,
288            serde_json::json!({
289                "version": 1,
290                "hooks": {"preToolUse": [{"command": "sh run.sh"}]}
291            })
292        );
293    }
294
295    #[test]
296    fn merging_the_same_fragment_twice_does_not_duplicate_the_hook() {
297        // tuff#83: the harness ran a hook once per copy. Pinned for both
298        // shapes, since the fix once had to be applied in four places.
299        for shape in [HookSettingsShape::Grouped, HookSettingsShape::Flat] {
300            let fragment = shape.command_fragment("before_finish", "sh .agents/hooks/x/run.sh");
301            let once = shape
302                .merge_fragment("settings.json", None, &fragment)
303                .expect("first merge");
304            let twice = shape
305                .merge_fragment("settings.json", Some(&once), &fragment)
306                .expect("second merge");
307            let settings: serde_json::Value = serde_json::from_slice(&twice).unwrap();
308            assert_eq!(
309                settings["hooks"]["before_finish"].as_array().unwrap().len(),
310                1,
311                "{shape:?}: re-adding a hook must not register it twice"
312            );
313            assert_eq!(
314                once, twice,
315                "{shape:?}: a redundant merge must leave the file unchanged"
316            );
317        }
318    }
319
320    #[test]
321    fn merging_keeps_what_the_user_already_had() {
322        let existing = br#"{"permissions": {"allow": ["Bash"]}, "hooks": {"Stop": [{"hooks": [{"type": "command", "command": "theirs"}]}]}}"#;
323        let fragment = HookSettingsShape::Grouped.command_fragment("Stop", "ours");
324        let merged = HookSettingsShape::Grouped
325            .merge_fragment(".claude/settings.json", Some(existing), &fragment)
326            .unwrap();
327        let settings: serde_json::Value = serde_json::from_slice(&merged).unwrap();
328        assert_eq!(settings["permissions"]["allow"][0], "Bash");
329        let groups = settings["hooks"]["Stop"].as_array().unwrap();
330        assert_eq!(groups.len(), 2);
331        assert_eq!(groups[0]["hooks"][0]["command"], "theirs");
332        assert_eq!(groups[1]["hooks"][0]["command"], "ours");
333    }
334
335    #[test]
336    fn a_flat_file_without_a_version_gains_one() {
337        let existing = br#"{"hooks": {}}"#;
338        let fragment = HookSettingsShape::Flat.command_fragment("stop", "sh run.sh");
339        let merged = HookSettingsShape::Flat
340            .merge_fragment(".cursor/hooks.json", Some(existing), &fragment)
341            .unwrap();
342        let settings: serde_json::Value = serde_json::from_slice(&merged).unwrap();
343        assert_eq!(settings["version"], 1);
344    }
345
346    #[test]
347    fn a_whole_settings_file_is_refused_as_a_fragment() {
348        let full = serde_json::json!({"permissions": {}, "hooks": {}});
349        let error = HookSettingsShape::Grouped
350            .validate_fragment(&full)
351            .unwrap_err();
352        assert!(error.to_string().contains("hooks-only"), "{error}");
353
354        // The flat shape carries its version beside the hooks, and only that.
355        HookSettingsShape::Flat
356            .validate_fragment(&serde_json::json!({"version": 1, "hooks": {}}))
357            .unwrap();
358        let error = HookSettingsShape::Flat
359            .validate_fragment(&full)
360            .unwrap_err();
361        assert!(error.to_string().contains("optional 'version'"), "{error}");
362
363        for shape in [HookSettingsShape::Grouped, HookSettingsShape::Flat] {
364            assert!(shape.validate_fragment(&serde_json::json!([])).is_err());
365            assert!(shape.validate_fragment(&serde_json::json!({})).is_err());
366            assert!(
367                shape
368                    .validate_fragment(&serde_json::json!({"hooks": []}))
369                    .is_err()
370            );
371        }
372    }
373
374    #[test]
375    fn a_settings_file_that_is_not_an_object_is_reported_as_corrupt() {
376        let error = HookSettingsShape::Grouped
377            .merge_fragment(
378                ".claude/settings.json",
379                Some(b"[]"),
380                &HookSettingsShape::Grouped.command_fragment("Stop", "x"),
381            )
382            .unwrap_err();
383        assert!(
384            error
385                .to_string()
386                .contains(".claude/settings.json must be a JSON object"),
387            "{error}"
388        );
389    }
390
391    #[test]
392    fn removal_takes_out_only_tuff_registrations_in_either_shape() {
393        let temp = tempfile::tempdir().unwrap();
394        let grouped = r#"{"permissions": {}, "hooks": {"Stop": [{"hooks": [{"type": "command", "command": "theirs"}, {"type": "command", "command": "ours"}]}], "PreToolUse": [{"hooks": [{"type": "command", "command": "ours"}]}]}}"#;
395        std::fs::create_dir_all(temp.path().join(".claude")).unwrap();
396        std::fs::write(temp.path().join(".claude/settings.json"), grouped).unwrap();
397        remove_registrations(
398            ".claude/settings.json",
399            temp.path(),
400            &[
401                managed(".claude/settings.json", "Stop", "ours"),
402                managed(".claude/settings.json", "PreToolUse", "ours"),
403                managed(".cursor/hooks.json", "stop", "theirs"),
404            ],
405        )
406        .unwrap();
407        let settings: serde_json::Value = serde_json::from_str(
408            &std::fs::read_to_string(temp.path().join(".claude/settings.json")).unwrap(),
409        )
410        .unwrap();
411        assert_eq!(
412            settings,
413            serde_json::json!({
414                "permissions": {},
415                "hooks": {"Stop": [{"hooks": [{"type": "command", "command": "theirs"}]}]}
416            }),
417            "the event Tuff emptied is pruned; the other file's registration is ignored"
418        );
419
420        let flat = r#"{"version": 1, "hooks": {"stop": [{"command": "theirs"}, {"command": "ours"}], "preToolUse": [{"command": "ours"}]}}"#;
421        std::fs::create_dir_all(temp.path().join(".cursor")).unwrap();
422        std::fs::write(temp.path().join(".cursor/hooks.json"), flat).unwrap();
423        remove_registrations(
424            ".cursor/hooks.json",
425            temp.path(),
426            &[
427                managed(".cursor/hooks.json", "stop", "ours"),
428                managed(".cursor/hooks.json", "preToolUse", "ours"),
429            ],
430        )
431        .unwrap();
432        let settings: serde_json::Value = serde_json::from_str(
433            &std::fs::read_to_string(temp.path().join(".cursor/hooks.json")).unwrap(),
434        )
435        .unwrap();
436        assert_eq!(
437            settings,
438            serde_json::json!({"version": 1, "hooks": {"stop": [{"command": "theirs"}]}})
439        );
440    }
441
442    #[test]
443    fn removal_with_nothing_registered_or_no_file_is_a_no_op() {
444        let temp = tempfile::tempdir().unwrap();
445        remove_registrations(".claude/settings.json", temp.path(), &[]).unwrap();
446        remove_registrations(
447            ".claude/settings.json",
448            temp.path(),
449            &[managed(".claude/settings.json", "Stop", "ours")],
450        )
451        .unwrap();
452        assert!(!temp.path().join(".claude/settings.json").exists());
453    }
454}