kaeru 0.1.5

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! Agents' hook files, such as Claude Code's `settings.json` and Codex's
//! `hooks.json`: adding kaeru's `SessionStart` hook, and taking it out again,
//! without touching anything else in the file. Both files use the same shape:
//! `{"hooks": {"SessionStart": [{"hooks": [{"type": "command", ...}]}]}}`.
//! Codex shows a hook's `statusMessage` as its name when it asks you to trust
//! the hook, so kaeru's Codex hook has one.

use anyhow::{Context, Result};
use serde_json::{Value, json};

/// Returns whether the file's JSON runs `command` from a `SessionStart` hook.
pub fn has_hook(root: &Value, command: &str) -> bool {
    root.pointer("/hooks/SessionStart")
        .and_then(Value::as_array)
        .is_some_and(|groups| groups.iter().any(|group| runs(group, command)))
}

/// Returns whether a group of hooks runs `command`.
fn runs(group: &Value, command: &str) -> bool {
    group
        .get("hooks")
        .and_then(Value::as_array)
        .is_some_and(|hooks| hooks.iter().any(|hook| is(hook, command)))
}

/// Returns whether a hook is the command hook that runs `command`.
fn is(hook: &Value, command: &str) -> bool {
    hook.get("command").and_then(Value::as_str) == Some(command)
}

/// Adds a `SessionStart` hook that runs `command`, unless the JSON has one,
/// with `name` as its `statusMessage` when there is one. Returns whether it
/// changed anything.
///
/// # Errors
///
/// Fails when the JSON, its `hooks` or its `SessionStart` has another shape,
/// which kaeru leaves alone.
pub fn add_hook(root: &mut Value, command: &str, name: Option<&str>) -> Result<bool> {
    if has_hook(root, command) {
        return Ok(false);
    }
    let file = root
        .as_object_mut()
        .context("the file isn't a JSON object")?;
    let hooks = file
        .entry("hooks")
        .or_insert_with(|| json!({}))
        .as_object_mut()
        .context("its \"hooks\" isn't an object")?;
    let start = hooks
        .entry("SessionStart")
        .or_insert_with(|| json!([]))
        .as_array_mut()
        .context("its \"hooks.SessionStart\" isn't a list")?;
    let mut hook = json!({ "type": "command", "command": command });
    if let Some(name) = name {
        hook["statusMessage"] = json!(name);
    }
    start.push(json!({ "hooks": [hook] }));
    Ok(true)
}

/// Takes every `SessionStart` hook that runs `command` out of the JSON, along
/// with the lists and objects that this leaves empty. Returns whether it
/// changed anything.
pub fn remove_hook(root: &mut Value, command: &str) -> bool {
    let before = root.clone();
    if let Some(start) = root
        .pointer_mut("/hooks/SessionStart")
        .and_then(Value::as_array_mut)
    {
        for group in start.iter_mut() {
            if let Some(hooks) = group.get_mut("hooks").and_then(Value::as_array_mut) {
                hooks.retain(|hook| !is(hook, command));
            }
        }
        start.retain(|group| {
            group
                .get("hooks")
                .and_then(Value::as_array)
                .is_none_or(|hooks| !hooks.is_empty())
        });
    }
    if let Some(hooks) = root.get_mut("hooks").and_then(Value::as_object_mut) {
        if hooks
            .get("SessionStart")
            .and_then(Value::as_array)
            .is_some_and(Vec::is_empty)
        {
            hooks.remove("SessionStart");
        }
        if hooks.is_empty()
            && let Some(file) = root.as_object_mut()
        {
            file.remove("hooks");
        }
    }
    *root != before
}

#[cfg(test)]
mod tests {
    use super::*;

    const COMMAND: &str = "kaeru hook claude";

    #[test]
    fn the_hook_is_added_and_everything_else_is_kept() {
        let mut root = json!({
            "model": "some-model",
            "hooks": {
                "SessionStart": [{ "hooks": [{ "type": "command", "command": "other" }] }],
                "Stop": [{ "hooks": [{ "type": "command", "command": "notify" }] }]
            }
        });
        assert!(add_hook(&mut root, COMMAND, None).unwrap());
        assert!(has_hook(&root, COMMAND));
        assert!(has_hook(&root, "other"));
        assert_eq!(root["model"], "some-model");
        assert_eq!(root["hooks"]["Stop"][0]["hooks"][0]["command"], "notify");
    }

    #[test]
    fn adding_twice_changes_nothing() {
        let mut root = json!({});
        assert!(add_hook(&mut root, COMMAND, None).unwrap());
        let once = root.clone();
        assert!(!add_hook(&mut root, COMMAND, None).unwrap());
        assert_eq!(root, once);
    }

    #[test]
    fn a_hook_can_have_a_name() {
        let mut root = json!({});
        add_hook(&mut root, "kaeru hook codex", Some("kaeru: test")).unwrap();
        assert_eq!(
            root,
            json!({ "hooks": { "SessionStart": [{ "hooks": [{
                "type": "command",
                "command": "kaeru hook codex",
                "statusMessage": "kaeru: test"
            }] }] } })
        );
        assert!(remove_hook(&mut root, "kaeru hook codex"));
        assert_eq!(root, json!({}));
    }

    #[test]
    fn removing_leaves_the_file_as_it_was() {
        let original = json!({
            "model": "some-model",
            "hooks": { "Stop": [{ "hooks": [{ "type": "command", "command": "notify" }] }] }
        });
        let mut root = original.clone();
        add_hook(&mut root, COMMAND, None).unwrap();
        assert!(remove_hook(&mut root, COMMAND));
        assert_eq!(root, original);
        assert!(!remove_hook(&mut root, COMMAND));
    }

    #[test]
    fn removing_from_a_file_with_only_kaeru_s_hook_empties_it() {
        let mut root = json!({});
        add_hook(&mut root, COMMAND, None).unwrap();
        remove_hook(&mut root, COMMAND);
        assert_eq!(root, json!({}));
    }

    #[test]
    fn a_file_of_another_shape_is_left_alone() {
        let mut root = json!({ "hooks": "not an object" });
        assert!(add_hook(&mut root, COMMAND, None).is_err());
        assert_eq!(root, json!({ "hooks": "not an object" }));
        assert!(add_hook(&mut json!([1, 2]), COMMAND, None).is_err());
    }

    #[test]
    fn the_key_order_of_the_file_is_kept() {
        let mut root: Value = serde_json::from_str(r#"{"zeta":1,"alpha":2}"#).unwrap();
        add_hook(&mut root, COMMAND, None).unwrap();
        let text = serde_json::to_string(&root).unwrap();
        assert!(text.starts_with(r#"{"zeta":1,"alpha":2,"hooks""#));
    }
}