Skip to main content

ljos_cli/
runner_hooks.rs

1//! Hook setups for runners whose hook contract is not Claude Code's own:
2//! GitHub Copilot, Gemini CLI, Windsurf (Devin Desktop), Factory Droid,
3//! Kiro, Cline, Qwen Code, Crush, Auggie, goose and Amp.
4//!
5//! `onboard` writes each runner's hook file with the command
6//! `ljos hook --runner NAME`. That command turns the runner's stdin into
7//! the Claude Code payload the seat reads, runs the ordinary hook, and
8//! writes the answer back in the runner's own contract: its field names,
9//! and for some runners an exit code. A runner that cannot ask the person
10//! gets a deny in place of an ask, with the reason saying so.
11
12use serde_json::{json, Map, Value};
13use std::path::Path;
14
15use crate::Step;
16
17/// The runners this module serves, by the name `--runner` takes.
18pub 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
136/// Runners whose hook entry must name one program with no arguments (Amp's
137/// delegate) or a `.sh` file (Auggie): onboard writes this script beside
138/// the settings file, and the entry names it.
139fn needs_script(runner: &str) -> bool {
140    matches!(runner, "auggie" | "amp")
141}
142
143/// The wrapper script's path for a runner whose hooks live in `file`.
144#[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/// Whether `name` is a runner this module writes hooks for.
152#[must_use]
153pub fn is_runner(name: &str) -> bool {
154    RUNNERS.contains(&name)
155}
156
157/// Whether the runner shows the person a prompt on an `ask`.
158fn 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
170/// The event names Gemini CLI uses, as the seat's.
171fn gemini_event(raw: &str) -> &str {
172    match raw {
173        "BeforeTool" => "PreToolUse",
174        "AfterTool" => "PostToolUse",
175        "BeforeAgent" => "UserPromptSubmit",
176        other => other,
177    }
178}
179
180/// A command line out of a tool's arguments: `command`, or a list of
181/// `commands`, one to a line.
182fn 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/// The runner's stdin as the Claude Code payload `ljos hook` reads:
195/// `hook_event_name`, `session_id`, `cwd`, and `tool_name` with
196/// `tool_input`, or `prompt`. A payload that is not JSON, or a runner
197/// that already sends this shape, is returned as it came.
198#[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            // The camelCase contract: `toolArgs` may arrive as JSON text.
265            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            // Amp pipes the tool's arguments alone and names the tool in
327            // the environment; Bash takes `cmd`.
328            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/// What the seat's answer says, whatever shape it came in.
360#[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        // A plain-text answer is an argv line; a deny says so first.
371        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/// The seat's answer (the Claude Code JSON `ljos hook` prints) in the
408/// runner's contract: what to print, what to write to stderr, and the
409/// exit code. `event` is the event name the runner sent.
410#[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/// The event name in a runner's stdin, as the runner spelled it.
516#[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
534/// The default wait for the inner `ljos hook` on a tool call.
535/// [`relay_timeout`] is what [`relay`] uses. Each runner's own timeout is
536/// 15 or 20 seconds, and several of them let the call run when it lapses,
537/// so the relay answers first on a gate.
538pub const INNER_TIMEOUT: std::time::Duration = crate::GUARD_TIMEOUT;
539
540/// A runner's event name as the seat spells it, so [`crate::is_gate_event`]
541/// can tell a tool call from a prompt. Gemini's `BeforeTool` and
542/// Windsurf's `pre_run_command` are the gate. An empty name is a tool
543/// call: Amp sends the arguments alone.
544fn 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/// How long [`relay`] waits. A tool call uses [`crate::guard_timeout`].
566/// A prompt waits out the inner hook's own deadline
567/// ([`crate::HOOK_DEADLINE_MS`]): that hook exits on its own with whatever
568/// it has, and a shorter wait kills the answer. Rendering that kill as a
569/// deny blocks the person's prompt.
570#[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
579/// The answer for an inner hook fault. `what` says how it failed. A
580/// fault allows with a note on every event: a prompt that the guard could
581/// not finish is not a command, and a command the guard could not judge
582/// runs with the warning, since the deny-on-fault switch is gone.
583fn fault_output(event: &str, what: &str) -> String {
584    if !gate_event(event) || crate::guard_fail_open() {
585        return json!({
586            "hookSpecificOutput": {
587                "hookEventName": if event.is_empty() { "PreToolUse" } else { event },
588                "additionalContext": crate::unhealthy_note(what),
589            }
590        })
591        .to_string();
592    }
593    let reason = crate::guard_fault_reason(what);
594    json!({
595        "hookSpecificOutput": {
596            "hookEventName": if event.is_empty() { "PreToolUse" } else { event },
597            "permissionDecision": "deny",
598            "permissionDecisionReason": reason,
599        }
600    })
601    .to_string()
602}
603
604/// Whether `event` is a tool call the relay must fail closed. An unnamed
605/// event is a tool call: Amp sends the arguments alone, and stdin that is
606/// not text has no event to read.
607#[must_use]
608pub fn relay_event_is_gate(event: Option<&str>) -> bool {
609    match event {
610        Some(name) if !name.is_empty() => gate_event(name),
611        _ => true,
612    }
613}
614
615/// Whether this payload is a tool call. The event in the payload wins;
616/// otherwise the `--event` flag, and an unnamed one is a gate.
617#[must_use]
618pub fn relay_input_is_gate(input: &str, event: Option<&str>) -> bool {
619    let raw = raw_event(input);
620    if raw.is_empty() {
621        relay_event_is_gate(event)
622    } else {
623        gate_event(&raw)
624    }
625}
626
627/// A deny for a relay that failed before it could judge, in the runner's
628/// own contract. `None` when `event` is a prompt: that error still exits
629/// 1, and denying it would block the person. Exit 2 with no JSON allows
630/// the command on Gemini, Copilot, Cline and Auggie, so those runners
631/// get their deny object and the exit their contract uses.
632#[must_use]
633pub fn relay_fault_deny(runner: &str, event: &str, what: &str) -> Option<(String, String, i32)> {
634    if !event.is_empty() && !gate_event(event) {
635        return None;
636    }
637    let what: String = what
638        .chars()
639        .map(|c| if c.is_control() { ' ' } else { c })
640        .take(240)
641        .collect();
642    let text = fault_output(event, &what);
643    Some(answer(runner, event, &text))
644}
645
646/// The command a normalized payload would run, or empty when it has none.
647fn tool_command(normalized: &str) -> String {
648    serde_json::from_str::<Value>(normalized.trim())
649        .ok()
650        .and_then(|v| command_of(&v["tool_input"]))
651        .unwrap_or_default()
652}
653
654/// The fast in-process verdict, in the shape the inner hook prints, when
655/// the command is one the static check refuses. `None` means the slow
656/// hook still has to run.
657/// A runner's pre-tool event, as the seat names it. Gemini's `BeforeTool`
658/// and Windsurf's `pre_run_command` are that gate. Rendering the verdict
659/// under the raw name prints no decision, and Gemini reads a JSON object
660/// with no `decision` as an allow.
661fn seat_tool_event(event: &str) -> &str {
662    match event {
663        "" | "BeforeTool" | "pre_run_command" => "PreToolUse",
664        other => other,
665    }
666}
667
668fn early_answer(normalized: &str, event: &str) -> Option<String> {
669    let line = tool_command(normalized);
670    let parsed = serde_json::from_str::<Value>(normalized.trim()).ok();
671    let cwd = parsed
672        .as_ref()
673        .and_then(|v| v["cwd"].as_str().map(std::path::PathBuf::from));
674    let rule = crate::static_guard_in(&line, cwd.as_deref())?;
675    let named = parsed
676        .as_ref()
677        .and_then(|v| v["hook_event_name"].as_str())
678        .filter(|name| !name.is_empty());
679    let event = seat_tool_event(named.unwrap_or(event));
680    let call = crate::HookCall {
681        event: event.to_string(),
682        cue: line,
683        session: None,
684        shape: crate::HookShape::CamelCase,
685    };
686    Some(crate::hook_output_ruled(&call, "", Some(&rule)))
687}
688
689/// Run `cmd` as the inner hook with `stdin` as its input, and give back
690/// what it printed. On a tool call, a spawn error, a kill by signal, a
691/// non-zero exit, or no exit within `timeout` is a deny that says how the
692/// guard failed. A prompt keeps the old allow with a note: the person's
693/// turn is not a command. A non-zero exit that still printed a deny or an
694/// ask keeps it. A successful exit is that answer, including an allow
695/// that carries the unhealthy-guard sentence: the check already denied
696/// a real fault, and matching the sentence again missed it once a push
697/// warning was joined on.
698#[must_use]
699pub fn run_inner(
700    mut cmd: std::process::Command,
701    stdin: &str,
702    event: &str,
703    timeout: std::time::Duration,
704) -> String {
705    use std::io::{Read, Write};
706    let spawned = cmd
707        .stdin(std::process::Stdio::piped())
708        .stdout(std::process::Stdio::piped())
709        .spawn();
710    let mut child = match spawned {
711        Ok(child) => child,
712        Err(e) => return fault_output(event, &format!("did not start ({e})")),
713    };
714    // Feed and drain on their own threads, so a hook that reads nothing or
715    // prints a lot cannot stall the clock below.
716    let input = stdin.to_string();
717    // The writer is never joined: a child that left a grandchild holding
718    // its stdin could block it, and the process exits soon after.
719    if let Some(mut pipe) = child.stdin.take() {
720        std::thread::spawn(move || {
721            let _ = pipe.write_all(input.as_bytes());
722        });
723    }
724    let reader = child.stdout.take().map(|mut pipe| {
725        std::thread::spawn(move || {
726            let mut buf = Vec::new();
727            let _ = pipe.read_to_end(&mut buf);
728            buf
729        })
730    });
731    let deadline = std::time::Instant::now() + timeout;
732    let status = loop {
733        match child.try_wait() {
734            Ok(Some(status)) => break Ok(status),
735            Ok(None) if std::time::Instant::now() >= deadline => {
736                let _ = child.kill();
737                let _ = child.wait();
738                break Err(format!("gave no answer within {} s", timeout.as_secs_f32()));
739            }
740            Ok(None) => std::thread::sleep(std::time::Duration::from_millis(20)),
741            Err(e) => break Err(format!("could not be waited on ({e})")),
742        }
743    };
744    let status = match status {
745        Ok(status) => status,
746        // A killed hook's children may still hold the pipe; do not wait
747        // for the reader.
748        Err(what) => return fault_output(event, &what),
749    };
750    let out = reader
751        .and_then(|r| r.join().ok())
752        .map(|b| String::from_utf8_lossy(&b).into_owned())
753        .unwrap_or_default();
754    let said = read_answer(&out);
755    if said.decision.is_some() || status.success() {
756        return out;
757    }
758    let what = match status.code() {
759        Some(code) => format!("exited with status {code}"),
760        None => "was killed by a signal".to_string(),
761    };
762    fault_output(event, &what)
763}
764
765/// Run the seat's hook for a runner: `ljos hook` on the normalized
766/// payload, its answer put in the runner's contract. Returns the exit
767/// code the runner reads. A force push, a seat deny, and an `rm -rf` are
768/// judged here, before the inner hook. An inner hook that crashes, exits
769/// non-zero without a decision, or runs past [`crate::guard_timeout`]
770/// denies the call and says the guard failed. A prompt is not denied: the
771/// wait is the prompt hook's own deadline, and a fault stays an allow
772/// with a note.
773pub fn relay(runner: &str, input: &str, limit: usize, event: Option<&str>) -> anyhow::Result<i32> {
774    let normalized = normalize_input(runner, input);
775    let raw = raw_event(input);
776    let text = match early_answer(&normalized, &raw) {
777        Some(text) => text,
778        None => match std::env::current_exe() {
779            Ok(exe) => {
780                let mut cmd = std::process::Command::new(exe);
781                cmd.arg("hook").arg("--limit").arg(limit.to_string());
782                cmd.env(crate::rewrite::RELAY_VAR, runner);
783                if let Some(e) = event {
784                    cmd.arg("--event").arg(e);
785                }
786                run_inner(cmd, &normalized, &raw, relay_timeout(&raw))
787            }
788            Err(e) => fault_output(&raw, &format!("could not find its own binary ({e})")),
789        },
790    };
791    let (mut out, err, code) = answer(runner, &raw, &text);
792    if let Some(line) = first_prompt_start_line(runner, &raw, input) {
793        out = with_start_line(&out, &line);
794    }
795    print!("{out}");
796    eprint!("{err}");
797    Ok(code)
798}
799
800/// OpenHands drops a `SessionStart` hook's output, so the session-start
801/// line rides on the session's first prompt: once per session id, marked
802/// under the state directory.
803fn first_prompt_start_line(runner: &str, raw: &str, input: &str) -> Option<String> {
804    if runner != "openhands" || raw != "UserPromptSubmit" {
805        return None;
806    }
807    let v: Value = serde_json::from_str(input.trim()).ok()?;
808    let sid: String = v["session_id"]
809        .as_str()?
810        .chars()
811        .filter(|c| c.is_ascii_alphanumeric() || *c == '-')
812        .collect();
813    if sid.is_empty() {
814        return None;
815    }
816    let state = std::env::var_os("XDG_STATE_HOME")
817        .map(std::path::PathBuf::from)
818        .or_else(|| std::env::var_os("HOME").map(|h| Path::new(&h).join(".local/state")))?;
819    let mark = state.join("ljos/openhands-started").join(&sid);
820    if mark.exists() {
821        return None;
822    }
823    let _ = mark.parent().map(std::fs::create_dir_all);
824    let _ = std::fs::write(&mark, "");
825    Some(crate::session_start_for(Some(&sid)))
826}
827
828/// An OpenHands answer with `line` put ahead of its context.
829fn with_start_line(out: &str, line: &str) -> String {
830    let mut v: Value = serde_json::from_str(out.trim()).unwrap_or_else(|_| json!({}));
831    if v.get("decision").is_some() {
832        return out.to_string();
833    }
834    let rest = v["additionalContext"].as_str().unwrap_or("").to_string();
835    v["additionalContext"] = json!(if rest.is_empty() {
836        line.to_string()
837    } else {
838        format!("{line}\n\n{rest}")
839    });
840    v.to_string() + "\n"
841}
842
843/// The hook command a runner's file names.
844#[must_use]
845pub fn runner_command(base: &str, runner: &str) -> String {
846    format!("{base} --runner {runner}")
847}
848
849fn ours(v: &Value, runner: &str) -> bool {
850    let t = v.to_string();
851    t.contains(&format!("--runner {runner}")) || t.contains(&format!("ljos-guard-{runner}.sh"))
852}
853
854/// Push `item` onto the array at `key` of `obj` unless one already names
855/// the seat's command. True when it was added.
856fn ensure_in(obj: &mut Map<String, Value>, key: &str, item: Value, runner: &str) -> bool {
857    let list = obj.entry(key.to_string()).or_insert_with(|| json!([]));
858    let Some(list) = list.as_array_mut() else {
859        return false;
860    };
861    if list.iter().any(|g| ours(g, runner)) {
862        return false;
863    }
864    list.push(item);
865    true
866}
867
868fn group(matcher: Option<&str>, command: &str, timeout: u64, runner: &str) -> Value {
869    let mut hook = json!({ "type": "command", "command": command, "timeout": timeout });
870    if runner == "gemini" {
871        hook["name"] = json!("ljos");
872    }
873    let mut g = json!({ "hooks": [hook] });
874    if let Some(m) = matcher {
875        g["matcher"] = json!(m);
876    }
877    g
878}
879
880fn hooks_of(obj: &mut Map<String, Value>) -> Result<&mut Map<String, Value>, String> {
881    obj.entry("hooks")
882        .or_insert_with(|| json!({}))
883        .as_object_mut()
884        .ok_or_else(|| "hooks is not an object".to_string())
885}
886
887/// Merge or write the runner's hook file so it runs `command`. A file
888/// the seat owns whole (Copilot's and Kiro's) is rewritten; a shared
889/// settings file keeps every entry that is not the seat's.
890fn spec(runner: &str, root: &mut Value, command: &str) -> Result<bool, String> {
891    let obj = root
892        .as_object_mut()
893        .ok_or_else(|| "not a JSON object".to_string())?;
894    let changed = match runner {
895        "copilot" => {
896            let want = json!({
897                "version": 1,
898                "hooks": { "PreToolUse": [{
899                    "type": "command", "matcher": "Bash", "bash": command, "timeoutSec": 20
900                }]}
901            });
902            let same = Value::Object(obj.clone()) == want;
903            *obj = want.as_object().cloned().unwrap_or_default();
904            !same
905        }
906        "kiro" => {
907            let want = json!({
908                "version": "v1",
909                "hooks": [{
910                    "name": "ljos guard",
911                    "description": "The seat's guard on shell commands; written by ljos onboard.",
912                    "trigger": "PreToolUse",
913                    "matcher": "shell",
914                    "action": { "type": "command", "command": command },
915                    "timeout": 20
916                }]
917            });
918            let same = Value::Object(obj.clone()) == want;
919            *obj = want.as_object().cloned().unwrap_or_default();
920            !same
921        }
922        "gemini" => {
923            let hooks = hooks_of(obj)?;
924            let a = ensure_in(
925                hooks,
926                "BeforeTool",
927                group(Some("run_shell_command"), command, 20_000, runner),
928                runner,
929            );
930            let b = ensure_in(
931                hooks,
932                "BeforeAgent",
933                group(None, command, 15_000, runner),
934                runner,
935            );
936            a || b
937        }
938        "qwen" => {
939            let hooks = hooks_of(obj)?;
940            let a = ensure_in(
941                hooks,
942                "PreToolUse",
943                group(Some("^run_shell_command$"), command, 20, runner),
944                runner,
945            );
946            let b = ensure_in(
947                hooks,
948                "UserPromptSubmit",
949                group(None, command, 15, runner),
950                runner,
951            );
952            a || b
953        }
954        "factory" => {
955            // hooks.json is keyed by event at the top level.
956            let a = ensure_in(
957                obj,
958                "PreToolUse",
959                group(Some("Execute"), command, 20, runner),
960                runner,
961            );
962            let b = ensure_in(
963                obj,
964                "UserPromptSubmit",
965                group(None, command, 15, runner),
966                runner,
967            );
968            a || b
969        }
970        "windsurf" => {
971            let hooks = hooks_of(obj)?;
972            ensure_in(
973                hooks,
974                "pre_run_command",
975                json!({ "command": command, "show_output": false }),
976                runner,
977            )
978        }
979        "openhands" => {
980            let hooks = hooks_of(obj)?;
981            let a = ensure_in(
982                hooks,
983                "PreToolUse",
984                group(Some("terminal"), command, 20, runner),
985                runner,
986            );
987            let b = ensure_in(
988                hooks,
989                "UserPromptSubmit",
990                group(None, command, 15, runner),
991                runner,
992            );
993            a || b
994        }
995        "auggie" => {
996            let hooks = hooks_of(obj)?;
997            ensure_in(
998                hooks,
999                "PreToolUse",
1000                group(Some("launch-process"), command, 20_000, runner),
1001                runner,
1002            )
1003        }
1004        "goose" => {
1005            // The plugin's hooks file is the seat's whole; a hook that
1006            // cannot run blocks the call.
1007            let want = json!({ "hooks": {
1008                "PreToolUse": [{ "matcher": "shell", "hooks": [{
1009                    "type": "command", "command": command, "timeout": 20, "on_failure": "block"
1010                }]}],
1011                "UserPromptSubmit": [{ "hooks": [{
1012                    "type": "command", "command": command, "timeout": 15
1013                }]}]
1014            }});
1015            let same = Value::Object(obj.clone()) == want;
1016            *obj = want.as_object().cloned().unwrap_or_default();
1017            !same
1018        }
1019        "amp" => {
1020            let list = obj
1021                .entry("amp.permissions".to_string())
1022                .or_insert_with(|| json!([]));
1023            let Some(list) = list.as_array_mut() else {
1024                return Err("amp.permissions is not a list".into());
1025            };
1026            if list.iter().any(|r| ours(r, runner)) {
1027                false
1028            } else {
1029                // First, since Amp applies the first rule that matches.
1030                list.insert(
1031                    0,
1032                    json!({ "tool": "Bash", "action": "delegate", "to": command }),
1033                );
1034                true
1035            }
1036        }
1037        "crush" => {
1038            let hooks = hooks_of(obj)?;
1039            ensure_in(
1040                hooks,
1041                "PreToolUse",
1042                json!({ "name": "ljos", "matcher": "^bash$", "command": command, "timeout": 20 }),
1043                runner,
1044            )
1045        }
1046        other => return Err(format!("no hook shape for {other}")),
1047    };
1048    Ok(changed)
1049}
1050
1051/// The text of a Cline hook script that runs the seat's hook.
1052#[must_use]
1053pub fn cline_script(command: &str) -> String {
1054    format!("#!/bin/sh\n# Written by ljos onboard: the seat's hook for Cline.\nexec {command}\n")
1055}
1056
1057/// Write the runner's hooks at `file` (for Cline, the hooks directory).
1058#[must_use]
1059pub fn hook_step(runner: &str, file: &Path, base_command: &str, dry: bool) -> Step {
1060    let what = "hook".to_string();
1061    let mut command = runner_command(base_command, runner);
1062    if runner == "cline" {
1063        return cline_step(file, &command, dry);
1064    }
1065    let script = needs_script(runner).then(|| script_path(runner, file));
1066    let script_text = format!(
1067        "#!/bin/sh\n# Written by ljos onboard: the seat's guard for {runner}.\nexec {command}\n"
1068    );
1069    let script_stale = script
1070        .as_ref()
1071        .is_some_and(|p| std::fs::read_to_string(p).ok().as_deref() != Some(script_text.as_str()));
1072    if let Some(p) = &script {
1073        command = p.display().to_string();
1074    }
1075    let mut root: Value = match std::fs::read_to_string(file) {
1076        Ok(text) if !text.trim().is_empty() => match serde_json::from_str(&text) {
1077            Ok(v) => v,
1078            Err(e) => {
1079                return Step {
1080                    what,
1081                    detail: format!("{}: not JSON: {e}", file.display()),
1082                    ok: false,
1083                }
1084            }
1085        },
1086        _ => json!({}),
1087    };
1088    let changed = match spec(runner, &mut root, &command) {
1089        Ok(c) => c,
1090        Err(e) => {
1091            return Step {
1092                what,
1093                detail: format!("{}: {e}", file.display()),
1094                ok: false,
1095            }
1096        }
1097    };
1098    let manifest = (runner == "goose")
1099        .then(|| {
1100            file.parent()
1101                .and_then(Path::parent)
1102                .map(|d| d.join("plugin.json"))
1103        })
1104        .flatten();
1105    let manifest_missing = manifest.as_ref().is_some_and(|m| !m.is_file());
1106    if !changed && !script_stale && !manifest_missing {
1107        return Step {
1108            what,
1109            detail: format!("{} carries the seat's {runner} hook", file.display()),
1110            ok: true,
1111        };
1112    }
1113    if dry {
1114        return Step {
1115            what,
1116            detail: format!("would write the seat's {runner} hook to {}", file.display()),
1117            ok: true,
1118        };
1119    }
1120    let written = file
1121        .parent()
1122        .map_or(Ok(()), std::fs::create_dir_all)
1123        .and_then(|()| serde_json::to_string_pretty(&root).map_err(std::io::Error::other))
1124        .and_then(|text| std::fs::write(file, text + "\n"))
1125        .and_then(|()| match &script {
1126            Some(p) => std::fs::write(p, &script_text).and_then(|()| set_executable(p)),
1127            None => Ok(()),
1128        })
1129        .and_then(|()| match &manifest {
1130            Some(m) if manifest_missing => std::fs::write(
1131                m,
1132                "{\n  \"name\": \"ljos\",\n  \"version\": \"1.0.0\",\n  \"description\": \
1133                 \"The ljos seat's memory and guard, written by ljos onboard\"\n}\n",
1134            ),
1135            _ => Ok(()),
1136        });
1137    match written {
1138        Ok(()) => Step {
1139            what,
1140            detail: format!("wrote the seat's {runner} hook to {}", file.display()),
1141            ok: true,
1142        },
1143        Err(e) => Step {
1144            what,
1145            detail: format!("{}: {e}", file.display()),
1146            ok: false,
1147        },
1148    }
1149}
1150
1151/// Cline runs an executable named after the event from its hooks
1152/// directory. A script there that is not the seat's is left alone.
1153fn cline_step(dir: &Path, command: &str, dry: bool) -> Step {
1154    let what = "hook".to_string();
1155    let text = cline_script(command);
1156    let mut todo = Vec::new();
1157    for event in ["PreToolUse", "UserPromptSubmit"] {
1158        let path = dir.join(event);
1159        match std::fs::read_to_string(&path) {
1160            Ok(t) if t == text => {}
1161            Ok(t) if !t.contains("ljos onboard") => {
1162                return Step {
1163                    what,
1164                    detail: format!(
1165                        "{} is someone else's hook; add `{command}` to it",
1166                        path.display()
1167                    ),
1168                    ok: false,
1169                }
1170            }
1171            _ => todo.push(path),
1172        }
1173    }
1174    if todo.is_empty() {
1175        return Step {
1176            what,
1177            detail: format!("{} carries the seat's cline hooks", dir.display()),
1178            ok: true,
1179        };
1180    }
1181    if dry {
1182        return Step {
1183            what,
1184            detail: format!("would write the seat's cline hooks to {}", dir.display()),
1185            ok: true,
1186        };
1187    }
1188    for path in &todo {
1189        let written = std::fs::create_dir_all(dir)
1190            .and_then(|()| std::fs::write(path, &text))
1191            .and_then(|()| set_executable(path));
1192        if let Err(e) = written {
1193            return Step {
1194                what,
1195                detail: format!("{}: {e}", path.display()),
1196                ok: false,
1197            };
1198        }
1199    }
1200    Step {
1201        what,
1202        detail: format!("wrote the seat's cline hooks to {}", dir.display()),
1203        ok: true,
1204    }
1205}
1206
1207#[cfg(unix)]
1208fn set_executable(path: &Path) -> std::io::Result<()> {
1209    use std::os::unix::fs::PermissionsExt;
1210    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755))
1211}
1212
1213#[cfg(not(unix))]
1214fn set_executable(_path: &Path) -> std::io::Result<()> {
1215    Ok(())
1216}
1217
1218#[cfg(test)]
1219mod tests {
1220    use super::*;
1221
1222    const DENY: &str = r#"{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"no force push (ljos rule `ljos-policyd`)"}}"#;
1223    const ASK: &str = r#"{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"ask","permissionDecisionReason":"a push"}}"#;
1224    const NOTE: &str = r#"{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"lesson: run the tests"}}"#;
1225
1226    #[test]
1227    fn each_runner_has_one_contract_row() {
1228        for runner in RUNNERS {
1229            assert_eq!(
1230                RUNNER_CONTRACTS
1231                    .iter()
1232                    .filter(|(name, _)| name == runner)
1233                    .count(),
1234                1,
1235                "{runner}"
1236            );
1237        }
1238    }
1239
1240    fn payload(runner: &str, input: Value) -> Value {
1241        serde_json::from_str(&normalize_input(runner, &input.to_string())).unwrap()
1242    }
1243
1244    #[test]
1245    fn each_runner_payload_reads_as_the_command_it_runs() {
1246        let cases = [
1247            (
1248                "windsurf",
1249                json!({"agent_action_name": "pre_run_command", "trajectory_id": "task-0001",
1250                       "tool_info": {"command_line": "git push -f", "cwd": "/tmp"}}),
1251            ),
1252            (
1253                "cline",
1254                json!({"hookName": "PreToolUse", "taskId": "task-0001", "workspaceRoots": ["/tmp"],
1255                       "preToolUse": {"toolName": "execute_command", "parameters": {"command": "git push -f"}}}),
1256            ),
1257            (
1258                "cline",
1259                json!({"hookName": "tool_call", "taskId": "task-0001", "workspaceRoots": ["/tmp"],
1260                       "tool_call": {"id": "c", "name": "run_commands", "input": {"commands": ["git push -f"]}}}),
1261            ),
1262            (
1263                "copilot",
1264                json!({"sessionId": "task-0001", "timestamp": 1, "cwd": "/tmp", "toolName": "bash",
1265                       "toolArgs": "{\"command\": \"git push -f\"}"}),
1266            ),
1267            (
1268                "copilot",
1269                json!({"hook_event_name": "PreToolUse", "session_id": "task-0001", "cwd": "/tmp",
1270                       "tool_name": "Bash", "tool_input": {"command": "git push -f"}}),
1271            ),
1272            (
1273                "gemini",
1274                json!({"hook_event_name": "BeforeTool", "session_id": "task-0001", "cwd": "/tmp",
1275                       "tool_name": "run_shell_command", "tool_input": {"command": "git push -f"}}),
1276            ),
1277            (
1278                "crush",
1279                json!({"event": "PreToolUse", "session_id": "task-0001", "cwd": "/tmp",
1280                       "tool_name": "bash", "tool_input": {"command": "git push -f"}}),
1281            ),
1282            (
1283                "kiro",
1284                json!({"hook_event_name": "PreToolUse", "session_id": "task-0001", "cwd": "/tmp",
1285                       "tool_name": "shell", "tool_input": {"command": "git push -f"}}),
1286            ),
1287            (
1288                "factory",
1289                json!({"hook_event_name": "PreToolUse", "session_id": "task-0001", "cwd": "/tmp",
1290                       "tool_name": "Execute", "tool_input": {"command": "git push -f"}}),
1291            ),
1292            (
1293                "qwen",
1294                json!({"hook_event_name": "PreToolUse", "session_id": "task-0001", "cwd": "/tmp",
1295                       "tool_name": "run_shell_command", "tool_input": {"command": "git push -f"}}),
1296            ),
1297        ];
1298        for (runner, input) in cases {
1299            let v = payload(runner, input.clone());
1300            let call = crate::hook_call(&v.to_string());
1301            assert_eq!(call.event, "PreToolUse", "{runner}: {v}");
1302            assert_eq!(call.cue, "git push -f", "{runner}: {v}");
1303            assert_eq!(call.session.as_deref(), Some("task-0001"), "{runner}: {v}");
1304            assert_eq!(
1305                crate::hook_directory(&v.to_string()).unwrap(),
1306                std::fs::canonicalize("/tmp").unwrap(),
1307                "{runner}"
1308            );
1309        }
1310        let prompt = payload(
1311            "gemini",
1312            json!({"hook_event_name": "BeforeAgent", "session_id": "t", "prompt": "fix the build"}),
1313        );
1314        let call = crate::hook_call(&prompt.to_string());
1315        assert_eq!(
1316            (call.event.as_str(), call.cue.as_str()),
1317            ("UserPromptSubmit", "fix the build")
1318        );
1319        let prompt = payload(
1320            "cline",
1321            json!({"hookName": "UserPromptSubmit", "taskId": "t", "userPromptSubmit": {"prompt": "fix it"}}),
1322        );
1323        assert_eq!(
1324            crate::hook_call(&prompt.to_string()).event,
1325            "UserPromptSubmit"
1326        );
1327    }
1328
1329    #[test]
1330    fn a_deny_reaches_each_runner_in_its_own_contract() {
1331        let (out, _, code) = answer("copilot", "PreToolUse", DENY);
1332        let v: Value = serde_json::from_str(&out).unwrap();
1333        assert_eq!((v["permissionDecision"].as_str(), code), (Some("deny"), 0));
1334        assert!(v["permissionDecisionReason"]
1335            .as_str()
1336            .unwrap()
1337            .contains("force push"));
1338
1339        let (out, _, code) = answer("gemini", "BeforeTool", DENY);
1340        let v: Value = serde_json::from_str(&out).unwrap();
1341        assert_eq!((v["decision"].as_str(), code), (Some("deny"), 0));
1342        assert!(v["reason"].as_str().unwrap().contains("force push"));
1343
1344        for runner in ["windsurf", "kiro"] {
1345            let (out, err, code) = answer(runner, "PreToolUse", DENY);
1346            assert_eq!((out.as_str(), code), ("", 2), "{runner}");
1347            assert!(err.contains("force push"), "{runner}");
1348        }
1349
1350        for runner in ["factory", "qwen"] {
1351            let (out, err, code) = answer(runner, "PreToolUse", DENY);
1352            assert_eq!(out.as_str(), DENY, "{runner}");
1353            assert_eq!(code, 2, "{runner}");
1354            assert!(err.contains("force push"), "{runner}: {err}");
1355        }
1356
1357        let (out, _, _) = answer("cline", "PreToolUse", DENY);
1358        let v: Value = serde_json::from_str(&out).unwrap();
1359        assert_eq!(v["cancel"], json!(true));
1360        assert!(v["errorMessage"].as_str().unwrap().contains("force push"));
1361
1362        let (out, err, code) = answer("crush", "PreToolUse", DENY);
1363        let v: Value = serde_json::from_str(&out).unwrap();
1364        assert_eq!(v["decision"], json!("deny"));
1365        assert_eq!(code, 2);
1366        assert!(err.contains("force push"));
1367    }
1368
1369    #[test]
1370    fn an_ask_is_a_deny_where_the_runner_cannot_ask() {
1371        let (out, _, _) = answer("copilot", "PreToolUse", ASK);
1372        assert!(out.contains("\"ask\""));
1373        for runner in ["gemini", "cline", "crush"] {
1374            let (out, _, _) = answer(runner, "PreToolUse", ASK);
1375            assert!(!out.contains("\"ask\""), "{runner}: {out}");
1376            assert!(out.contains("cannot ask"), "{runner}: {out}");
1377        }
1378        let (_, err, code) = answer("windsurf", "PreToolUse", ASK);
1379        assert_eq!(code, 2);
1380        assert!(err.contains("ask the person"));
1381    }
1382
1383    #[test]
1384    fn an_allow_says_nothing_and_a_note_reaches_runners_that_take_one() {
1385        for runner in ["copilot", "windsurf", "kiro", "crush"] {
1386            assert_eq!(
1387                answer(runner, "PreToolUse", ""),
1388                (String::new(), String::new(), 0)
1389            );
1390        }
1391        let (out, _, code) = answer("cline", "PreToolUse", "");
1392        assert_eq!(
1393            serde_json::from_str::<Value>(&out).unwrap(),
1394            json!({"cancel": false})
1395        );
1396        assert_eq!(code, 0);
1397        let (out, _, _) = answer("gemini", "BeforeAgent", NOTE);
1398        let v: Value = serde_json::from_str(&out).unwrap();
1399        assert_eq!(v["hookSpecificOutput"]["hookEventName"], "BeforeAgent");
1400        assert_eq!(
1401            v["hookSpecificOutput"]["additionalContext"],
1402            "lesson: run the tests"
1403        );
1404        let (out, _, _) = answer("cline", "UserPromptSubmit", NOTE);
1405        assert!(out.contains("contextModification"));
1406    }
1407
1408    #[cfg(unix)]
1409    fn sh(script: &str) -> std::process::Command {
1410        let mut cmd = std::process::Command::new("sh");
1411        cmd.arg("-c").arg(script);
1412        cmd
1413    }
1414
1415    #[cfg(unix)]
1416    fn inner(script: &str, timeout_ms: u64) -> String {
1417        run_inner(
1418            sh(script),
1419            r#"{"tool_name":"Bash"}"#,
1420            "PreToolUse",
1421            std::time::Duration::from_millis(timeout_ms),
1422        )
1423    }
1424
1425    fn runner_denied(runner: &str, stdout: &str, _stderr: &str, code: i32) -> bool {
1426        match runner {
1427            "copilot" => code == 0 && stdout.contains(r#""permissionDecision":"deny""#),
1428            "gemini" => code == 0 && stdout.contains(r#""decision":"deny""#),
1429            "windsurf" | "factory" | "kiro" | "qwen" | "crush" | "goose" | "amp" | "openhands" => {
1430                code == 2
1431            }
1432            "cline" => code == 0 && stdout.contains(r#""cancel":true"#),
1433            "auggie" => code == 0 && stdout.contains(r#""permissionDecision":"deny""#),
1434            _ => false,
1435        }
1436    }
1437
1438    #[test]
1439    fn a_relay_fault_allows_and_warns_in_the_runners_contract() {
1440        for runner in RUNNERS {
1441            let (stdout, stderr, code) =
1442                relay_fault_deny(runner, "", "stdin is not utf-8").expect(runner);
1443            let body = format!("{stdout}{stderr}");
1444            assert_eq!(code, 0, "{runner}: code {code} {body}");
1445            assert!(
1446                !runner_denied(runner, &stdout, &stderr, code),
1447                "{runner}: {body}"
1448            );
1449            if shows_context(runner) {
1450                assert!(body.contains("unhealthy"), "{runner}: {body}");
1451                assert!(body.contains("stdin is not utf-8"), "{runner}: {body}");
1452            }
1453        }
1454        for runner in ["gemini", "copilot", "cline", "auggie"] {
1455            let (stdout, stderr, code) =
1456                relay_fault_deny(runner, "BeforeTool", "stdin is not utf-8").expect(runner);
1457            let body = format!("{stdout}{stderr}");
1458            assert_eq!(code, 0, "{runner}: {body}");
1459            assert!(
1460                !runner_denied(runner, &stdout, &stderr, code),
1461                "{runner}: {body}"
1462            );
1463        }
1464        assert!(relay_fault_deny("windsurf", "UserPromptSubmit", "stdin is not utf-8").is_none());
1465        assert!(relay_fault_deny("gemini", "BeforeAgent", "stdin is not utf-8").is_none());
1466        assert!(relay_event_is_gate(None));
1467        assert!(relay_event_is_gate(Some("")));
1468        assert!(!relay_event_is_gate(Some("BeforeAgent")));
1469        assert!(relay_input_is_gate(
1470            r#"{"hook_event_name":"PreToolUse"}"#,
1471            Some("UserPromptSubmit")
1472        ));
1473        assert!(!relay_input_is_gate(
1474            r#"{"hook_event_name":"UserPromptSubmit","prompt":"hi"}"#,
1475            None
1476        ));
1477    }
1478
1479    fn shows_context(runner: &str) -> bool {
1480        matches!(
1481            runner,
1482            "gemini" | "openhands" | "auggie" | "kiro" | "cline" | "crush" | "factory" | "qwen"
1483        )
1484    }
1485
1486    fn allows_fault(out: &str, why: &str) {
1487        let said = read_answer(out);
1488        assert!(said.decision.is_none(), "{out}");
1489        assert!(said.context.contains("unhealthy"), "{out}");
1490        assert!(said.context.contains(why), "{out}");
1491        for runner in RUNNERS {
1492            let (stdout, stderr, code) = answer(runner, "PreToolUse", out);
1493            let body = format!("{stdout}{stderr}");
1494            assert_eq!(code, 0, "{runner}: {body}");
1495            assert!(
1496                !runner_denied(runner, &stdout, &stderr, code),
1497                "{runner}: {body}"
1498            );
1499            if shows_context(runner) {
1500                assert!(body.contains("unhealthy"), "{runner}: {body}");
1501                assert!(body.contains(why), "{runner}: {body}");
1502            }
1503        }
1504    }
1505
1506    #[cfg(unix)]
1507    #[test]
1508    fn an_inner_hook_fault_allows_in_every_runner_shape() {
1509        let _lock = crate::test_env_lock();
1510        unsafe { std::env::remove_var("LJOS_GUARD_FAIL_OPEN") };
1511        // The timeout, the exit, and the signal are injected. A wall-clock
1512        // race is what made a slow runner report the timeout instead of
1513        // the signal.
1514        let timeout = std::time::Duration::from_secs(5);
1515        let injected = [
1516            format!("gave no answer within {} s", timeout.as_secs_f32()),
1517            "exited with status 3".to_string(),
1518            "was killed by a signal".to_string(),
1519        ];
1520        for why in &injected {
1521            allows_fault(&fault_output("PreToolUse", why), why);
1522        }
1523        allows_fault(&inner("exit 3", 30_000), "exited with status 3");
1524        let missing = run_inner(
1525            std::process::Command::new("/nonexistent/ljos"),
1526            "{}",
1527            "PreToolUse",
1528            std::time::Duration::from_secs(1),
1529        );
1530        allows_fault(&missing, "did not start");
1531        assert_eq!(INNER_TIMEOUT, crate::GUARD_TIMEOUT);
1532    }
1533
1534    /// A wedged memory pack used to miss the prompt hook's own deadline:
1535    /// the relay waited five seconds, then denied the prompt with "while
1536    /// checking this command". Gemini, Qwen, Factory, OpenHands, goose and
1537    /// Cline all block on that deny. A prompt is not a tool call.
1538    #[test]
1539    fn a_prompt_fault_is_not_a_deny() {
1540        let _lock = crate::test_env_lock();
1541        unsafe { std::env::remove_var("LJOS_GUARD_FAIL_OPEN") };
1542        let why = format!(
1543            "gave no answer within {} s",
1544            crate::GUARD_TIMEOUT.as_secs_f32()
1545        );
1546        let prompts = [
1547            ("gemini", "BeforeAgent"),
1548            ("qwen", "UserPromptSubmit"),
1549            ("factory", "UserPromptSubmit"),
1550            ("openhands", "UserPromptSubmit"),
1551            ("goose", "UserPromptSubmit"),
1552            ("cline", "UserPromptSubmit"),
1553        ];
1554        for (runner, event) in prompts {
1555            let fault = fault_output(event, &why);
1556            let said = read_answer(&fault);
1557            assert!(said.decision.is_none(), "{runner}: {fault}");
1558            assert!(
1559                !fault.contains("while checking this command"),
1560                "{runner}: {fault}"
1561            );
1562            assert!(said.context.contains("unhealthy"), "{runner}: {fault}");
1563            let (stdout, stderr, code) = answer(runner, event, &fault);
1564            let body = format!("{stdout}{stderr}");
1565            assert_eq!(code, 0, "{runner}: {body}");
1566            assert!(
1567                !runner_denied(runner, &stdout, &stderr, code),
1568                "{runner}: {body}"
1569            );
1570            assert!(
1571                !body.contains("while checking this command"),
1572                "{runner}: {body}"
1573            );
1574        }
1575        allows_fault(&fault_output("PreToolUse", &why), &why);
1576        allows_fault(&fault_output("BeforeTool", &why), &why);
1577        let deadline = std::time::Duration::from_millis(crate::HOOK_DEADLINE_MS);
1578        assert!(relay_timeout("UserPromptSubmit") >= deadline);
1579        assert!(relay_timeout("BeforeAgent") >= deadline);
1580        assert!(relay_timeout("pre_user_prompt") >= deadline);
1581        assert_eq!(relay_timeout("PreToolUse"), crate::guard_timeout());
1582        assert_eq!(relay_timeout("BeforeTool"), crate::guard_timeout());
1583        assert_eq!(relay_timeout(""), crate::guard_timeout());
1584    }
1585
1586    #[cfg(unix)]
1587    #[test]
1588    fn a_prompt_hook_that_exits_early_is_not_denied() {
1589        let _lock = crate::test_env_lock();
1590        unsafe { std::env::remove_var("LJOS_GUARD_FAIL_OPEN") };
1591        let out = run_inner(
1592            sh("exit 3"),
1593            r#"{"hook_event_name":"UserPromptSubmit","prompt":"hello"}"#,
1594            "UserPromptSubmit",
1595            std::time::Duration::from_secs(2),
1596        );
1597        let said = read_answer(&out);
1598        assert!(said.decision.is_none(), "{out}");
1599        assert!(!out.contains("while checking this command"), "{out}");
1600        assert!(said.context.contains("unhealthy"), "{out}");
1601    }
1602
1603    /// The relay used to deny a tool call whose answer was the exact
1604    /// unhealthy-guard sentence. A push warning joined onto that sentence
1605    /// defeated the match, so the same fault was allowed. The check denies
1606    /// a real fault itself. An allow that carries the sentence, alone or
1607    /// with a warning, stays that allow.
1608    #[cfg(unix)]
1609    #[test]
1610    fn an_unhealthy_note_is_not_a_second_deny() {
1611        let _lock = crate::test_env_lock();
1612        unsafe { std::env::remove_var("LJOS_GUARD_FAIL_OPEN") };
1613        let why = "did not answer in time";
1614        let exact = json!({
1615            "hookSpecificOutput": {
1616                "hookEventName": "PreToolUse",
1617                "additionalContext": crate::unhealthy_note(why),
1618            }
1619        })
1620        .to_string();
1621        let merged = json!({
1622            "hookSpecificOutput": {
1623                "hookEventName": "PreToolUse",
1624                "additionalContext": format!(
1625                    "{}\nthe tip has no passing test record",
1626                    crate::unhealthy_note(why)
1627                ),
1628            }
1629        })
1630        .to_string();
1631        for body in [exact, merged] {
1632            let out = inner(&format!("printf '%s' '{body}'"), 30_000);
1633            allows_fault(&out, why);
1634        }
1635    }
1636
1637    #[cfg(unix)]
1638    #[test]
1639    fn an_inner_hook_that_answers_keeps_its_answer() {
1640        let _lock = crate::test_env_lock();
1641        unsafe { std::env::remove_var("LJOS_GUARD_FAIL_OPEN") };
1642        assert_eq!(inner("true", 30_000), "", "a clean allow");
1643        assert_eq!(inner(&format!("printf '%s' '{DENY}'"), 30_000), DENY);
1644        assert_eq!(
1645            inner(&format!("printf '%s' '{DENY}'; exit 1"), 30_000),
1646            DENY,
1647            "a deny printed before a non-zero exit stands"
1648        );
1649        let note = inner(&format!("printf '%s' '{NOTE}'; exit 1"), 30_000);
1650        allows_fault(&note, "exited with status 1");
1651    }
1652
1653    #[cfg(unix)]
1654    #[test]
1655    fn guard_fail_open_restores_allow_with_note() {
1656        let _lock = crate::test_env_lock();
1657        unsafe { std::env::set_var("LJOS_GUARD_FAIL_OPEN", "1") };
1658        allows_fault(
1659            &fault_output("PreToolUse", "exited with status 3"),
1660            "exited with status 3",
1661        );
1662        allows_fault(&inner("exit 3", 30_000), "exited with status 3");
1663        let unhealthy = json!({
1664            "hookSpecificOutput": {
1665                "hookEventName": "PreToolUse",
1666                "additionalContext": crate::unhealthy_note("did not answer in time"),
1667            }
1668        })
1669        .to_string();
1670        let from_policyd = inner(&format!("printf '%s' '{unhealthy}'"), 30_000);
1671        allows_fault(&from_policyd, "did not answer in time");
1672    }
1673
1674    #[test]
1675    fn a_known_dangerous_command_is_judged_before_the_inner_hook() {
1676        use std::os::unix::fs::PermissionsExt;
1677        let _lock = crate::test_env_lock();
1678        let dir = crate::test_seat_root::seat_root(crate::bookkeep::path_is_temp)
1679            .join(format!("ljos-early-{}", std::process::id()));
1680        let _ = std::fs::remove_dir_all(&dir);
1681        std::fs::create_dir_all(&dir).unwrap();
1682        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
1683        let data = dir.join("data");
1684        unsafe {
1685            std::env::set_var("HOME", &dir);
1686            std::env::set_var("XDG_DATA_HOME", &data);
1687            std::env::set_var("LJOS_OFF", "0");
1688            std::env::set_var("POLICYD_BIN", dir.join("does-not-run"));
1689            std::env::set_var("PACKSET_WORKSPACE", "early-guard");
1690        }
1691        let force = json!({"tool_input": {"command": "git push --force origin main"}}).to_string();
1692        let started = std::time::Instant::now();
1693        let asked = early_answer(&force, "PreToolUse").expect("a force push asks");
1694        let plain = json!({"tool_input": {"command": "git status"}}).to_string();
1695        assert!(
1696            early_answer(&plain, "").is_none(),
1697            "git status is not dangerous"
1698        );
1699        let rm = json!({"tool_input": {"command": "rm -rf /home/u/proj"}}).to_string();
1700        let denied = early_answer(&rm, "PreToolUse").expect("rm -rf denies");
1701        assert!(
1702            started.elapsed() < std::time::Duration::from_secs(5),
1703            "the static check waited on the guard"
1704        );
1705        assert_eq!(
1706            read_answer(&asked).decision.as_deref(),
1707            Some("ask"),
1708            "{asked}"
1709        );
1710        assert!(asked.contains("git-force-push"), "{asked}");
1711        assert!(!asked.contains("git-push-evidence"), "{asked}");
1712        assert_eq!(
1713            read_answer(&denied).decision.as_deref(),
1714            Some("deny"),
1715            "{denied}"
1716        );
1717        assert!(denied.contains("rm-rf-outside-tmp"), "{denied}");
1718        // Gemini names the gate BeforeTool. A verdict rendered under that
1719        // name used to omit the decision, and Gemini allows an object
1720        // that has none.
1721        let before = early_answer(&rm, "BeforeTool").expect("BeforeTool is still a gate");
1722        assert_eq!(
1723            read_answer(&before).decision.as_deref(),
1724            Some("deny"),
1725            "{before}"
1726        );
1727        let (out, _, code) = answer("gemini", "BeforeTool", &before);
1728        assert_eq!(code, 0);
1729        assert!(out.contains("\"deny\""), "{out}");
1730        assert!(!out.contains("\"ask\""), "{out}");
1731        let wind = early_answer(&rm, "pre_run_command").expect("pre_run_command is still a gate");
1732        assert_eq!(
1733            read_answer(&wind).decision.as_deref(),
1734            Some("deny"),
1735            "{wind}"
1736        );
1737        let _ = std::fs::remove_dir_all(&dir);
1738    }
1739
1740    #[test]
1741    fn hook_files_are_written_in_each_runner_shape_and_never_twice() {
1742        let tmp = tempfile::tempdir().unwrap();
1743        let dir = tmp.path().to_path_buf();
1744        let base = "/opt/bin/ljos hook";
1745        for runner in RUNNERS {
1746            let file = if *runner == "cline" {
1747                dir.join("cline-hooks")
1748            } else {
1749                dir.join(format!("{runner}.json"))
1750            };
1751            if *runner == "gemini" {
1752                // A settings file with entries of its own keeps them.
1753                std::fs::write(&file, r#"{"mcpServers":{"x":{}},"hooks":{"BeforeTool":[{"matcher":"x","hooks":[]}]}}"#).unwrap();
1754            }
1755            let first = hook_step(runner, &file, base, false);
1756            assert!(first.ok, "{runner}: {}", first.detail);
1757            assert!(first.detail.contains("wrote"), "{runner}: {}", first.detail);
1758            let again = hook_step(runner, &file, base, false);
1759            assert!(
1760                again.ok && again.detail.contains("carries"),
1761                "{runner}: {}",
1762                again.detail
1763            );
1764            let command = format!("{base} --runner {runner}");
1765            if *runner == "cline" {
1766                for event in ["PreToolUse", "UserPromptSubmit"] {
1767                    let text = std::fs::read_to_string(file.join(event)).unwrap();
1768                    assert!(text.contains(&command));
1769                }
1770                continue;
1771            }
1772            let v: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
1773            let found = |p: &str| v.pointer(p).cloned().unwrap_or(Value::Null);
1774            match *runner {
1775                "copilot" => {
1776                    assert_eq!(found("/version"), json!(1));
1777                    assert_eq!(found("/hooks/PreToolUse/0/bash"), json!(command));
1778                    assert_eq!(found("/hooks/PreToolUse/0/matcher"), json!("Bash"));
1779                }
1780                "gemini" => {
1781                    assert_eq!(found("/mcpServers/x"), json!({}));
1782                    assert_eq!(found("/hooks/BeforeTool/0/matcher"), json!("x"));
1783                    assert_eq!(
1784                        found("/hooks/BeforeTool/1/matcher"),
1785                        json!("run_shell_command")
1786                    );
1787                    assert_eq!(
1788                        found("/hooks/BeforeTool/1/hooks/0/timeout"),
1789                        json!(20_000),
1790                        "milliseconds"
1791                    );
1792                    assert_eq!(
1793                        found("/hooks/BeforeAgent/0/hooks/0/command"),
1794                        json!(command)
1795                    );
1796                }
1797                "qwen" => {
1798                    assert_eq!(
1799                        found("/hooks/PreToolUse/0/matcher"),
1800                        json!("^run_shell_command$")
1801                    );
1802                    assert_eq!(
1803                        found("/hooks/PreToolUse/0/hooks/0/timeout"),
1804                        json!(20),
1805                        "seconds"
1806                    );
1807                }
1808                "factory" => {
1809                    assert_eq!(found("/PreToolUse/0/matcher"), json!("Execute"));
1810                    assert_eq!(found("/PreToolUse/0/hooks/0/command"), json!(command));
1811                }
1812                "windsurf" => {
1813                    assert_eq!(found("/hooks/pre_run_command/0/command"), json!(command));
1814                }
1815                "kiro" => {
1816                    assert_eq!(found("/version"), json!("v1"));
1817                    assert_eq!(found("/hooks/0/trigger"), json!("PreToolUse"));
1818                    assert_eq!(found("/hooks/0/action/command"), json!(command));
1819                }
1820                "crush" => {
1821                    assert_eq!(found("/hooks/PreToolUse/0/matcher"), json!("^bash$"));
1822                    assert_eq!(found("/hooks/PreToolUse/0/command"), json!(command));
1823                }
1824                "goose" => {
1825                    assert_eq!(found("/hooks/PreToolUse/0/hooks/0/command"), json!(command));
1826                }
1827                "auggie" => {
1828                    assert_eq!(
1829                        found("/hooks/PreToolUse/0/matcher"),
1830                        json!("launch-process")
1831                    );
1832                    let script = script_path("auggie", &file).display().to_string();
1833                    assert_eq!(found("/hooks/PreToolUse/0/hooks/0/command"), json!(script));
1834                }
1835                "amp" => {
1836                    assert_eq!(found("/amp.permissions/0/action"), json!("delegate"));
1837                }
1838                "openhands" => {
1839                    assert_eq!(found("/hooks/PreToolUse/0/matcher"), json!("terminal"));
1840                    assert_eq!(found("/hooks/PreToolUse/0/hooks/0/command"), json!(command));
1841                }
1842                _ => unreachable!(),
1843            }
1844        }
1845        let foreign = dir.join("foreign-cline");
1846        std::fs::create_dir_all(&foreign).unwrap();
1847        std::fs::write(foreign.join("PreToolUse"), "#!/bin/sh\necho mine\n").unwrap();
1848        let step = hook_step("cline", &foreign, base, false);
1849        assert!(
1850            !step.ok && step.detail.contains("someone else's"),
1851            "{}",
1852            step.detail
1853        );
1854    }
1855
1856    #[test]
1857    fn goose_payload_reaches_the_seat_and_a_deny_exits_2() {
1858        let n = normalize_input(
1859            "goose",
1860            r#"{"event":"PreToolUse","session_id":"g-1","tool_name":"shell","tool_input":{"command":"rm -rf /"},"working_dir":"/r"}"#,
1861        );
1862        let v: Value = serde_json::from_str(&n).unwrap();
1863        assert_eq!(v["hook_event_name"], "PreToolUse");
1864        assert_eq!(v["tool_input"]["command"], "rm -rf /");
1865        assert_eq!(v["cwd"], "/r");
1866        let deny = r#"{"hookSpecificOutput":{"permissionDecision":"deny","permissionDecisionReason":"no"}}"#;
1867        assert_eq!(
1868            answer("goose", "PreToolUse", deny),
1869            (String::new(), "no\n".into(), 2)
1870        );
1871        assert_eq!(answer("goose", "PreToolUse", "{}").2, 0);
1872    }
1873
1874    #[test]
1875    fn amp_reads_cmd_and_rejects_with_2_and_asks_with_1() {
1876        let n = normalize_input("amp", r#"{"cmd":"git push --force"}"#);
1877        let v: Value = serde_json::from_str(&n).unwrap();
1878        assert_eq!(v["tool_input"]["command"], "git push --force");
1879        let deny = r#"{"hookSpecificOutput":{"permissionDecision":"deny","permissionDecisionReason":"no"}}"#;
1880        assert_eq!(answer("amp", "", deny).2, 2);
1881        let ask = r#"{"hookSpecificOutput":{"permissionDecision":"ask","permissionDecisionReason":"sure?"}}"#;
1882        assert_eq!(answer("amp", "", ask).2, 1);
1883        assert_eq!(answer("amp", "", "").2, 0);
1884    }
1885
1886    #[test]
1887    fn auggie_launch_process_is_the_shell_and_its_deny_is_claude_shaped() {
1888        let n = normalize_input(
1889            "auggie",
1890            r#"{"hook_event_name":"PreToolUse","tool_name":"launch-process","tool_input":{"command":"ls"}}"#,
1891        );
1892        let v: Value = serde_json::from_str(&n).unwrap();
1893        assert_eq!(v["tool_name"], "Bash");
1894        let deny = r#"{"hookSpecificOutput":{"permissionDecision":"deny","permissionDecisionReason":"no"}}"#;
1895        let (out, _, code) = answer("auggie", "PreToolUse", deny);
1896        let o: Value = serde_json::from_str(&out).unwrap();
1897        assert_eq!(o["hookSpecificOutput"]["permissionDecision"], "deny");
1898        assert_eq!(code, 0);
1899    }
1900
1901    #[test]
1902    fn auggie_and_amp_hooks_name_a_script_and_are_written_once() {
1903        for (runner, name) in [("auggie", "settings.json"), ("amp", "settings.json")] {
1904            let dir = tempfile::tempdir().unwrap();
1905            let file = dir.path().join(name);
1906            std::fs::write(
1907                &file,
1908                r#"{"keep": 1, "amp.permissions": [{"tool": "Read", "action": "allow"}]}"#,
1909            )
1910            .unwrap();
1911            let step = hook_step(runner, &file, "/bin/ljos hook", false);
1912            assert!(step.ok, "{}", step.detail);
1913            let script = script_path(runner, &file);
1914            let text = std::fs::read_to_string(&script).unwrap();
1915            assert!(text.contains(&format!("/bin/ljos hook --runner {runner}")));
1916            let v: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
1917            assert_eq!(v["keep"], 1);
1918            assert!(v.to_string().contains(&script.display().to_string()));
1919            if runner == "amp" {
1920                assert_eq!(v["amp.permissions"][0]["action"], "delegate");
1921                assert_eq!(v["amp.permissions"][1]["tool"], "Read");
1922            }
1923            let again = hook_step(runner, &file, "/bin/ljos hook", false);
1924            assert!(again.detail.contains("carries"), "{}", again.detail);
1925        }
1926    }
1927
1928    #[test]
1929    fn goose_hook_is_a_plugin_that_fails_closed() {
1930        let dir = tempfile::tempdir().unwrap();
1931        let file = dir.path().join("ljos/hooks/hooks.json");
1932        let step = hook_step("goose", &file, "/bin/ljos hook", false);
1933        assert!(step.ok, "{}", step.detail);
1934        let v: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
1935        assert_eq!(
1936            v["hooks"]["PreToolUse"][0]["hooks"][0]["on_failure"],
1937            "block"
1938        );
1939        assert!(dir.path().join("ljos/plugin.json").is_file());
1940        assert!(hook_step("goose", &file, "/bin/ljos hook", false)
1941            .detail
1942            .contains("carries"));
1943    }
1944
1945    #[test]
1946    fn openhands_terminal_is_the_shell_and_a_deny_exits_2() {
1947        let n = normalize_input(
1948            "openhands",
1949            r#"{"event_type":"PreToolUse","tool_name":"terminal","tool_input":{"command":"rm -rf ~"},"working_dir":"/w"}"#,
1950        );
1951        let v: Value = serde_json::from_str(&n).unwrap();
1952        assert_eq!(v["tool_name"], "Bash");
1953        assert_eq!(v["cwd"], "/w");
1954        let deny = r#"{"hookSpecificOutput":{"permissionDecision":"deny","permissionDecisionReason":"no"}}"#;
1955        let (out, _, code) = answer("openhands", "PreToolUse", deny);
1956        assert!(out.contains("\"decision\":\"deny\""));
1957        assert_eq!(code, 2);
1958    }
1959
1960    #[test]
1961    fn the_start_line_leads_an_openhands_prompt_note() {
1962        let out = with_start_line("{\"additionalContext\":\"lesson\"}\n", "ljos is on: x");
1963        let v: Value = serde_json::from_str(&out).unwrap();
1964        assert_eq!(v["additionalContext"], "ljos is on: x\n\nlesson");
1965        assert_eq!(
1966            with_start_line("", "ljos is on").trim(),
1967            r#"{"additionalContext":"ljos is on"}"#
1968        );
1969    }
1970}