1use std::path::Path;
18
19use kintsugi_core::{shell, Class, Decision, ObservedIngest, ProposedCommand};
20use kintsugi_daemon::Client;
21use serde::Deserialize;
22
23pub use crate::dialect::HookOutcome;
24
25use crate::dialect::{self, Dialect, Parsed, Resolved};
26use crate::observe;
27
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
33pub enum HookEvent {
34 #[default]
36 PreToolUse,
37 Write,
41}
42
43pub fn handle_with(dialect: Dialect, input: &str) -> HookOutcome {
45 handle_with_event(dialect, input, HookEvent::PreToolUse)
46}
47
48pub fn handle_with_event(dialect: Dialect, input: &str, event: HookEvent) -> HookOutcome {
54 if event == HookEvent::Write {
55 observe_write_call(dialect, input);
56 if !matches!(dialect.parse(input), Parsed::Shell(_)) {
61 return HookOutcome::silent();
62 }
63 eprintln!(
64 "kintsugi-hook: --event write received a shell payload — honouring the gate instead of \
65 only observing; check the {} hook registration",
66 dialect.agent_id()
67 );
68 }
69 if is_post_tool_use(input) {
76 observe_post_call(dialect, input);
77 return HookOutcome::silent();
78 }
79 let parsed = match dialect.parse(input) {
80 Parsed::Shell(s) => s,
81 Parsed::NotShell => {
82 observe_content_call(dialect, input);
86 return HookOutcome::silent();
87 }
88 Parsed::Bad(e) => {
89 eprintln!(
91 "kintsugi-hook: could not parse {} payload: {e}",
92 dialect.agent_id()
93 );
94 return HookOutcome::silent();
95 }
96 };
97
98 let argv = shell::split(&parsed.command);
99 let session = parsed.session_id.clone();
100 let cwd = parsed.cwd.clone();
101 let proposed =
102 ProposedCommand::new(dialect.agent_id(), parsed.cwd, argv.clone(), parsed.command)
103 .with_session(parsed.session_id);
104
105 match Client::send(&proposed) {
106 Ok(verdict) => {
107 let resolved = match dialect::resolve(&verdict) {
108 Resolved::Deny(reason)
114 if verdict.decision == Decision::Hold
115 && verdict.class == Class::Catastrophic =>
116 {
117 Resolved::Deny(held_for_approval(&reason, &proposed.id.to_string()))
118 }
119 other => other,
120 };
121 let outcome = dialect.format(&resolved);
122 if matches!(resolved, Resolved::Allow) {
127 observe_shell_ingest(dialect, &argv, session.as_deref(), &cwd);
128 }
129 outcome
130 }
131 Err(e) => {
132 if kintsugi_core::classify(&proposed).class == Class::Catastrophic {
136 eprintln!(
137 "kintsugi-hook: daemon unreachable; denying catastrophic (fail-closed): {e}"
138 );
139 dialect.format(&dialect::Resolved::Deny(
140 "Kintsugi daemon unreachable; catastrophic command blocked (fail-closed)"
141 .into(),
142 ))
143 } else if fail_closed() {
144 eprintln!("kintsugi-hook: daemon unreachable; denying (fail-closed): {e}");
145 dialect.format(&dialect::Resolved::Deny(
146 "Kintsugi daemon unreachable (fail-closed)".into(),
147 ))
148 } else {
149 eprintln!("kintsugi-hook: warning: daemon unreachable; allowing unguarded: {e}");
150 dialect.pass()
151 }
152 }
153 }
154}
155
156pub fn handle(input: &str) -> HookOutcome {
158 handle_with(Dialect::Claude, input)
159}
160
161fn observe_content_call(dialect: Dialect, input: &str) {
166 let Some(call) = dialect.parse_content(input) else {
167 return;
168 };
169 if let Some(src) = observe::classify_tool_ingest(&call.tool, &call.input, &call.cwd) {
170 send_ingest(dialect, src, call.session_id.as_deref(), &call.cwd);
171 }
172}
173
174fn observe_post_call(dialect: Dialect, input: &str) {
181 let Some(call) = dialect.parse_post(input) else {
182 return;
183 };
184 if let Some(src) =
187 observe::classify_result_ingest(&call.tool, &call.input, &call.response, &call.cwd)
188 {
189 send_ingest(dialect, src, call.session_id.as_deref(), &call.cwd);
190 }
191 if let Some(path) = observe::classify_tool_read(&call.tool, &call.input, &call.cwd) {
194 send_read(call.session_id.as_deref(), &path, &call.cwd);
195 }
196}
197
198fn observe_write_call(dialect: Dialect, input: &str) {
204 let Some(call) = dialect.parse_write(input) else {
205 return;
206 };
207 if let Some(path) = observe::classify_tool_write(&call.tool, &call.input, &call.cwd) {
208 send_write(call.session_id.as_deref(), &path, &call.cwd);
209 }
210}
211
212fn send_write(session: Option<&str>, path: &str, cwd: &Path) {
217 let Some(session) = session.filter(|s| !s.is_empty()) else {
218 return;
219 };
220 let _ = Client::write_observed(session, path, cwd);
221}
222
223fn send_read(session: Option<&str>, path: &str, cwd: &Path) {
227 let Some(session) = session.filter(|s| !s.is_empty()) else {
228 return;
229 };
230 let _ = Client::read_observed(session, path, cwd);
231}
232
233#[derive(Debug, Deserialize)]
238struct EventMarker {
239 #[serde(default)]
240 hook_event_name: Option<String>,
241}
242
243fn is_post_tool_use(input: &str) -> bool {
246 serde_json::from_str::<EventMarker>(input)
247 .ok()
248 .and_then(|e| e.hook_event_name)
249 .is_some_and(|name| name == "PostToolUse")
250}
251
252fn observe_shell_ingest(dialect: Dialect, argv: &[String], session: Option<&str>, cwd: &Path) {
255 if let Some(src) = observe::classify_shell_ingest(argv) {
256 send_ingest(dialect, src, session, cwd);
257 }
258}
259
260fn send_ingest(dialect: Dialect, src: observe::IngestSource, session: Option<&str>, cwd: &Path) {
264 let Some(session) = session.filter(|s| !s.is_empty()) else {
265 return;
266 };
267 let observed = ObservedIngest::now(src.kind, src.id, dialect.agent_id(), session, cwd);
268 let _ = Client::ingest(&observed);
269}
270
271fn held_for_approval(reason: &str, id: &str) -> String {
283 let short = id.get(..8).unwrap_or(id);
284 format!(
285 "{reason} Kintsugi blocked this catastrophic command — do NOT run it or try to work \
286 around it. Stop and tell the user: if they want it, they can approve it in the Kintsugi \
287 app (Held → Approve & run) or run `kintsugi run {short}` in their terminal — either way \
288 it is snapshotted first, so `kintsugi undo` can roll it back. You will not resume \
289 automatically; once they've handled it, they can tell you to continue."
290 )
291}
292
293fn fail_closed() -> bool {
297 kintsugi_daemon::is_fail_closed_marked()
298 || matches!(
299 std::env::var("KINTSUGI_FAIL_CLOSED").ok().as_deref(),
300 Some("1") | Some("true") | Some("yes")
301 )
302}
303
304pub fn dialect_from_args<I: IntoIterator<Item = String>>(args: I) -> Dialect {
309 let mut it = args.into_iter();
310 while let Some(a) = it.next() {
311 let value = if let Some(v) = a.strip_prefix("--agent=") {
312 Some(v.to_string())
313 } else if a == "--agent" {
314 it.next()
315 } else {
316 None
317 };
318 if let Some(v) = value {
319 match Dialect::from_agent(&v) {
320 Some(d) => return d,
321 None => {
322 eprintln!("kintsugi-hook: unknown --agent '{v}', defaulting to claude-code");
323 return Dialect::Claude;
324 }
325 }
326 }
327 }
328 Dialect::Claude
329}
330
331pub fn event_from_args<I: IntoIterator<Item = String>>(args: I) -> HookEvent {
337 let mut it = args.into_iter();
338 while let Some(a) = it.next() {
339 let value = if let Some(v) = a.strip_prefix("--event=") {
340 Some(v.to_string())
341 } else if a == "--event" {
342 it.next()
343 } else {
344 None
345 };
346 if let Some(v) = value {
347 return match v.as_str() {
348 "write" => HookEvent::Write,
349 other => {
350 eprintln!("kintsugi-hook: unknown --event '{other}', using the pre-tool path");
351 HookEvent::PreToolUse
352 }
353 };
354 }
355 }
356 HookEvent::PreToolUse
357}
358
359pub fn run() -> i32 {
362 let args: Vec<String> = std::env::args().skip(1).collect();
363 let dialect = dialect_from_args(args.iter().cloned());
364 let event = event_from_args(args);
365 let stdin = std::io::stdin();
366 let stdout = std::io::stdout();
367 run_io_event(dialect, event, stdin.lock(), stdout.lock())
368}
369
370pub fn run_io<R: std::io::Read, W: std::io::Write>(dialect: Dialect, reader: R, writer: W) -> i32 {
373 run_io_event(dialect, HookEvent::PreToolUse, reader, writer)
374}
375
376pub fn run_io_event<R: std::io::Read, W: std::io::Write>(
378 dialect: Dialect,
379 event: HookEvent,
380 mut reader: R,
381 mut writer: W,
382) -> i32 {
383 let mut input = String::new();
384 if let Err(e) = reader.read_to_string(&mut input) {
385 eprintln!("kintsugi-hook: failed to read stdin: {e}");
386 return 0; }
388 let outcome = handle_with_event(dialect, &input, event);
389 if let Some(out) = outcome.stdout {
390 let _ = writeln!(writer, "{out}");
391 }
392 outcome.exit_code
393}
394
395#[cfg(test)]
396mod tests {
397 use super::*;
398
399 #[test]
400 fn non_shell_tool_is_allowed_silently() {
401 let payload = r#"{"tool_name":"Edit","tool_input":{"file_path":"x"}}"#;
402 assert_eq!(handle(payload), HookOutcome::silent());
403 }
404
405 #[test]
406 fn held_for_approval_guides_stop_approve_continue() {
407 let msg = held_for_approval("recursively deletes files.", "abcd1234-5678-90ab-cdef");
408 assert!(msg.contains("recursively deletes files."));
409 assert!(
410 msg.contains("do NOT run it") && msg.contains("work around"),
411 "must tell the agent to stop, not run or work around it"
412 );
413 assert!(
414 msg.contains("Kintsugi app") || msg.contains("Approve & run"),
415 "should point at approving in the app"
416 );
417 assert!(
418 msg.contains("kintsugi run abcd1234"),
419 "should give the guarded CLI run command with the short id"
420 );
421 assert!(msg.contains("undo"), "should mention reversibility");
422 assert!(
423 msg.contains("continue"),
424 "should set up the human-driven resume (tell the agent to continue)"
425 );
426 }
427
428 #[test]
429 fn malformed_payload_is_allowed_silently() {
430 assert_eq!(handle("not json"), HookOutcome::silent());
431 }
432
433 #[test]
434 fn empty_command_is_allowed_silently() {
435 let payload = r#"{"tool_name":"Bash","tool_input":{"command":" "}}"#;
436 assert_eq!(handle(payload), HookOutcome::silent());
437 }
438
439 #[test]
440 fn run_io_allows_non_shell_tool_silently() {
441 let input = br#"{"tool_name":"Edit","tool_input":{"file_path":"x"}}"#;
442 let mut out = Vec::new();
443 let code = run_io(Dialect::Claude, &input[..], &mut out);
444 assert_eq!(code, 0);
445 assert!(out.is_empty(), "allow-silent writes nothing");
446 }
447
448 #[test]
449 fn dialect_from_args_reads_flag_forms() {
450 assert_eq!(
451 dialect_from_args(["--agent".to_string(), "cursor".to_string()]),
452 Dialect::Cursor
453 );
454 assert_eq!(
455 dialect_from_args(["--agent=qwen".to_string()]),
456 Dialect::Qwen
457 );
458 assert_eq!(dialect_from_args(Vec::<String>::new()), Dialect::Claude);
460 assert_eq!(
462 dialect_from_args(["--agent=banana".to_string()]),
463 Dialect::Claude
464 );
465 }
466
467 #[test]
470 fn post_tool_use_event_is_observed_never_gated() {
471 let payload = r#"{
474 "hook_event_name": "PostToolUse",
475 "tool_name": "WebFetch",
476 "tool_input": { "url": "https://example.com/p" },
477 "tool_response": "page body",
478 "cwd": "/work"
479 }"#;
480 assert_eq!(handle(payload), HookOutcome::silent());
481 }
482
483 #[test]
484 fn post_tool_use_shell_result_is_never_rejudged_as_a_proposal() {
485 let payload = r#"{
491 "hook_event_name": "PostToolUse",
492 "tool_name": "Bash",
493 "tool_input": { "command": "rm -rf /" },
494 "tool_response": "done"
495 }"#;
496 assert_eq!(handle(payload), HookOutcome::silent());
497 }
498
499 #[test]
500 fn is_post_tool_use_matches_only_the_explicit_event_marker() {
501 assert!(is_post_tool_use(
502 r#"{"hook_event_name":"PostToolUse","tool_name":"Read"}"#
503 ));
504 assert!(!is_post_tool_use(
508 r#"{"hook_event_name":"PreToolUse","tool_name":"Bash"}"#
509 ));
510 assert!(!is_post_tool_use(
511 r#"{"hook_event_name":"postToolUse","tool_name":"Bash"}"#
512 ));
513 assert!(!is_post_tool_use(r#"{"tool_name":"Bash"}"#));
514 assert!(!is_post_tool_use("not json"));
515 assert!(!is_post_tool_use(r#"["an array"]"#));
516 assert!(!is_post_tool_use("42"));
517 }
518
519 #[test]
522 fn event_from_args_defaults_to_the_pre_tool_path() {
523 assert_eq!(event_from_args(Vec::<String>::new()), HookEvent::PreToolUse);
526 assert_eq!(
527 event_from_args(["--agent".to_string(), "opencode".to_string()]),
528 HookEvent::PreToolUse
529 );
530 assert_eq!(
531 event_from_args(["--event".to_string(), "writes".to_string()]),
532 HookEvent::PreToolUse
533 );
534 assert_eq!(
536 event_from_args(["--event".to_string(), "write".to_string()]),
537 HookEvent::Write
538 );
539 assert_eq!(
540 event_from_args(["--agent=opencode".to_string(), "--event=write".to_string()]),
541 HookEvent::Write
542 );
543 }
544
545 #[test]
546 fn a_write_event_is_observation_only_and_never_gates() {
547 let payload = r#"{
550 "tool": "write",
551 "args": { "filePath": "/work/repo/src/notes.rs" },
552 "cwd": "/work/repo"
553 }"#;
554 assert_eq!(
555 handle_with_event(Dialect::OpenCode, payload, HookEvent::Write),
556 HookOutcome::silent()
557 );
558 }
559
560 #[test]
561 fn a_write_event_falls_through_to_the_gate_for_shell_payloads() {
562 let file_write =
567 r#"{"tool":"write","args":{"filePath":"/work/repo/x.rs"},"cwd":"/work/repo"}"#;
568 assert_eq!(
569 handle_with_event(Dialect::OpenCode, file_write, HookEvent::Write),
570 HookOutcome::silent()
571 );
572 assert_eq!(
574 handle_with_event(Dialect::OpenCode, "not json", HookEvent::Write),
575 HookOutcome::silent()
576 );
577 let shell = r#"{"command":"rm -rf /","cwd":"/work"}"#;
579 assert_ne!(
580 handle_with_event(Dialect::Cursor, shell, HookEvent::Write),
581 HookOutcome::silent(),
582 "a shell payload on the write route must not be waved through"
583 );
584 }
585
586 #[test]
587 fn run_io_event_handles_the_write_route() {
588 let input = br#"{"tool":"write","args":{"filePath":"/work/repo/x"},"cwd":"/work/repo"}"#;
589 let mut out = Vec::new();
590 let code = run_io_event(Dialect::OpenCode, HookEvent::Write, &input[..], &mut out);
591 assert_eq!(code, 0);
592 assert!(out.is_empty(), "a write observation writes nothing");
593 }
594}