use std::path::Path;
use kintsugi_core::{shell, Class, Decision, ObservedIngest, ProposedCommand};
use kintsugi_daemon::Client;
use serde::Deserialize;
pub use crate::dialect::HookOutcome;
use crate::dialect::{self, Dialect, Parsed, Resolved};
use crate::observe;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum HookEvent {
#[default]
PreToolUse,
Write,
}
pub fn handle_with(dialect: Dialect, input: &str) -> HookOutcome {
handle_with_event(dialect, input, HookEvent::PreToolUse)
}
pub fn handle_with_event(dialect: Dialect, input: &str, event: HookEvent) -> HookOutcome {
if event == HookEvent::Write {
observe_write_call(dialect, input);
if !matches!(dialect.parse(input), Parsed::Shell(_)) {
return HookOutcome::silent();
}
eprintln!(
"kintsugi-hook: --event write received a shell payload — honouring the gate instead of \
only observing; check the {} hook registration",
dialect.agent_id()
);
}
if is_post_tool_use(input) {
observe_post_call(dialect, input);
return HookOutcome::silent();
}
let parsed = match dialect.parse(input) {
Parsed::Shell(s) => s,
Parsed::NotShell => {
observe_content_call(dialect, input);
return HookOutcome::silent();
}
Parsed::Bad(e) => {
eprintln!(
"kintsugi-hook: could not parse {} payload: {e}",
dialect.agent_id()
);
return HookOutcome::silent();
}
};
let argv = shell::split(&parsed.command);
let session = parsed.session_id.clone();
let cwd = parsed.cwd.clone();
let proposed =
ProposedCommand::new(dialect.agent_id(), parsed.cwd, argv.clone(), parsed.command)
.with_session(parsed.session_id);
match Client::send(&proposed) {
Ok(verdict) => {
let resolved = match dialect::resolve(&verdict) {
Resolved::Deny(reason)
if verdict.decision == Decision::Hold
&& verdict.class == Class::Catastrophic =>
{
Resolved::Deny(held_for_approval(&reason, &proposed.id.to_string()))
}
other => other,
};
let outcome = dialect.format(&resolved);
if matches!(resolved, Resolved::Allow) {
observe_shell_ingest(dialect, &argv, session.as_deref(), &cwd);
}
outcome
}
Err(e) => {
if kintsugi_core::classify(&proposed).class == Class::Catastrophic {
eprintln!(
"kintsugi-hook: daemon unreachable; denying catastrophic (fail-closed): {e}"
);
dialect.format(&dialect::Resolved::Deny(
"Kintsugi daemon unreachable; catastrophic command blocked (fail-closed)"
.into(),
))
} else if fail_closed() {
eprintln!("kintsugi-hook: daemon unreachable; denying (fail-closed): {e}");
dialect.format(&dialect::Resolved::Deny(
"Kintsugi daemon unreachable (fail-closed)".into(),
))
} else {
eprintln!("kintsugi-hook: warning: daemon unreachable; allowing unguarded: {e}");
dialect.pass()
}
}
}
}
pub fn handle(input: &str) -> HookOutcome {
handle_with(Dialect::Claude, input)
}
fn observe_content_call(dialect: Dialect, input: &str) {
let Some(call) = dialect.parse_content(input) else {
return;
};
if let Some(src) = observe::classify_tool_ingest(&call.tool, &call.input, &call.cwd) {
send_ingest(dialect, src, call.session_id.as_deref(), &call.cwd);
}
}
fn observe_post_call(dialect: Dialect, input: &str) {
let Some(call) = dialect.parse_post(input) else {
return;
};
if let Some(src) =
observe::classify_result_ingest(&call.tool, &call.input, &call.response, &call.cwd)
{
send_ingest(dialect, src, call.session_id.as_deref(), &call.cwd);
}
if let Some(path) = observe::classify_tool_read(&call.tool, &call.input, &call.cwd) {
send_read(call.session_id.as_deref(), &path, &call.cwd);
}
}
fn observe_write_call(dialect: Dialect, input: &str) {
let Some(call) = dialect.parse_write(input) else {
return;
};
if let Some(path) = observe::classify_tool_write(&call.tool, &call.input, &call.cwd) {
send_write(call.session_id.as_deref(), &path, &call.cwd);
}
}
fn send_write(session: Option<&str>, path: &str, cwd: &Path) {
let Some(session) = session.filter(|s| !s.is_empty()) else {
return;
};
let _ = Client::write_observed(session, path, cwd);
}
fn send_read(session: Option<&str>, path: &str, cwd: &Path) {
let Some(session) = session.filter(|s| !s.is_empty()) else {
return;
};
let _ = Client::read_observed(session, path, cwd);
}
#[derive(Debug, Deserialize)]
struct EventMarker {
#[serde(default)]
hook_event_name: Option<String>,
}
fn is_post_tool_use(input: &str) -> bool {
serde_json::from_str::<EventMarker>(input)
.ok()
.and_then(|e| e.hook_event_name)
.is_some_and(|name| name == "PostToolUse")
}
fn observe_shell_ingest(dialect: Dialect, argv: &[String], session: Option<&str>, cwd: &Path) {
if let Some(src) = observe::classify_shell_ingest(argv) {
send_ingest(dialect, src, session, cwd);
}
}
fn send_ingest(dialect: Dialect, src: observe::IngestSource, session: Option<&str>, cwd: &Path) {
let Some(session) = session.filter(|s| !s.is_empty()) else {
return;
};
let observed = ObservedIngest::now(src.kind, src.id, dialect.agent_id(), session, cwd);
let _ = Client::ingest(&observed);
}
fn held_for_approval(reason: &str, id: &str) -> String {
let short = id.get(..8).unwrap_or(id);
format!(
"{reason} Kintsugi blocked this catastrophic command — do NOT run it or try to work \
around it. Stop and tell the user: if they want it, they can approve it in the Kintsugi \
app (Held → Approve & run) or run `kintsugi run {short}` in their terminal — either way \
it is snapshotted first, so `kintsugi undo` can roll it back. You will not resume \
automatically; once they've handled it, they can tell you to continue."
)
}
fn fail_closed() -> bool {
kintsugi_daemon::is_fail_closed_marked()
|| matches!(
std::env::var("KINTSUGI_FAIL_CLOSED").ok().as_deref(),
Some("1") | Some("true") | Some("yes")
)
}
pub fn dialect_from_args<I: IntoIterator<Item = String>>(args: I) -> Dialect {
let mut it = args.into_iter();
while let Some(a) = it.next() {
let value = if let Some(v) = a.strip_prefix("--agent=") {
Some(v.to_string())
} else if a == "--agent" {
it.next()
} else {
None
};
if let Some(v) = value {
match Dialect::from_agent(&v) {
Some(d) => return d,
None => {
eprintln!("kintsugi-hook: unknown --agent '{v}', defaulting to claude-code");
return Dialect::Claude;
}
}
}
}
Dialect::Claude
}
pub fn event_from_args<I: IntoIterator<Item = String>>(args: I) -> HookEvent {
let mut it = args.into_iter();
while let Some(a) = it.next() {
let value = if let Some(v) = a.strip_prefix("--event=") {
Some(v.to_string())
} else if a == "--event" {
it.next()
} else {
None
};
if let Some(v) = value {
return match v.as_str() {
"write" => HookEvent::Write,
other => {
eprintln!("kintsugi-hook: unknown --event '{other}', using the pre-tool path");
HookEvent::PreToolUse
}
};
}
}
HookEvent::PreToolUse
}
pub fn run() -> i32 {
let args: Vec<String> = std::env::args().skip(1).collect();
let dialect = dialect_from_args(args.iter().cloned());
let event = event_from_args(args);
let stdin = std::io::stdin();
let stdout = std::io::stdout();
run_io_event(dialect, event, stdin.lock(), stdout.lock())
}
pub fn run_io<R: std::io::Read, W: std::io::Write>(dialect: Dialect, reader: R, writer: W) -> i32 {
run_io_event(dialect, HookEvent::PreToolUse, reader, writer)
}
pub fn run_io_event<R: std::io::Read, W: std::io::Write>(
dialect: Dialect,
event: HookEvent,
mut reader: R,
mut writer: W,
) -> i32 {
let mut input = String::new();
if let Err(e) = reader.read_to_string(&mut input) {
eprintln!("kintsugi-hook: failed to read stdin: {e}");
return 0; }
let outcome = handle_with_event(dialect, &input, event);
if let Some(out) = outcome.stdout {
let _ = writeln!(writer, "{out}");
}
outcome.exit_code
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn non_shell_tool_is_allowed_silently() {
let payload = r#"{"tool_name":"Edit","tool_input":{"file_path":"x"}}"#;
assert_eq!(handle(payload), HookOutcome::silent());
}
#[test]
fn held_for_approval_guides_stop_approve_continue() {
let msg = held_for_approval("recursively deletes files.", "abcd1234-5678-90ab-cdef");
assert!(msg.contains("recursively deletes files."));
assert!(
msg.contains("do NOT run it") && msg.contains("work around"),
"must tell the agent to stop, not run or work around it"
);
assert!(
msg.contains("Kintsugi app") || msg.contains("Approve & run"),
"should point at approving in the app"
);
assert!(
msg.contains("kintsugi run abcd1234"),
"should give the guarded CLI run command with the short id"
);
assert!(msg.contains("undo"), "should mention reversibility");
assert!(
msg.contains("continue"),
"should set up the human-driven resume (tell the agent to continue)"
);
}
#[test]
fn malformed_payload_is_allowed_silently() {
assert_eq!(handle("not json"), HookOutcome::silent());
}
#[test]
fn empty_command_is_allowed_silently() {
let payload = r#"{"tool_name":"Bash","tool_input":{"command":" "}}"#;
assert_eq!(handle(payload), HookOutcome::silent());
}
#[test]
fn run_io_allows_non_shell_tool_silently() {
let input = br#"{"tool_name":"Edit","tool_input":{"file_path":"x"}}"#;
let mut out = Vec::new();
let code = run_io(Dialect::Claude, &input[..], &mut out);
assert_eq!(code, 0);
assert!(out.is_empty(), "allow-silent writes nothing");
}
#[test]
fn dialect_from_args_reads_flag_forms() {
assert_eq!(
dialect_from_args(["--agent".to_string(), "cursor".to_string()]),
Dialect::Cursor
);
assert_eq!(
dialect_from_args(["--agent=qwen".to_string()]),
Dialect::Qwen
);
assert_eq!(dialect_from_args(Vec::<String>::new()), Dialect::Claude);
assert_eq!(
dialect_from_args(["--agent=banana".to_string()]),
Dialect::Claude
);
}
#[test]
fn post_tool_use_event_is_observed_never_gated() {
let payload = r#"{
"hook_event_name": "PostToolUse",
"tool_name": "WebFetch",
"tool_input": { "url": "https://example.com/p" },
"tool_response": "page body",
"cwd": "/work"
}"#;
assert_eq!(handle(payload), HookOutcome::silent());
}
#[test]
fn post_tool_use_shell_result_is_never_rejudged_as_a_proposal() {
let payload = r#"{
"hook_event_name": "PostToolUse",
"tool_name": "Bash",
"tool_input": { "command": "rm -rf /" },
"tool_response": "done"
}"#;
assert_eq!(handle(payload), HookOutcome::silent());
}
#[test]
fn is_post_tool_use_matches_only_the_explicit_event_marker() {
assert!(is_post_tool_use(
r#"{"hook_event_name":"PostToolUse","tool_name":"Read"}"#
));
assert!(!is_post_tool_use(
r#"{"hook_event_name":"PreToolUse","tool_name":"Bash"}"#
));
assert!(!is_post_tool_use(
r#"{"hook_event_name":"postToolUse","tool_name":"Bash"}"#
));
assert!(!is_post_tool_use(r#"{"tool_name":"Bash"}"#));
assert!(!is_post_tool_use("not json"));
assert!(!is_post_tool_use(r#"["an array"]"#));
assert!(!is_post_tool_use("42"));
}
#[test]
fn event_from_args_defaults_to_the_pre_tool_path() {
assert_eq!(event_from_args(Vec::<String>::new()), HookEvent::PreToolUse);
assert_eq!(
event_from_args(["--agent".to_string(), "opencode".to_string()]),
HookEvent::PreToolUse
);
assert_eq!(
event_from_args(["--event".to_string(), "writes".to_string()]),
HookEvent::PreToolUse
);
assert_eq!(
event_from_args(["--event".to_string(), "write".to_string()]),
HookEvent::Write
);
assert_eq!(
event_from_args(["--agent=opencode".to_string(), "--event=write".to_string()]),
HookEvent::Write
);
}
#[test]
fn a_write_event_is_observation_only_and_never_gates() {
let payload = r#"{
"tool": "write",
"args": { "filePath": "/work/repo/src/notes.rs" },
"cwd": "/work/repo"
}"#;
assert_eq!(
handle_with_event(Dialect::OpenCode, payload, HookEvent::Write),
HookOutcome::silent()
);
}
#[test]
fn a_write_event_falls_through_to_the_gate_for_shell_payloads() {
let file_write =
r#"{"tool":"write","args":{"filePath":"/work/repo/x.rs"},"cwd":"/work/repo"}"#;
assert_eq!(
handle_with_event(Dialect::OpenCode, file_write, HookEvent::Write),
HookOutcome::silent()
);
assert_eq!(
handle_with_event(Dialect::OpenCode, "not json", HookEvent::Write),
HookOutcome::silent()
);
let shell = r#"{"command":"rm -rf /","cwd":"/work"}"#;
assert_ne!(
handle_with_event(Dialect::Cursor, shell, HookEvent::Write),
HookOutcome::silent(),
"a shell payload on the write route must not be waved through"
);
}
#[test]
fn run_io_event_handles_the_write_route() {
let input = br#"{"tool":"write","args":{"filePath":"/work/repo/x"},"cwd":"/work/repo"}"#;
let mut out = Vec::new();
let code = run_io_event(Dialect::OpenCode, HookEvent::Write, &input[..], &mut out);
assert_eq!(code, 0);
assert!(out.is_empty(), "a write observation writes nothing");
}
}