second-brain-cli 0.13.0

Memory layer for AI coding agents: ingest, recall, and sync across machines
use std::io::Read;

use serde_json::Value;

mod asked;
mod context;
mod daemon;
mod project;
mod prompt;
mod session_start;
mod siblings;
mod stop;

pub(crate) struct HookEvent {
    pub(crate) event: &'static str,
    pub(crate) name: &'static str,
    /// Called with `event`, so a handler that serves several events can name
    /// the one it answers.
    run: fn(&'static str, &Value) -> Option<Value>,
}

pub(crate) const HOOK_EVENTS: &[HookEvent] = &[
    HookEvent {
        event: "Stop",
        name: "stop",
        run: stop::run,
    },
    HookEvent {
        event: "UserPromptSubmit",
        name: "prompt",
        run: prompt::run,
    },
    HookEvent {
        event: "SessionStart",
        name: "session-start",
        run: session_start::run,
    },
    HookEvent {
        event: "SubagentStart",
        name: "subagent-start",
        run: session_start::run,
    },
    HookEvent {
        event: "PostToolUse",
        name: "post-tool-use",
        run: siblings::run,
    },
];

/// Always exits 0 with nothing on stdout but the handler's reply: any other
/// output or status would surface in the agent's session as a hook error.
pub(crate) fn cmd_hook(name: Option<&str>) {
    let mut input = String::new();
    if let Err(e) = std::io::stdin().read_to_string(&mut input) {
        eprintln!("sb hook: reading the event from stdin failed: {e}");
        return;
    }
    let Some(hook) = HOOK_EVENTS.iter().find(|h| Some(h.name) == name) else {
        eprintln!("sb hook: no hook named {:?}", name.unwrap_or_default());
        return;
    };
    let Ok(event) = serde_json::from_str::<Value>(&input) else {
        return;
    };
    if let Some(reply) = (hook.run)(hook.event, &event) {
        println!("{reply}");
    }
}