1use serde_json::{json, Map, Value};
13use std::path::Path;
14
15use crate::Step;
16
17pub const RUNNERS: &[&str] = &[
19 "copilot",
20 "gemini",
21 "windsurf",
22 "factory",
23 "kiro",
24 "cline",
25 "qwen",
26 "crush",
27 "auggie",
28 "goose",
29 "amp",
30 "openhands",
31];
32
33#[derive(Clone, Copy)]
34struct RunnerContract {
35 asks: bool,
36 deny_by_exit: bool,
37}
38
39const RUNNER_CONTRACTS: &[(&str, RunnerContract)] = &[
40 (
41 "copilot",
42 RunnerContract {
43 asks: true,
44 deny_by_exit: false,
45 },
46 ),
47 (
48 "gemini",
49 RunnerContract {
50 asks: false,
51 deny_by_exit: false,
52 },
53 ),
54 (
55 "windsurf",
56 RunnerContract {
57 asks: false,
58 deny_by_exit: true,
59 },
60 ),
61 (
62 "factory",
63 RunnerContract {
64 asks: true,
65 deny_by_exit: true,
66 },
67 ),
68 (
69 "kiro",
70 RunnerContract {
71 asks: false,
72 deny_by_exit: true,
73 },
74 ),
75 (
76 "cline",
77 RunnerContract {
78 asks: false,
79 deny_by_exit: false,
80 },
81 ),
82 (
83 "qwen",
84 RunnerContract {
85 asks: true,
86 deny_by_exit: true,
87 },
88 ),
89 (
90 "crush",
91 RunnerContract {
92 asks: false,
93 deny_by_exit: true,
94 },
95 ),
96 (
97 "auggie",
98 RunnerContract {
99 asks: false,
100 deny_by_exit: false,
101 },
102 ),
103 (
104 "goose",
105 RunnerContract {
106 asks: false,
107 deny_by_exit: true,
108 },
109 ),
110 (
111 "amp",
112 RunnerContract {
113 asks: true,
114 deny_by_exit: true,
115 },
116 ),
117 (
118 "openhands",
119 RunnerContract {
120 asks: false,
121 deny_by_exit: true,
122 },
123 ),
124];
125
126fn contract(runner: &str) -> RunnerContract {
127 RUNNER_CONTRACTS
128 .iter()
129 .find_map(|(name, contract)| (*name == runner).then_some(*contract))
130 .unwrap_or(RunnerContract {
131 asks: false,
132 deny_by_exit: false,
133 })
134}
135
136fn needs_script(runner: &str) -> bool {
140 matches!(runner, "auggie" | "amp")
141}
142
143#[must_use]
145pub fn script_path(runner: &str, file: &Path) -> std::path::PathBuf {
146 file.parent()
147 .unwrap_or_else(|| Path::new("."))
148 .join(format!("ljos-guard-{runner}.sh"))
149}
150
151#[must_use]
153pub fn is_runner(name: &str) -> bool {
154 RUNNERS.contains(&name)
155}
156
157fn asks(runner: &str) -> bool {
159 contract(runner).asks
160}
161
162fn reason_stderr(reason: &str) -> String {
163 if reason.trim().is_empty() {
164 "ljos denied this command.\n".to_string()
165 } else {
166 format!("{reason}\n")
167 }
168}
169
170fn gemini_event(raw: &str) -> &str {
172 match raw {
173 "BeforeTool" => "PreToolUse",
174 "AfterTool" => "PostToolUse",
175 "BeforeAgent" => "UserPromptSubmit",
176 other => other,
177 }
178}
179
180fn command_of(args: &Value) -> Option<String> {
183 if let Some(c) = args["command"].as_str() {
184 return Some(c.to_string());
185 }
186 args["commands"].as_array().map(|list| {
187 list.iter()
188 .filter_map(Value::as_str)
189 .collect::<Vec<_>>()
190 .join("\n")
191 })
192}
193
194#[must_use]
199pub fn normalize_input(runner: &str, input: &str) -> String {
200 let Ok(v) = serde_json::from_str::<Value>(input.trim()) else {
201 return input.to_string();
202 };
203 let mut out = Map::new();
204 let put = |out: &mut Map<String, Value>, k: &str, val: Option<&str>| {
205 if let Some(s) = val.filter(|s| !s.is_empty()) {
206 out.insert(k.into(), Value::String(s.to_string()));
207 }
208 };
209 match runner {
210 "windsurf" => {
211 let action = v["agent_action_name"].as_str().unwrap_or("");
212 let info = &v["tool_info"];
213 let event = match action {
214 "pre_run_command" => "PreToolUse",
215 "post_run_command" => "PostToolUse",
216 "pre_user_prompt" => "UserPromptSubmit",
217 other => other,
218 };
219 out.insert("hook_event_name".into(), json!(event));
220 put(&mut out, "session_id", v["trajectory_id"].as_str());
221 put(&mut out, "cwd", info["cwd"].as_str());
222 if let Some(line) = info["command_line"].as_str() {
223 out.insert("tool_name".into(), json!("Bash"));
224 out.insert("tool_input".into(), json!({ "command": line }));
225 }
226 put(&mut out, "prompt", info["user_prompt"].as_str());
227 }
228 "cline" => {
229 put(&mut out, "session_id", v["taskId"].as_str());
230 put(&mut out, "cwd", v["workspaceRoots"][0].as_str());
231 if let Some(pre) = v.get("preToolUse").filter(|p| p.is_object()) {
232 let tool = pre["toolName"].as_str().or_else(|| pre["tool"].as_str());
233 out.insert("hook_event_name".into(), json!("PreToolUse"));
234 put(&mut out, "tool_name", tool);
235 let args = &pre["parameters"];
236 match command_of(args) {
237 Some(c) => {
238 out.insert("tool_input".into(), json!({ "command": c }));
239 }
240 None => {
241 out.insert("tool_input".into(), args.clone());
242 }
243 }
244 } else if let Some(call) = v.get("tool_call").filter(|p| p.is_object()) {
245 out.insert("hook_event_name".into(), json!("PreToolUse"));
246 put(&mut out, "tool_name", call["name"].as_str());
247 let args = &call["input"];
248 match command_of(args) {
249 Some(c) => {
250 out.insert("tool_input".into(), json!({ "command": c }));
251 }
252 None => {
253 out.insert("tool_input".into(), args.clone());
254 }
255 }
256 } else if let Some(p) = v["userPromptSubmit"]["prompt"].as_str() {
257 out.insert("hook_event_name".into(), json!("UserPromptSubmit"));
258 out.insert("prompt".into(), json!(p));
259 } else {
260 return input.to_string();
261 }
262 }
263 "copilot" if v.get("toolName").is_some() || v.get("sessionId").is_some() => {
264 let event = if v.get("toolName").is_some() {
266 "PreToolUse"
267 } else if v.get("prompt").is_some() {
268 "UserPromptSubmit"
269 } else {
270 "SessionStart"
271 };
272 out.insert("hook_event_name".into(), json!(event));
273 put(&mut out, "session_id", v["sessionId"].as_str());
274 put(&mut out, "cwd", v["cwd"].as_str());
275 put(&mut out, "tool_name", v["toolName"].as_str());
276 put(&mut out, "prompt", v["prompt"].as_str());
277 let args = match &v["toolArgs"] {
278 Value::String(s) => serde_json::from_str(s).unwrap_or(json!({ "command": s })),
279 other => other.clone(),
280 };
281 if !args.is_null() {
282 out.insert("tool_input".into(), args);
283 }
284 }
285 "gemini" => {
286 let mut v = v;
287 if let Some(e) = v["hook_event_name"].as_str() {
288 let seat = gemini_event(e).to_string();
289 v["hook_event_name"] = Value::String(seat);
290 }
291 return v.to_string();
292 }
293 "goose" => {
294 let event = v["event"].as_str().unwrap_or("PreToolUse");
295 out.insert("hook_event_name".into(), json!(event));
296 put(&mut out, "session_id", v["session_id"].as_str());
297 put(&mut out, "cwd", v["working_dir"].as_str());
298 put(&mut out, "tool_name", v["tool_name"].as_str());
299 put(&mut out, "prompt", v["message"].as_str());
300 if !v["tool_input"].is_null() {
301 out.insert("tool_input".into(), v["tool_input"].clone());
302 }
303 }
304 "openhands" => {
305 let event = v["event_type"].as_str().unwrap_or("PreToolUse");
306 out.insert("hook_event_name".into(), json!(event));
307 put(&mut out, "session_id", v["session_id"].as_str());
308 put(&mut out, "cwd", v["working_dir"].as_str());
309 put(&mut out, "prompt", v["message"].as_str());
310 let tool = v["tool_name"]
311 .as_str()
312 .map(|t| if t == "terminal" { "Bash" } else { t });
313 put(&mut out, "tool_name", tool);
314 if !v["tool_input"].is_null() {
315 out.insert("tool_input".into(), v["tool_input"].clone());
316 }
317 }
318 "auggie" => {
319 let mut v = v;
320 if v["tool_name"].as_str() == Some("launch-process") {
321 v["tool_name"] = json!("Bash");
322 }
323 return v.to_string();
324 }
325 "amp" => {
326 let tool = std::env::var("AGENT_TOOL_NAME").unwrap_or_else(|_| "Bash".into());
329 out.insert("hook_event_name".into(), json!("PreToolUse"));
330 out.insert("tool_name".into(), json!(tool));
331 if let Ok(t) = std::env::var("AMP_THREAD_ID") {
332 put(&mut out, "session_id", Some(&t));
333 }
334 put(&mut out, "cwd", v["cwd"].as_str());
335 match v["cmd"]
336 .as_str()
337 .map(str::to_string)
338 .or_else(|| command_of(&v))
339 {
340 Some(c) => {
341 out.insert("tool_input".into(), json!({ "command": c }));
342 }
343 None => {
344 out.insert("tool_input".into(), v.clone());
345 }
346 }
347 }
348 "crush" if v.get("hook_event_name").is_none() => {
349 let mut v = v;
350 let event = v["event"].as_str().unwrap_or("PreToolUse").to_string();
351 v["hook_event_name"] = Value::String(event);
352 return v.to_string();
353 }
354 _ => return input.to_string(),
355 }
356 Value::Object(out).to_string()
357}
358
359#[derive(Debug, Default, PartialEq, Eq)]
361struct Said {
362 decision: Option<String>,
363 reason: String,
364 context: String,
365}
366
367fn read_answer(out: &str) -> Said {
368 let trimmed = out.trim();
369 let Ok(v) = serde_json::from_str::<Value>(trimmed) else {
370 if trimmed.starts_with("deny:") {
372 return Said {
373 decision: Some("deny".into()),
374 reason: trimmed.trim_start_matches("deny:").trim().to_string(),
375 context: String::new(),
376 };
377 }
378 return Said {
379 context: trimmed.to_string(),
380 ..Said::default()
381 };
382 };
383 let specific = &v["hookSpecificOutput"];
384 let decision = specific["permissionDecision"]
385 .as_str()
386 .or_else(|| v["decision"].as_str())
387 .map(|d| if d == "block" { "deny" } else { d })
388 .filter(|d| matches!(*d, "deny" | "ask"))
389 .map(str::to_string);
390 let reason = specific["permissionDecisionReason"]
391 .as_str()
392 .or_else(|| v["reason"].as_str())
393 .unwrap_or("")
394 .to_string();
395 let context = specific["additionalContext"]
396 .as_str()
397 .or_else(|| v["context"].as_str())
398 .unwrap_or("")
399 .to_string();
400 Said {
401 decision,
402 reason,
403 context,
404 }
405}
406
407#[must_use]
411pub fn answer(runner: &str, event: &str, out: &str) -> (String, String, i32) {
412 let mut said = read_answer(out);
413 if said.decision.as_deref() == Some("ask") && !asks(runner) {
414 said.decision = Some("deny".into());
415 said.reason = format!(
416 "ask the person before running this: {}. This runner cannot ask, so retrying \
417 returns this same refusal: stop, tell the person the exact command, and leave \
418 it for them to run.",
419 said.reason
420 );
421 }
422 let line = |v: Value| v.to_string() + "\n";
423 let reason = said.reason.clone();
424 let context = said.context.clone();
425 let mut rendered = match (runner, said.decision.as_deref()) {
426 ("factory" | "qwen", _) => (out.to_string(), String::new(), 0),
427 ("copilot", Some(d)) => (
428 line(json!({
429 "permissionDecision": d,
430 "permissionDecisionReason": reason.clone(),
431 })),
432 String::new(),
433 0,
434 ),
435 ("copilot", None) => (String::new(), String::new(), 0),
436 ("gemini", d) => {
437 let mut v = Map::new();
438 if let Some(d) = d {
439 v.insert("decision".into(), json!(d));
440 v.insert("reason".into(), json!(reason.clone()));
441 }
442 if !context.is_empty() {
443 v.insert(
444 "hookSpecificOutput".into(),
445 json!({ "hookEventName": event, "additionalContext": context }),
446 );
447 }
448 (line(Value::Object(v)), String::new(), 0)
449 }
450 ("windsurf" | "kiro" | "goose", Some(_)) => (String::new(), reason_stderr(&reason), 2),
451 ("goose", None) => (String::new(), String::new(), 0),
452 ("openhands", Some(_)) => (
453 line(json!({ "decision": "deny", "reason": reason.clone() })),
454 reason_stderr(&reason),
455 2,
456 ),
457 ("openhands", None) if !context.is_empty() => (
458 line(json!({ "additionalContext": context })),
459 String::new(),
460 0,
461 ),
462 ("amp", Some("ask")) => (String::new(), reason_stderr(&reason), 1),
463 ("amp", Some(_)) => (String::new(), reason_stderr(&reason), 2),
464 ("amp", None) => (String::new(), String::new(), 0),
465 ("auggie", Some(d)) => (
466 line(json!({ "hookSpecificOutput": {
467 "hookEventName": if event.is_empty() { "PreToolUse" } else { event },
468 "permissionDecision": d,
469 "permissionDecisionReason": reason.clone(),
470 }})),
471 String::new(),
472 0,
473 ),
474 ("auggie", None) if !context.is_empty() => (
475 line(json!({ "hookSpecificOutput": {
476 "hookEventName": if event.is_empty() { "PreToolUse" } else { event },
477 "additionalContext": context,
478 }})),
479 String::new(),
480 0,
481 ),
482 ("kiro", None) if !context.is_empty() => (context + "\n", String::new(), 0),
483 ("windsurf" | "kiro", None) => (String::new(), String::new(), 0),
484 ("cline", Some(_)) => (
485 line(json!({ "cancel": true, "errorMessage": reason.clone() })),
486 String::new(),
487 0,
488 ),
489 ("cline", None) => {
490 let mut v = json!({ "cancel": false });
491 if !context.is_empty() {
492 v["contextModification"] = json!(context);
493 }
494 (line(v), String::new(), 0)
495 }
496 ("crush", Some(d)) => (
497 line(json!({ "decision": d, "reason": reason.clone() })),
498 String::new(),
499 0,
500 ),
501 ("crush", None) if !context.is_empty() => {
502 (line(json!({ "context": context })), String::new(), 0)
503 }
504 _ => (String::new(), String::new(), 0),
505 };
506 if said.decision.as_deref() == Some("deny") && contract(runner).deny_by_exit {
507 rendered.2 = 2;
508 if rendered.1.trim().is_empty() {
509 rendered.1 = reason_stderr(&reason);
510 }
511 }
512 rendered
513}
514
515#[must_use]
517pub fn raw_event(input: &str) -> String {
518 serde_json::from_str::<Value>(input.trim())
519 .ok()
520 .and_then(|v| {
521 [
522 "hook_event_name",
523 "agent_action_name",
524 "hookName",
525 "event",
526 "event_type",
527 ]
528 .iter()
529 .find_map(|k| v[*k].as_str().map(str::to_string))
530 })
531 .unwrap_or_default()
532}
533
534pub const INNER_TIMEOUT: std::time::Duration = crate::GUARD_TIMEOUT;
539
540fn seat_event(event: &str) -> &str {
545 match event {
546 ""
547 | "BeforeTool"
548 | "pre_run_command"
549 | "tool_call"
550 | "pre_tool_use"
551 | "preToolUse"
552 | "beforeShellExecution" => "PreToolUse",
553 "BeforeAgent" | "pre_user_prompt" | "beforeSubmitPrompt" | "pre_llm_call" => {
554 "UserPromptSubmit"
555 }
556 "AfterTool" | "post_run_command" | "post_tool_use" | "postToolUse" => "PostToolUse",
557 other => other,
558 }
559}
560
561fn gate_event(event: &str) -> bool {
562 crate::is_gate_event(seat_event(event))
563}
564
565#[must_use]
571pub fn relay_timeout(event: &str) -> std::time::Duration {
572 if gate_event(event) {
573 crate::guard_timeout()
574 } else {
575 std::time::Duration::from_millis(crate::HOOK_DEADLINE_MS.saturating_add(1_000))
576 }
577}
578
579fn fault_output(event: &str, what: &str) -> String {
584 json!({
585 "hookSpecificOutput": {
586 "hookEventName": if event.is_empty() { "PreToolUse" } else { event },
587 "additionalContext": crate::unhealthy_note(what),
588 }
589 })
590 .to_string()
591}
592
593#[must_use]
597pub fn relay_event_is_gate(event: Option<&str>) -> bool {
598 match event {
599 Some(name) if !name.is_empty() => gate_event(name),
600 _ => true,
601 }
602}
603
604#[must_use]
607pub fn relay_input_is_gate(input: &str, event: Option<&str>) -> bool {
608 let raw = raw_event(input);
609 if raw.is_empty() {
610 relay_event_is_gate(event)
611 } else {
612 gate_event(&raw)
613 }
614}
615
616#[must_use]
622pub fn relay_fault_answer(runner: &str, event: &str, what: &str) -> Option<(String, String, i32)> {
623 if !event.is_empty() && !gate_event(event) {
624 return None;
625 }
626 let what: String = what
627 .chars()
628 .map(|c| if c.is_control() { ' ' } else { c })
629 .take(240)
630 .collect();
631 let text = fault_output(event, &what);
632 Some(answer(runner, event, &text))
633}
634
635fn tool_command(normalized: &str) -> String {
637 serde_json::from_str::<Value>(normalized.trim())
638 .ok()
639 .and_then(|v| command_of(&v["tool_input"]))
640 .unwrap_or_default()
641}
642
643fn seat_tool_event(event: &str) -> &str {
651 match event {
652 "" | "BeforeTool" | "pre_run_command" => "PreToolUse",
653 other => other,
654 }
655}
656
657fn early_answer(normalized: &str, event: &str) -> Option<String> {
658 let line = tool_command(normalized);
659 let parsed = serde_json::from_str::<Value>(normalized.trim()).ok();
660 let cwd = parsed
661 .as_ref()
662 .and_then(|v| v["cwd"].as_str().map(std::path::PathBuf::from));
663 let rule = crate::static_guard_in(&line, cwd.as_deref())?;
664 let named = parsed
665 .as_ref()
666 .and_then(|v| v["hook_event_name"].as_str())
667 .filter(|name| !name.is_empty());
668 let event = seat_tool_event(named.unwrap_or(event));
669 let call = crate::HookCall {
670 event: event.to_string(),
671 cue: line,
672 session: None,
673 shape: crate::HookShape::CamelCase,
674 };
675 Some(crate::hook_output_ruled(&call, "", Some(&rule)))
676}
677
678#[must_use]
688pub fn run_inner(
689 mut cmd: std::process::Command,
690 stdin: &str,
691 event: &str,
692 timeout: std::time::Duration,
693) -> String {
694 use std::io::{Read, Write};
695 let spawned = cmd
696 .stdin(std::process::Stdio::piped())
697 .stdout(std::process::Stdio::piped())
698 .spawn();
699 let mut child = match spawned {
700 Ok(child) => child,
701 Err(e) => return fault_output(event, &format!("did not start ({e})")),
702 };
703 let input = stdin.to_string();
706 if let Some(mut pipe) = child.stdin.take() {
709 std::thread::spawn(move || {
710 let _ = pipe.write_all(input.as_bytes());
711 });
712 }
713 let reader = child.stdout.take().map(|mut pipe| {
714 std::thread::spawn(move || {
715 let mut buf = Vec::new();
716 let _ = pipe.read_to_end(&mut buf);
717 buf
718 })
719 });
720 let deadline = std::time::Instant::now() + timeout;
721 let status = loop {
722 match child.try_wait() {
723 Ok(Some(status)) => break Ok(status),
724 Ok(None) if std::time::Instant::now() >= deadline => {
725 let _ = child.kill();
726 let _ = child.wait();
727 break Err(format!("gave no answer within {} s", timeout.as_secs_f32()));
728 }
729 Ok(None) => std::thread::sleep(std::time::Duration::from_millis(20)),
730 Err(e) => break Err(format!("could not be waited on ({e})")),
731 }
732 };
733 let status = match status {
734 Ok(status) => status,
735 Err(what) => return fault_output(event, &what),
738 };
739 let out = reader
740 .and_then(|r| r.join().ok())
741 .map(|b| String::from_utf8_lossy(&b).into_owned())
742 .unwrap_or_default();
743 let said = read_answer(&out);
744 if said.decision.is_some() || status.success() {
745 return out;
746 }
747 let what = match status.code() {
748 Some(code) => format!("exited with status {code}"),
749 None => "was killed by a signal".to_string(),
750 };
751 fault_output(event, &what)
752}
753
754pub fn relay(runner: &str, input: &str, limit: usize, event: Option<&str>) -> anyhow::Result<i32> {
763 let normalized = normalize_input(runner, input);
764 let raw = raw_event(input);
765 let text = match early_answer(&normalized, &raw) {
766 Some(text) => text,
767 None => match std::env::current_exe() {
768 Ok(exe) => {
769 let mut cmd = std::process::Command::new(exe);
770 cmd.arg("hook").arg("--limit").arg(limit.to_string());
771 cmd.env(crate::rewrite::RELAY_VAR, runner);
772 if let Some(e) = event {
773 cmd.arg("--event").arg(e);
774 }
775 run_inner(cmd, &normalized, &raw, relay_timeout(&raw))
776 }
777 Err(e) => fault_output(&raw, &format!("could not find its own binary ({e})")),
778 },
779 };
780 let (mut out, err, code) = answer(runner, &raw, &text);
781 if let Some(line) = first_prompt_start_line(runner, &raw, input) {
782 out = with_start_line(&out, &line);
783 }
784 print!("{out}");
785 eprint!("{err}");
786 Ok(code)
787}
788
789fn first_prompt_start_line(runner: &str, raw: &str, input: &str) -> Option<String> {
793 if runner != "openhands" || raw != "UserPromptSubmit" {
794 return None;
795 }
796 let v: Value = serde_json::from_str(input.trim()).ok()?;
797 let sid: String = v["session_id"]
798 .as_str()?
799 .chars()
800 .filter(|c| c.is_ascii_alphanumeric() || *c == '-')
801 .collect();
802 if sid.is_empty() {
803 return None;
804 }
805 let state = std::env::var_os("XDG_STATE_HOME")
806 .map(std::path::PathBuf::from)
807 .or_else(|| std::env::var_os("HOME").map(|h| Path::new(&h).join(".local/state")))?;
808 let mark = state.join("ljos/openhands-started").join(&sid);
809 if mark.exists() {
810 return None;
811 }
812 let _ = mark.parent().map(std::fs::create_dir_all);
813 let _ = std::fs::write(&mark, "");
814 Some(crate::session_start_for(Some(&sid)))
815}
816
817fn with_start_line(out: &str, line: &str) -> String {
819 let mut v: Value = serde_json::from_str(out.trim()).unwrap_or_else(|_| json!({}));
820 if v.get("decision").is_some() {
821 return out.to_string();
822 }
823 let rest = v["additionalContext"].as_str().unwrap_or("").to_string();
824 v["additionalContext"] = json!(if rest.is_empty() {
825 line.to_string()
826 } else {
827 format!("{line}\n\n{rest}")
828 });
829 v.to_string() + "\n"
830}
831
832#[must_use]
834pub fn runner_command(base: &str, runner: &str) -> String {
835 format!("{base} --runner {runner}")
836}
837
838fn ours(v: &Value, runner: &str) -> bool {
839 let t = v.to_string();
840 t.contains(&format!("--runner {runner}")) || t.contains(&format!("ljos-guard-{runner}.sh"))
841}
842
843fn ensure_in(obj: &mut Map<String, Value>, key: &str, item: Value, runner: &str) -> bool {
846 let list = obj.entry(key.to_string()).or_insert_with(|| json!([]));
847 let Some(list) = list.as_array_mut() else {
848 return false;
849 };
850 if list.iter().any(|g| ours(g, runner)) {
851 return false;
852 }
853 list.push(item);
854 true
855}
856
857fn group(matcher: Option<&str>, command: &str, timeout: u64, runner: &str) -> Value {
858 let mut hook = json!({ "type": "command", "command": command, "timeout": timeout });
859 if runner == "gemini" {
860 hook["name"] = json!("ljos");
861 }
862 let mut g = json!({ "hooks": [hook] });
863 if let Some(m) = matcher {
864 g["matcher"] = json!(m);
865 }
866 g
867}
868
869fn hooks_of(obj: &mut Map<String, Value>) -> Result<&mut Map<String, Value>, String> {
870 obj.entry("hooks")
871 .or_insert_with(|| json!({}))
872 .as_object_mut()
873 .ok_or_else(|| "hooks is not an object".to_string())
874}
875
876fn spec(runner: &str, root: &mut Value, command: &str) -> Result<bool, String> {
880 let obj = root
881 .as_object_mut()
882 .ok_or_else(|| "not a JSON object".to_string())?;
883 let changed = match runner {
884 "copilot" => {
885 let want = json!({
886 "version": 1,
887 "hooks": { "PreToolUse": [{
888 "type": "command", "matcher": "Bash", "bash": command, "timeoutSec": 20
889 }]}
890 });
891 let same = Value::Object(obj.clone()) == want;
892 *obj = want.as_object().cloned().unwrap_or_default();
893 !same
894 }
895 "kiro" => {
896 let want = json!({
897 "version": "v1",
898 "hooks": [{
899 "name": "ljos guard",
900 "description": "The seat's guard on shell commands; written by ljos onboard.",
901 "trigger": "PreToolUse",
902 "matcher": "shell",
903 "action": { "type": "command", "command": command },
904 "timeout": 20
905 }]
906 });
907 let same = Value::Object(obj.clone()) == want;
908 *obj = want.as_object().cloned().unwrap_or_default();
909 !same
910 }
911 "gemini" => {
912 let hooks = hooks_of(obj)?;
913 let a = ensure_in(
914 hooks,
915 "BeforeTool",
916 group(Some("run_shell_command"), command, 20_000, runner),
917 runner,
918 );
919 let b = ensure_in(
920 hooks,
921 "BeforeAgent",
922 group(None, command, 15_000, runner),
923 runner,
924 );
925 a || b
926 }
927 "qwen" => {
928 let hooks = hooks_of(obj)?;
929 let a = ensure_in(
930 hooks,
931 "PreToolUse",
932 group(Some("^run_shell_command$"), command, 20, runner),
933 runner,
934 );
935 let b = ensure_in(
936 hooks,
937 "UserPromptSubmit",
938 group(None, command, 15, runner),
939 runner,
940 );
941 a || b
942 }
943 "factory" => {
944 let a = ensure_in(
946 obj,
947 "PreToolUse",
948 group(Some("Execute"), command, 20, runner),
949 runner,
950 );
951 let b = ensure_in(
952 obj,
953 "UserPromptSubmit",
954 group(None, command, 15, runner),
955 runner,
956 );
957 a || b
958 }
959 "windsurf" => {
960 let hooks = hooks_of(obj)?;
961 ensure_in(
962 hooks,
963 "pre_run_command",
964 json!({ "command": command, "show_output": false }),
965 runner,
966 )
967 }
968 "openhands" => {
969 let hooks = hooks_of(obj)?;
970 let a = ensure_in(
971 hooks,
972 "PreToolUse",
973 group(Some("terminal"), command, 20, runner),
974 runner,
975 );
976 let b = ensure_in(
977 hooks,
978 "UserPromptSubmit",
979 group(None, command, 15, runner),
980 runner,
981 );
982 a || b
983 }
984 "auggie" => {
985 let hooks = hooks_of(obj)?;
986 ensure_in(
987 hooks,
988 "PreToolUse",
989 group(Some("launch-process"), command, 20_000, runner),
990 runner,
991 )
992 }
993 "goose" => {
994 let want = json!({ "hooks": {
997 "PreToolUse": [{ "matcher": "shell", "hooks": [{
998 "type": "command", "command": command, "timeout": 20, "on_failure": "block"
999 }]}],
1000 "UserPromptSubmit": [{ "hooks": [{
1001 "type": "command", "command": command, "timeout": 15
1002 }]}]
1003 }});
1004 let same = Value::Object(obj.clone()) == want;
1005 *obj = want.as_object().cloned().unwrap_or_default();
1006 !same
1007 }
1008 "amp" => {
1009 let list = obj
1010 .entry("amp.permissions".to_string())
1011 .or_insert_with(|| json!([]));
1012 let Some(list) = list.as_array_mut() else {
1013 return Err("amp.permissions is not a list".into());
1014 };
1015 if list.iter().any(|r| ours(r, runner)) {
1016 false
1017 } else {
1018 list.insert(
1020 0,
1021 json!({ "tool": "Bash", "action": "delegate", "to": command }),
1022 );
1023 true
1024 }
1025 }
1026 "crush" => {
1027 let hooks = hooks_of(obj)?;
1028 ensure_in(
1029 hooks,
1030 "PreToolUse",
1031 json!({ "name": "ljos", "matcher": "^bash$", "command": command, "timeout": 20 }),
1032 runner,
1033 )
1034 }
1035 other => return Err(format!("no hook shape for {other}")),
1036 };
1037 Ok(changed)
1038}
1039
1040#[must_use]
1042pub fn cline_script(command: &str) -> String {
1043 format!("#!/bin/sh\n# Written by ljos onboard: the seat's hook for Cline.\nexec {command}\n")
1044}
1045
1046#[must_use]
1048pub fn hook_step(runner: &str, file: &Path, base_command: &str, dry: bool) -> Step {
1049 let what = "hook".to_string();
1050 let mut command = runner_command(base_command, runner);
1051 if runner == "cline" {
1052 return cline_step(file, &command, dry);
1053 }
1054 let script = needs_script(runner).then(|| script_path(runner, file));
1055 let script_text = format!(
1056 "#!/bin/sh\n# Written by ljos onboard: the seat's guard for {runner}.\nexec {command}\n"
1057 );
1058 let script_stale = script
1059 .as_ref()
1060 .is_some_and(|p| std::fs::read_to_string(p).ok().as_deref() != Some(script_text.as_str()));
1061 if let Some(p) = &script {
1062 command = p.display().to_string();
1063 }
1064 let mut root: Value = match std::fs::read_to_string(file) {
1065 Ok(text) if !text.trim().is_empty() => match serde_json::from_str(&text) {
1066 Ok(v) => v,
1067 Err(e) => {
1068 return Step {
1069 what,
1070 detail: format!("{}: not JSON: {e}", file.display()),
1071 ok: false,
1072 }
1073 }
1074 },
1075 _ => json!({}),
1076 };
1077 let changed = match spec(runner, &mut root, &command) {
1078 Ok(c) => c,
1079 Err(e) => {
1080 return Step {
1081 what,
1082 detail: format!("{}: {e}", file.display()),
1083 ok: false,
1084 }
1085 }
1086 };
1087 let manifest = (runner == "goose")
1088 .then(|| {
1089 file.parent()
1090 .and_then(Path::parent)
1091 .map(|d| d.join("plugin.json"))
1092 })
1093 .flatten();
1094 let manifest_missing = manifest.as_ref().is_some_and(|m| !m.is_file());
1095 if !changed && !script_stale && !manifest_missing {
1096 return Step {
1097 what,
1098 detail: format!("{} carries the seat's {runner} hook", file.display()),
1099 ok: true,
1100 };
1101 }
1102 if dry {
1103 return Step {
1104 what,
1105 detail: format!("would write the seat's {runner} hook to {}", file.display()),
1106 ok: true,
1107 };
1108 }
1109 let written = file
1110 .parent()
1111 .map_or(Ok(()), std::fs::create_dir_all)
1112 .and_then(|()| serde_json::to_string_pretty(&root).map_err(std::io::Error::other))
1113 .and_then(|text| std::fs::write(file, text + "\n"))
1114 .and_then(|()| match &script {
1115 Some(p) => std::fs::write(p, &script_text).and_then(|()| set_executable(p)),
1116 None => Ok(()),
1117 })
1118 .and_then(|()| match &manifest {
1119 Some(m) if manifest_missing => std::fs::write(
1120 m,
1121 "{\n \"name\": \"ljos\",\n \"version\": \"1.0.0\",\n \"description\": \
1122 \"The ljos seat's memory and guard, written by ljos onboard\"\n}\n",
1123 ),
1124 _ => Ok(()),
1125 });
1126 match written {
1127 Ok(()) => Step {
1128 what,
1129 detail: format!("wrote the seat's {runner} hook to {}", file.display()),
1130 ok: true,
1131 },
1132 Err(e) => Step {
1133 what,
1134 detail: format!("{}: {e}", file.display()),
1135 ok: false,
1136 },
1137 }
1138}
1139
1140fn cline_step(dir: &Path, command: &str, dry: bool) -> Step {
1143 let what = "hook".to_string();
1144 let text = cline_script(command);
1145 let mut todo = Vec::new();
1146 for event in ["PreToolUse", "UserPromptSubmit"] {
1147 let path = dir.join(event);
1148 match std::fs::read_to_string(&path) {
1149 Ok(t) if t == text => {}
1150 Ok(t) if !t.contains("ljos onboard") => {
1151 return Step {
1152 what,
1153 detail: format!(
1154 "{} is someone else's hook; add `{command}` to it",
1155 path.display()
1156 ),
1157 ok: false,
1158 }
1159 }
1160 _ => todo.push(path),
1161 }
1162 }
1163 if todo.is_empty() {
1164 return Step {
1165 what,
1166 detail: format!("{} carries the seat's cline hooks", dir.display()),
1167 ok: true,
1168 };
1169 }
1170 if dry {
1171 return Step {
1172 what,
1173 detail: format!("would write the seat's cline hooks to {}", dir.display()),
1174 ok: true,
1175 };
1176 }
1177 for path in &todo {
1178 let written = std::fs::create_dir_all(dir)
1179 .and_then(|()| std::fs::write(path, &text))
1180 .and_then(|()| set_executable(path));
1181 if let Err(e) = written {
1182 return Step {
1183 what,
1184 detail: format!("{}: {e}", path.display()),
1185 ok: false,
1186 };
1187 }
1188 }
1189 Step {
1190 what,
1191 detail: format!("wrote the seat's cline hooks to {}", dir.display()),
1192 ok: true,
1193 }
1194}
1195
1196#[cfg(unix)]
1197fn set_executable(path: &Path) -> std::io::Result<()> {
1198 use std::os::unix::fs::PermissionsExt;
1199 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755))
1200}
1201
1202#[cfg(not(unix))]
1203fn set_executable(_path: &Path) -> std::io::Result<()> {
1204 Ok(())
1205}
1206
1207#[cfg(test)]
1208mod tests {
1209 use super::*;
1210
1211 const DENY: &str = r#"{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"no force push (ljos rule `ljos-policyd`)"}}"#;
1212 const ASK: &str = r#"{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"ask","permissionDecisionReason":"a push"}}"#;
1213 const NOTE: &str = r#"{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"lesson: run the tests"}}"#;
1214
1215 #[test]
1216 fn each_runner_has_one_contract_row() {
1217 for runner in RUNNERS {
1218 assert_eq!(
1219 RUNNER_CONTRACTS
1220 .iter()
1221 .filter(|(name, _)| name == runner)
1222 .count(),
1223 1,
1224 "{runner}"
1225 );
1226 }
1227 }
1228
1229 fn payload(runner: &str, input: Value) -> Value {
1230 serde_json::from_str(&normalize_input(runner, &input.to_string())).unwrap()
1231 }
1232
1233 #[test]
1234 fn each_runner_payload_reads_as_the_command_it_runs() {
1235 let cases = [
1236 (
1237 "windsurf",
1238 json!({"agent_action_name": "pre_run_command", "trajectory_id": "task-0001",
1239 "tool_info": {"command_line": "git push -f", "cwd": "/tmp"}}),
1240 ),
1241 (
1242 "cline",
1243 json!({"hookName": "PreToolUse", "taskId": "task-0001", "workspaceRoots": ["/tmp"],
1244 "preToolUse": {"toolName": "execute_command", "parameters": {"command": "git push -f"}}}),
1245 ),
1246 (
1247 "cline",
1248 json!({"hookName": "tool_call", "taskId": "task-0001", "workspaceRoots": ["/tmp"],
1249 "tool_call": {"id": "c", "name": "run_commands", "input": {"commands": ["git push -f"]}}}),
1250 ),
1251 (
1252 "copilot",
1253 json!({"sessionId": "task-0001", "timestamp": 1, "cwd": "/tmp", "toolName": "bash",
1254 "toolArgs": "{\"command\": \"git push -f\"}"}),
1255 ),
1256 (
1257 "copilot",
1258 json!({"hook_event_name": "PreToolUse", "session_id": "task-0001", "cwd": "/tmp",
1259 "tool_name": "Bash", "tool_input": {"command": "git push -f"}}),
1260 ),
1261 (
1262 "gemini",
1263 json!({"hook_event_name": "BeforeTool", "session_id": "task-0001", "cwd": "/tmp",
1264 "tool_name": "run_shell_command", "tool_input": {"command": "git push -f"}}),
1265 ),
1266 (
1267 "crush",
1268 json!({"event": "PreToolUse", "session_id": "task-0001", "cwd": "/tmp",
1269 "tool_name": "bash", "tool_input": {"command": "git push -f"}}),
1270 ),
1271 (
1272 "kiro",
1273 json!({"hook_event_name": "PreToolUse", "session_id": "task-0001", "cwd": "/tmp",
1274 "tool_name": "shell", "tool_input": {"command": "git push -f"}}),
1275 ),
1276 (
1277 "factory",
1278 json!({"hook_event_name": "PreToolUse", "session_id": "task-0001", "cwd": "/tmp",
1279 "tool_name": "Execute", "tool_input": {"command": "git push -f"}}),
1280 ),
1281 (
1282 "qwen",
1283 json!({"hook_event_name": "PreToolUse", "session_id": "task-0001", "cwd": "/tmp",
1284 "tool_name": "run_shell_command", "tool_input": {"command": "git push -f"}}),
1285 ),
1286 ];
1287 for (runner, input) in cases {
1288 let v = payload(runner, input.clone());
1289 let call = crate::hook_call(&v.to_string());
1290 assert_eq!(call.event, "PreToolUse", "{runner}: {v}");
1291 assert_eq!(call.cue, "git push -f", "{runner}: {v}");
1292 assert_eq!(call.session.as_deref(), Some("task-0001"), "{runner}: {v}");
1293 assert_eq!(
1294 crate::hook_directory(&v.to_string()).unwrap(),
1295 std::fs::canonicalize("/tmp").unwrap(),
1296 "{runner}"
1297 );
1298 }
1299 let prompt = payload(
1300 "gemini",
1301 json!({"hook_event_name": "BeforeAgent", "session_id": "t", "prompt": "fix the build"}),
1302 );
1303 let call = crate::hook_call(&prompt.to_string());
1304 assert_eq!(
1305 (call.event.as_str(), call.cue.as_str()),
1306 ("UserPromptSubmit", "fix the build")
1307 );
1308 let prompt = payload(
1309 "cline",
1310 json!({"hookName": "UserPromptSubmit", "taskId": "t", "userPromptSubmit": {"prompt": "fix it"}}),
1311 );
1312 assert_eq!(
1313 crate::hook_call(&prompt.to_string()).event,
1314 "UserPromptSubmit"
1315 );
1316 }
1317
1318 #[test]
1319 fn a_deny_reaches_each_runner_in_its_own_contract() {
1320 let (out, _, code) = answer("copilot", "PreToolUse", DENY);
1321 let v: Value = serde_json::from_str(&out).unwrap();
1322 assert_eq!((v["permissionDecision"].as_str(), code), (Some("deny"), 0));
1323 assert!(v["permissionDecisionReason"]
1324 .as_str()
1325 .unwrap()
1326 .contains("force push"));
1327
1328 let (out, _, code) = answer("gemini", "BeforeTool", DENY);
1329 let v: Value = serde_json::from_str(&out).unwrap();
1330 assert_eq!((v["decision"].as_str(), code), (Some("deny"), 0));
1331 assert!(v["reason"].as_str().unwrap().contains("force push"));
1332
1333 for runner in ["windsurf", "kiro"] {
1334 let (out, err, code) = answer(runner, "PreToolUse", DENY);
1335 assert_eq!((out.as_str(), code), ("", 2), "{runner}");
1336 assert!(err.contains("force push"), "{runner}");
1337 }
1338
1339 for runner in ["factory", "qwen"] {
1340 let (out, err, code) = answer(runner, "PreToolUse", DENY);
1341 assert_eq!(out.as_str(), DENY, "{runner}");
1342 assert_eq!(code, 2, "{runner}");
1343 assert!(err.contains("force push"), "{runner}: {err}");
1344 }
1345
1346 let (out, _, _) = answer("cline", "PreToolUse", DENY);
1347 let v: Value = serde_json::from_str(&out).unwrap();
1348 assert_eq!(v["cancel"], json!(true));
1349 assert!(v["errorMessage"].as_str().unwrap().contains("force push"));
1350
1351 let (out, err, code) = answer("crush", "PreToolUse", DENY);
1352 let v: Value = serde_json::from_str(&out).unwrap();
1353 assert_eq!(v["decision"], json!("deny"));
1354 assert_eq!(code, 2);
1355 assert!(err.contains("force push"));
1356 }
1357
1358 #[test]
1359 fn an_ask_is_a_deny_where_the_runner_cannot_ask() {
1360 let (out, _, _) = answer("copilot", "PreToolUse", ASK);
1361 assert!(out.contains("\"ask\""));
1362 for runner in ["gemini", "cline", "crush"] {
1363 let (out, _, _) = answer(runner, "PreToolUse", ASK);
1364 assert!(!out.contains("\"ask\""), "{runner}: {out}");
1365 assert!(out.contains("cannot ask"), "{runner}: {out}");
1366 }
1367 let (_, err, code) = answer("windsurf", "PreToolUse", ASK);
1368 assert_eq!(code, 2);
1369 assert!(err.contains("ask the person"));
1370 }
1371
1372 #[test]
1373 fn an_allow_says_nothing_and_a_note_reaches_runners_that_take_one() {
1374 for runner in ["copilot", "windsurf", "kiro", "crush"] {
1375 assert_eq!(
1376 answer(runner, "PreToolUse", ""),
1377 (String::new(), String::new(), 0)
1378 );
1379 }
1380 let (out, _, code) = answer("cline", "PreToolUse", "");
1381 assert_eq!(
1382 serde_json::from_str::<Value>(&out).unwrap(),
1383 json!({"cancel": false})
1384 );
1385 assert_eq!(code, 0);
1386 let (out, _, _) = answer("gemini", "BeforeAgent", NOTE);
1387 let v: Value = serde_json::from_str(&out).unwrap();
1388 assert_eq!(v["hookSpecificOutput"]["hookEventName"], "BeforeAgent");
1389 assert_eq!(
1390 v["hookSpecificOutput"]["additionalContext"],
1391 "lesson: run the tests"
1392 );
1393 let (out, _, _) = answer("cline", "UserPromptSubmit", NOTE);
1394 assert!(out.contains("contextModification"));
1395 }
1396
1397 #[cfg(unix)]
1398 fn sh(script: &str) -> std::process::Command {
1399 let mut cmd = std::process::Command::new("sh");
1400 cmd.arg("-c").arg(script);
1401 cmd
1402 }
1403
1404 #[cfg(unix)]
1405 fn inner(script: &str, timeout_ms: u64) -> String {
1406 run_inner(
1407 sh(script),
1408 r#"{"tool_name":"Bash"}"#,
1409 "PreToolUse",
1410 std::time::Duration::from_millis(timeout_ms),
1411 )
1412 }
1413
1414 fn runner_denied(runner: &str, stdout: &str, _stderr: &str, code: i32) -> bool {
1415 match runner {
1416 "copilot" => code == 0 && stdout.contains(r#""permissionDecision":"deny""#),
1417 "gemini" => code == 0 && stdout.contains(r#""decision":"deny""#),
1418 "windsurf" | "factory" | "kiro" | "qwen" | "crush" | "goose" | "amp" | "openhands" => {
1419 code == 2
1420 }
1421 "cline" => code == 0 && stdout.contains(r#""cancel":true"#),
1422 "auggie" => code == 0 && stdout.contains(r#""permissionDecision":"deny""#),
1423 _ => false,
1424 }
1425 }
1426
1427 #[test]
1428 fn a_relay_fault_allows_and_warns_in_the_runners_contract() {
1429 for runner in RUNNERS {
1430 let (stdout, stderr, code) =
1431 relay_fault_answer(runner, "", "stdin is not utf-8").expect(runner);
1432 let body = format!("{stdout}{stderr}");
1433 assert_eq!(code, 0, "{runner}: code {code} {body}");
1434 assert!(
1435 !runner_denied(runner, &stdout, &stderr, code),
1436 "{runner}: {body}"
1437 );
1438 if shows_context(runner) {
1439 assert!(body.contains("unhealthy"), "{runner}: {body}");
1440 assert!(body.contains("stdin is not utf-8"), "{runner}: {body}");
1441 }
1442 }
1443 for runner in ["gemini", "copilot", "cline", "auggie"] {
1444 let (stdout, stderr, code) =
1445 relay_fault_answer(runner, "BeforeTool", "stdin is not utf-8").expect(runner);
1446 let body = format!("{stdout}{stderr}");
1447 assert_eq!(code, 0, "{runner}: {body}");
1448 assert!(
1449 !runner_denied(runner, &stdout, &stderr, code),
1450 "{runner}: {body}"
1451 );
1452 }
1453 assert!(relay_fault_answer("windsurf", "UserPromptSubmit", "stdin is not utf-8").is_none());
1454 assert!(relay_fault_answer("gemini", "BeforeAgent", "stdin is not utf-8").is_none());
1455 assert!(relay_event_is_gate(None));
1456 assert!(relay_event_is_gate(Some("")));
1457 assert!(!relay_event_is_gate(Some("BeforeAgent")));
1458 assert!(relay_input_is_gate(
1459 r#"{"hook_event_name":"PreToolUse"}"#,
1460 Some("UserPromptSubmit")
1461 ));
1462 assert!(!relay_input_is_gate(
1463 r#"{"hook_event_name":"UserPromptSubmit","prompt":"hi"}"#,
1464 None
1465 ));
1466 }
1467
1468 fn shows_context(runner: &str) -> bool {
1469 matches!(
1470 runner,
1471 "gemini" | "openhands" | "auggie" | "kiro" | "cline" | "crush" | "factory" | "qwen"
1472 )
1473 }
1474
1475 fn allows_fault(out: &str, why: &str) {
1476 let said = read_answer(out);
1477 assert!(said.decision.is_none(), "{out}");
1478 assert!(said.context.contains("unhealthy"), "{out}");
1479 assert!(said.context.contains(why), "{out}");
1480 for runner in RUNNERS {
1481 let (stdout, stderr, code) = answer(runner, "PreToolUse", out);
1482 let body = format!("{stdout}{stderr}");
1483 assert_eq!(code, 0, "{runner}: {body}");
1484 assert!(
1485 !runner_denied(runner, &stdout, &stderr, code),
1486 "{runner}: {body}"
1487 );
1488 if shows_context(runner) {
1489 assert!(body.contains("unhealthy"), "{runner}: {body}");
1490 assert!(body.contains(why), "{runner}: {body}");
1491 }
1492 }
1493 }
1494
1495 #[cfg(unix)]
1496 #[test]
1497 fn an_inner_hook_fault_allows_in_every_runner_shape() {
1498 let _lock = crate::test_env_lock();
1499 unsafe { std::env::remove_var("LJOS_GUARD_FAIL_OPEN") };
1500 let timeout = std::time::Duration::from_secs(5);
1504 let injected = [
1505 format!("gave no answer within {} s", timeout.as_secs_f32()),
1506 "exited with status 3".to_string(),
1507 "was killed by a signal".to_string(),
1508 ];
1509 for why in &injected {
1510 allows_fault(&fault_output("PreToolUse", why), why);
1511 }
1512 allows_fault(&inner("exit 3", 30_000), "exited with status 3");
1513 let missing = run_inner(
1514 std::process::Command::new("/nonexistent/ljos"),
1515 "{}",
1516 "PreToolUse",
1517 std::time::Duration::from_secs(1),
1518 );
1519 allows_fault(&missing, "did not start");
1520 assert_eq!(INNER_TIMEOUT, crate::GUARD_TIMEOUT);
1521 }
1522
1523 #[test]
1528 fn a_prompt_fault_is_not_a_deny() {
1529 let _lock = crate::test_env_lock();
1530 unsafe { std::env::remove_var("LJOS_GUARD_FAIL_OPEN") };
1531 let why = format!(
1532 "gave no answer within {} s",
1533 crate::GUARD_TIMEOUT.as_secs_f32()
1534 );
1535 let prompts = [
1536 ("gemini", "BeforeAgent"),
1537 ("qwen", "UserPromptSubmit"),
1538 ("factory", "UserPromptSubmit"),
1539 ("openhands", "UserPromptSubmit"),
1540 ("goose", "UserPromptSubmit"),
1541 ("cline", "UserPromptSubmit"),
1542 ];
1543 for (runner, event) in prompts {
1544 let fault = fault_output(event, &why);
1545 let said = read_answer(&fault);
1546 assert!(said.decision.is_none(), "{runner}: {fault}");
1547 assert!(
1548 !fault.contains("while checking this command"),
1549 "{runner}: {fault}"
1550 );
1551 assert!(said.context.contains("unhealthy"), "{runner}: {fault}");
1552 let (stdout, stderr, code) = answer(runner, event, &fault);
1553 let body = format!("{stdout}{stderr}");
1554 assert_eq!(code, 0, "{runner}: {body}");
1555 assert!(
1556 !runner_denied(runner, &stdout, &stderr, code),
1557 "{runner}: {body}"
1558 );
1559 assert!(
1560 !body.contains("while checking this command"),
1561 "{runner}: {body}"
1562 );
1563 }
1564 allows_fault(&fault_output("PreToolUse", &why), &why);
1565 allows_fault(&fault_output("BeforeTool", &why), &why);
1566 let deadline = std::time::Duration::from_millis(crate::HOOK_DEADLINE_MS);
1567 assert!(relay_timeout("UserPromptSubmit") >= deadline);
1568 assert!(relay_timeout("BeforeAgent") >= deadline);
1569 assert!(relay_timeout("pre_user_prompt") >= deadline);
1570 assert_eq!(relay_timeout("PreToolUse"), crate::guard_timeout());
1571 assert_eq!(relay_timeout("BeforeTool"), crate::guard_timeout());
1572 assert_eq!(relay_timeout(""), crate::guard_timeout());
1573 }
1574
1575 #[cfg(unix)]
1576 #[test]
1577 fn a_prompt_hook_that_exits_early_is_not_denied() {
1578 let _lock = crate::test_env_lock();
1579 unsafe { std::env::remove_var("LJOS_GUARD_FAIL_OPEN") };
1580 let out = run_inner(
1581 sh("exit 3"),
1582 r#"{"hook_event_name":"UserPromptSubmit","prompt":"hello"}"#,
1583 "UserPromptSubmit",
1584 std::time::Duration::from_secs(2),
1585 );
1586 let said = read_answer(&out);
1587 assert!(said.decision.is_none(), "{out}");
1588 assert!(!out.contains("while checking this command"), "{out}");
1589 assert!(said.context.contains("unhealthy"), "{out}");
1590 }
1591
1592 #[cfg(unix)]
1598 #[test]
1599 fn an_unhealthy_note_is_not_a_second_deny() {
1600 let _lock = crate::test_env_lock();
1601 unsafe { std::env::remove_var("LJOS_GUARD_FAIL_OPEN") };
1602 let why = "did not answer in time";
1603 let exact = json!({
1604 "hookSpecificOutput": {
1605 "hookEventName": "PreToolUse",
1606 "additionalContext": crate::unhealthy_note(why),
1607 }
1608 })
1609 .to_string();
1610 let merged = json!({
1611 "hookSpecificOutput": {
1612 "hookEventName": "PreToolUse",
1613 "additionalContext": format!(
1614 "{}\nthe tip has no passing test record",
1615 crate::unhealthy_note(why)
1616 ),
1617 }
1618 })
1619 .to_string();
1620 for body in [exact, merged] {
1621 let out = inner(&format!("printf '%s' '{body}'"), 30_000);
1622 allows_fault(&out, why);
1623 }
1624 }
1625
1626 #[cfg(unix)]
1627 #[test]
1628 fn an_inner_hook_that_answers_keeps_its_answer() {
1629 let _lock = crate::test_env_lock();
1630 unsafe { std::env::remove_var("LJOS_GUARD_FAIL_OPEN") };
1631 assert_eq!(inner("true", 30_000), "", "a clean allow");
1632 assert_eq!(inner(&format!("printf '%s' '{DENY}'"), 30_000), DENY);
1633 assert_eq!(
1634 inner(&format!("printf '%s' '{DENY}'; exit 1"), 30_000),
1635 DENY,
1636 "a deny printed before a non-zero exit stands"
1637 );
1638 let note = inner(&format!("printf '%s' '{NOTE}'; exit 1"), 30_000);
1639 allows_fault(¬e, "exited with status 1");
1640 }
1641
1642 #[cfg(unix)]
1643 #[test]
1644 fn guard_fail_open_restores_allow_with_note() {
1645 let _lock = crate::test_env_lock();
1646 unsafe { std::env::set_var("LJOS_GUARD_FAIL_OPEN", "1") };
1647 allows_fault(
1648 &fault_output("PreToolUse", "exited with status 3"),
1649 "exited with status 3",
1650 );
1651 allows_fault(&inner("exit 3", 30_000), "exited with status 3");
1652 let unhealthy = json!({
1653 "hookSpecificOutput": {
1654 "hookEventName": "PreToolUse",
1655 "additionalContext": crate::unhealthy_note("did not answer in time"),
1656 }
1657 })
1658 .to_string();
1659 let from_policyd = inner(&format!("printf '%s' '{unhealthy}'"), 30_000);
1660 allows_fault(&from_policyd, "did not answer in time");
1661 }
1662
1663 #[test]
1664 fn a_known_dangerous_command_is_judged_before_the_inner_hook() {
1665 use std::os::unix::fs::PermissionsExt;
1666 let _lock = crate::test_env_lock();
1667 let dir = crate::test_seat_root::seat_root(crate::bookkeep::path_is_temp)
1668 .join(format!("ljos-early-{}", std::process::id()));
1669 let _ = std::fs::remove_dir_all(&dir);
1670 std::fs::create_dir_all(&dir).unwrap();
1671 std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
1672 let data = dir.join("data");
1673 unsafe {
1674 std::env::set_var("HOME", &dir);
1675 std::env::set_var("XDG_DATA_HOME", &data);
1676 std::env::set_var("LJOS_OFF", "0");
1677 std::env::set_var("POLICYD_BIN", dir.join("does-not-run"));
1678 std::env::set_var("PACKSET_WORKSPACE", "early-guard");
1679 }
1680 let force = json!({"tool_input": {"command": "git push --force origin main"}}).to_string();
1681 let started = std::time::Instant::now();
1682 let asked = early_answer(&force, "PreToolUse").expect("a force push asks");
1683 let plain = json!({"tool_input": {"command": "git status"}}).to_string();
1684 assert!(
1685 early_answer(&plain, "").is_none(),
1686 "git status is not dangerous"
1687 );
1688 let rm = json!({"tool_input": {"command": "rm -rf /home/u/proj"}}).to_string();
1689 let denied = early_answer(&rm, "PreToolUse").expect("rm -rf denies");
1690 assert!(
1691 started.elapsed() < std::time::Duration::from_secs(5),
1692 "the static check waited on the guard"
1693 );
1694 assert_eq!(
1695 read_answer(&asked).decision.as_deref(),
1696 Some("ask"),
1697 "{asked}"
1698 );
1699 assert!(asked.contains("git-force-push"), "{asked}");
1700 assert!(!asked.contains("git-push-evidence"), "{asked}");
1701 assert_eq!(
1702 read_answer(&denied).decision.as_deref(),
1703 Some("deny"),
1704 "{denied}"
1705 );
1706 assert!(denied.contains("rm-rf-outside-tmp"), "{denied}");
1707 let before = early_answer(&rm, "BeforeTool").expect("BeforeTool is still a gate");
1711 assert_eq!(
1712 read_answer(&before).decision.as_deref(),
1713 Some("deny"),
1714 "{before}"
1715 );
1716 let (out, _, code) = answer("gemini", "BeforeTool", &before);
1717 assert_eq!(code, 0);
1718 assert!(out.contains("\"deny\""), "{out}");
1719 assert!(!out.contains("\"ask\""), "{out}");
1720 let wind = early_answer(&rm, "pre_run_command").expect("pre_run_command is still a gate");
1721 assert_eq!(
1722 read_answer(&wind).decision.as_deref(),
1723 Some("deny"),
1724 "{wind}"
1725 );
1726 let _ = std::fs::remove_dir_all(&dir);
1727 }
1728
1729 #[test]
1730 fn hook_files_are_written_in_each_runner_shape_and_never_twice() {
1731 let tmp = tempfile::tempdir().unwrap();
1732 let dir = tmp.path().to_path_buf();
1733 let base = "/opt/bin/ljos hook";
1734 for runner in RUNNERS {
1735 let file = if *runner == "cline" {
1736 dir.join("cline-hooks")
1737 } else {
1738 dir.join(format!("{runner}.json"))
1739 };
1740 if *runner == "gemini" {
1741 std::fs::write(&file, r#"{"mcpServers":{"x":{}},"hooks":{"BeforeTool":[{"matcher":"x","hooks":[]}]}}"#).unwrap();
1743 }
1744 let first = hook_step(runner, &file, base, false);
1745 assert!(first.ok, "{runner}: {}", first.detail);
1746 assert!(first.detail.contains("wrote"), "{runner}: {}", first.detail);
1747 let again = hook_step(runner, &file, base, false);
1748 assert!(
1749 again.ok && again.detail.contains("carries"),
1750 "{runner}: {}",
1751 again.detail
1752 );
1753 let command = format!("{base} --runner {runner}");
1754 if *runner == "cline" {
1755 for event in ["PreToolUse", "UserPromptSubmit"] {
1756 let text = std::fs::read_to_string(file.join(event)).unwrap();
1757 assert!(text.contains(&command));
1758 }
1759 continue;
1760 }
1761 let v: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
1762 let found = |p: &str| v.pointer(p).cloned().unwrap_or(Value::Null);
1763 match *runner {
1764 "copilot" => {
1765 assert_eq!(found("/version"), json!(1));
1766 assert_eq!(found("/hooks/PreToolUse/0/bash"), json!(command));
1767 assert_eq!(found("/hooks/PreToolUse/0/matcher"), json!("Bash"));
1768 }
1769 "gemini" => {
1770 assert_eq!(found("/mcpServers/x"), json!({}));
1771 assert_eq!(found("/hooks/BeforeTool/0/matcher"), json!("x"));
1772 assert_eq!(
1773 found("/hooks/BeforeTool/1/matcher"),
1774 json!("run_shell_command")
1775 );
1776 assert_eq!(
1777 found("/hooks/BeforeTool/1/hooks/0/timeout"),
1778 json!(20_000),
1779 "milliseconds"
1780 );
1781 assert_eq!(
1782 found("/hooks/BeforeAgent/0/hooks/0/command"),
1783 json!(command)
1784 );
1785 }
1786 "qwen" => {
1787 assert_eq!(
1788 found("/hooks/PreToolUse/0/matcher"),
1789 json!("^run_shell_command$")
1790 );
1791 assert_eq!(
1792 found("/hooks/PreToolUse/0/hooks/0/timeout"),
1793 json!(20),
1794 "seconds"
1795 );
1796 }
1797 "factory" => {
1798 assert_eq!(found("/PreToolUse/0/matcher"), json!("Execute"));
1799 assert_eq!(found("/PreToolUse/0/hooks/0/command"), json!(command));
1800 }
1801 "windsurf" => {
1802 assert_eq!(found("/hooks/pre_run_command/0/command"), json!(command));
1803 }
1804 "kiro" => {
1805 assert_eq!(found("/version"), json!("v1"));
1806 assert_eq!(found("/hooks/0/trigger"), json!("PreToolUse"));
1807 assert_eq!(found("/hooks/0/action/command"), json!(command));
1808 }
1809 "crush" => {
1810 assert_eq!(found("/hooks/PreToolUse/0/matcher"), json!("^bash$"));
1811 assert_eq!(found("/hooks/PreToolUse/0/command"), json!(command));
1812 }
1813 "goose" => {
1814 assert_eq!(found("/hooks/PreToolUse/0/hooks/0/command"), json!(command));
1815 }
1816 "auggie" => {
1817 assert_eq!(
1818 found("/hooks/PreToolUse/0/matcher"),
1819 json!("launch-process")
1820 );
1821 let script = script_path("auggie", &file).display().to_string();
1822 assert_eq!(found("/hooks/PreToolUse/0/hooks/0/command"), json!(script));
1823 }
1824 "amp" => {
1825 assert_eq!(found("/amp.permissions/0/action"), json!("delegate"));
1826 }
1827 "openhands" => {
1828 assert_eq!(found("/hooks/PreToolUse/0/matcher"), json!("terminal"));
1829 assert_eq!(found("/hooks/PreToolUse/0/hooks/0/command"), json!(command));
1830 }
1831 _ => unreachable!(),
1832 }
1833 }
1834 let foreign = dir.join("foreign-cline");
1835 std::fs::create_dir_all(&foreign).unwrap();
1836 std::fs::write(foreign.join("PreToolUse"), "#!/bin/sh\necho mine\n").unwrap();
1837 let step = hook_step("cline", &foreign, base, false);
1838 assert!(
1839 !step.ok && step.detail.contains("someone else's"),
1840 "{}",
1841 step.detail
1842 );
1843 }
1844
1845 #[test]
1846 fn goose_payload_reaches_the_seat_and_a_deny_exits_2() {
1847 let n = normalize_input(
1848 "goose",
1849 r#"{"event":"PreToolUse","session_id":"g-1","tool_name":"shell","tool_input":{"command":"rm -rf /"},"working_dir":"/r"}"#,
1850 );
1851 let v: Value = serde_json::from_str(&n).unwrap();
1852 assert_eq!(v["hook_event_name"], "PreToolUse");
1853 assert_eq!(v["tool_input"]["command"], "rm -rf /");
1854 assert_eq!(v["cwd"], "/r");
1855 let deny = r#"{"hookSpecificOutput":{"permissionDecision":"deny","permissionDecisionReason":"no"}}"#;
1856 assert_eq!(
1857 answer("goose", "PreToolUse", deny),
1858 (String::new(), "no\n".into(), 2)
1859 );
1860 assert_eq!(answer("goose", "PreToolUse", "{}").2, 0);
1861 }
1862
1863 #[test]
1864 fn amp_reads_cmd_and_rejects_with_2_and_asks_with_1() {
1865 let n = normalize_input("amp", r#"{"cmd":"git push --force"}"#);
1866 let v: Value = serde_json::from_str(&n).unwrap();
1867 assert_eq!(v["tool_input"]["command"], "git push --force");
1868 let deny = r#"{"hookSpecificOutput":{"permissionDecision":"deny","permissionDecisionReason":"no"}}"#;
1869 assert_eq!(answer("amp", "", deny).2, 2);
1870 let ask = r#"{"hookSpecificOutput":{"permissionDecision":"ask","permissionDecisionReason":"sure?"}}"#;
1871 assert_eq!(answer("amp", "", ask).2, 1);
1872 assert_eq!(answer("amp", "", "").2, 0);
1873 }
1874
1875 #[test]
1876 fn auggie_launch_process_is_the_shell_and_its_deny_is_claude_shaped() {
1877 let n = normalize_input(
1878 "auggie",
1879 r#"{"hook_event_name":"PreToolUse","tool_name":"launch-process","tool_input":{"command":"ls"}}"#,
1880 );
1881 let v: Value = serde_json::from_str(&n).unwrap();
1882 assert_eq!(v["tool_name"], "Bash");
1883 let deny = r#"{"hookSpecificOutput":{"permissionDecision":"deny","permissionDecisionReason":"no"}}"#;
1884 let (out, _, code) = answer("auggie", "PreToolUse", deny);
1885 let o: Value = serde_json::from_str(&out).unwrap();
1886 assert_eq!(o["hookSpecificOutput"]["permissionDecision"], "deny");
1887 assert_eq!(code, 0);
1888 }
1889
1890 #[test]
1891 fn auggie_and_amp_hooks_name_a_script_and_are_written_once() {
1892 for (runner, name) in [("auggie", "settings.json"), ("amp", "settings.json")] {
1893 let dir = tempfile::tempdir().unwrap();
1894 let file = dir.path().join(name);
1895 std::fs::write(
1896 &file,
1897 r#"{"keep": 1, "amp.permissions": [{"tool": "Read", "action": "allow"}]}"#,
1898 )
1899 .unwrap();
1900 let step = hook_step(runner, &file, "/bin/ljos hook", false);
1901 assert!(step.ok, "{}", step.detail);
1902 let script = script_path(runner, &file);
1903 let text = std::fs::read_to_string(&script).unwrap();
1904 assert!(text.contains(&format!("/bin/ljos hook --runner {runner}")));
1905 let v: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
1906 assert_eq!(v["keep"], 1);
1907 assert!(v.to_string().contains(&script.display().to_string()));
1908 if runner == "amp" {
1909 assert_eq!(v["amp.permissions"][0]["action"], "delegate");
1910 assert_eq!(v["amp.permissions"][1]["tool"], "Read");
1911 }
1912 let again = hook_step(runner, &file, "/bin/ljos hook", false);
1913 assert!(again.detail.contains("carries"), "{}", again.detail);
1914 }
1915 }
1916
1917 #[test]
1918 fn goose_hook_is_a_plugin_that_fails_closed() {
1919 let dir = tempfile::tempdir().unwrap();
1920 let file = dir.path().join("ljos/hooks/hooks.json");
1921 let step = hook_step("goose", &file, "/bin/ljos hook", false);
1922 assert!(step.ok, "{}", step.detail);
1923 let v: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
1924 assert_eq!(
1925 v["hooks"]["PreToolUse"][0]["hooks"][0]["on_failure"],
1926 "block"
1927 );
1928 assert!(dir.path().join("ljos/plugin.json").is_file());
1929 assert!(hook_step("goose", &file, "/bin/ljos hook", false)
1930 .detail
1931 .contains("carries"));
1932 }
1933
1934 #[test]
1935 fn openhands_terminal_is_the_shell_and_a_deny_exits_2() {
1936 let n = normalize_input(
1937 "openhands",
1938 r#"{"event_type":"PreToolUse","tool_name":"terminal","tool_input":{"command":"rm -rf ~"},"working_dir":"/w"}"#,
1939 );
1940 let v: Value = serde_json::from_str(&n).unwrap();
1941 assert_eq!(v["tool_name"], "Bash");
1942 assert_eq!(v["cwd"], "/w");
1943 let deny = r#"{"hookSpecificOutput":{"permissionDecision":"deny","permissionDecisionReason":"no"}}"#;
1944 let (out, _, code) = answer("openhands", "PreToolUse", deny);
1945 assert!(out.contains("\"decision\":\"deny\""));
1946 assert_eq!(code, 2);
1947 }
1948
1949 #[test]
1950 fn the_start_line_leads_an_openhands_prompt_note() {
1951 let out = with_start_line("{\"additionalContext\":\"lesson\"}\n", "ljos is on: x");
1952 let v: Value = serde_json::from_str(&out).unwrap();
1953 assert_eq!(v["additionalContext"], "ljos is on: x\n\nlesson");
1954 assert_eq!(
1955 with_start_line("", "ljos is on").trim(),
1956 r#"{"additionalContext":"ljos is on"}"#
1957 );
1958 }
1959}