Skip to main content

kintsugi_intercept/
dialect.rs

1//! Per-CLI hook dialects.
2//!
3//! Every supported agent CLI exposes a "run a command before the tool executes,
4//! read a decision back" hook — but each speaks a slightly different protocol on
5//! stdin and stdout. A [`Dialect`] knows how to (a) parse one CLI's PreTool
6//! payload into a normalized [`Shell`] command and (b) serialize the daemon's
7//! [`Verdict`] back into that CLI's decision protocol.
8//!
9//! The decision *policy* (what Allow/Deny/Hold means, and that a catastrophic
10//! hold becomes a deny) lives in [`crate::hook`] and is identical for every
11//! dialect — only the wire format differs here. This keeps the security spine in
12//! one place and the per-CLI glue mechanical.
13//!
14//! Protocols, as researched against each CLI's docs:
15//! - Claude Code / Qwen Code / Codex CLI: `{tool_name, tool_input.command}` in;
16//!   `{hookSpecificOutput:{permissionDecision: allow|deny|ask, …}}` out.
17//! - Gemini CLI: `{tool_name, tool_input.command}` in; `{decision: allow|deny}`
18//!   out (no native "ask" — an ambiguous hold is mapped to deny).
19//! - GitHub Copilot CLI: `{toolName, toolArgs.command}` in (camelCase);
20//!   `{permissionDecision: allow|deny|ask, permissionDecisionReason}` out.
21//! - Cursor CLI: `{command, cwd}` in (beforeShellExecution); `{permission:
22//!   allow|deny|ask, userMessage, agentMessage}` out.
23//! - OpenCode: no external-command hook — a bundled JS plugin bridges to us with
24//!   a simple `{command, cwd}` in / `{decision: allow|deny|ask, reason}` out.
25//! - Google Antigravity: plugin `PreToolUse` hook (matcher `run_command`).
26//!   `{toolCall:{name, arguments:{CommandLine, Cwd}}, conversationId}` in
27//!   (PascalCase argument keys); `{decision: allow|deny, reason}` out — no native
28//!   ask, so an ambiguous hold is mapped to deny.
29
30use std::path::PathBuf;
31
32use kintsugi_core::{Class, Decision, Verdict};
33use serde::Deserialize;
34
35/// Which agent CLI's hook protocol to speak.
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub enum Dialect {
38    Claude,
39    Qwen,
40    Gemini,
41    Copilot,
42    Cursor,
43    OpenCode,
44    Codex,
45    Antigravity,
46}
47
48/// A normalized shell command extracted from a hook payload.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct Shell {
51    pub command: String,
52    pub cwd: PathBuf,
53    pub session_id: Option<String>,
54}
55
56/// A non-shell, content-ingesting tool call surfaced for provenance observation
57/// (a `WebFetch`, `Read`, web-search, MCP call). The raw `input` object is handed
58/// to [`crate::observe::classify_tool_ingest`]; we never read the *result* bytes.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct ContentCall {
61    pub tool: String,
62    pub input: serde_json::Value,
63    pub cwd: PathBuf,
64    pub session_id: Option<String>,
65}
66
67/// Result of parsing a hook payload.
68#[derive(Debug, PartialEq, Eq)]
69pub enum Parsed {
70    /// A shell command to send to the daemon.
71    Shell(Shell),
72    /// A well-formed payload that isn't a shell tool call — out of scope, pass.
73    NotShell,
74    /// An unparseable payload — fail open (never block on our own parse bug).
75    Bad(String),
76}
77
78/// The resolved, dialect-independent decision the daemon's verdict maps to.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum Resolved {
81    Allow,
82    Deny(String),
83    Ask(String),
84}
85
86/// What the adapter prints on stdout and exits with for one payload.
87#[derive(Debug, PartialEq, Eq)]
88pub struct HookOutcome {
89    pub stdout: Option<String>,
90    pub exit_code: i32,
91}
92
93impl HookOutcome {
94    /// Emit nothing, exit 0 — "Kintsugi has no opinion, use your default flow."
95    pub fn silent() -> Self {
96        Self {
97            stdout: None,
98            exit_code: 0,
99        }
100    }
101    fn json(value: serde_json::Value) -> Self {
102        Self {
103            stdout: Some(value.to_string()),
104            exit_code: 0,
105        }
106    }
107}
108
109impl Dialect {
110    /// Map an `--agent` value to a dialect. Accepts the CLI's stable id.
111    pub fn from_agent(s: &str) -> Option<Self> {
112        Some(match s {
113            "claude" | "claude-code" => Dialect::Claude,
114            "qwen" => Dialect::Qwen,
115            "gemini" => Dialect::Gemini,
116            "copilot" => Dialect::Copilot,
117            "cursor" => Dialect::Cursor,
118            "opencode" => Dialect::OpenCode,
119            "codex" => Dialect::Codex,
120            "antigravity" => Dialect::Antigravity,
121            _ => return None,
122        })
123    }
124
125    /// The `agent` tag stamped onto the [`kintsugi_core::ProposedCommand`] so the
126    /// log and TUI attribute the command to the right CLI.
127    pub fn agent_id(self) -> &'static str {
128        match self {
129            Dialect::Claude => "claude-code",
130            Dialect::Qwen => "qwen",
131            Dialect::Gemini => "gemini",
132            Dialect::Copilot => "copilot",
133            Dialect::Cursor => "cursor",
134            Dialect::OpenCode => "opencode",
135            Dialect::Codex => "codex",
136            Dialect::Antigravity => "antigravity",
137        }
138    }
139
140    /// Does this CLI have a native "ask the user" decision? If not, an ambiguous
141    /// hold is mapped to deny — safe per the monotonic-caution rule (the model
142    /// may only add caution, never remove it).
143    fn supports_ask(self) -> bool {
144        // Gemini's decision enum is allow/deny/block, and Antigravity's hook
145        // decision is allow/deny — neither has an interactive ask.
146        !matches!(self, Dialect::Gemini | Dialect::Antigravity)
147    }
148
149    /// Parse one CLI's hook payload into a normalized command.
150    pub fn parse(self, input: &str) -> Parsed {
151        match self {
152            Dialect::Claude | Dialect::Qwen | Dialect::Gemini | Dialect::Codex => {
153                self.parse_tool_style(input)
154            }
155            Dialect::Copilot => parse_copilot(input),
156            Dialect::Cursor | Dialect::OpenCode => parse_flat(input),
157            Dialect::Antigravity => parse_antigravity(input),
158        }
159    }
160
161    /// Extract a non-shell content-tool call for provenance observation, if this
162    /// payload is one. Tolerant: returns `None` (rather than erroring) for shell
163    /// tools, unparseable input, or dialects that only ever carry shell commands
164    /// (Cursor / OpenCode). Observation never blocks, so a miss is harmless.
165    pub fn parse_content(self, input: &str) -> Option<ContentCall> {
166        let v: serde_json::Value = serde_json::from_str(input).ok()?;
167        let get_str = |val: &serde_json::Value, k: &str| {
168            val.get(k).and_then(|s| s.as_str()).map(String::from)
169        };
170        let (tool, args, cwd, session) = match self {
171            Dialect::Claude | Dialect::Qwen | Dialect::Gemini | Dialect::Codex => (
172                get_str(&v, "tool_name")?,
173                v.get("tool_input")
174                    .cloned()
175                    .unwrap_or(serde_json::Value::Null),
176                get_str(&v, "cwd"),
177                get_str(&v, "session_id"),
178            ),
179            Dialect::Copilot => (
180                get_str(&v, "toolName")?,
181                v.get("toolArgs")
182                    .cloned()
183                    .unwrap_or(serde_json::Value::Null),
184                get_str(&v, "cwd"),
185                get_str(&v, "sessionId"),
186            ),
187            Dialect::Antigravity => {
188                let tc = v.get("toolCall")?;
189                let args = tc
190                    .get("arguments")
191                    .cloned()
192                    .unwrap_or(serde_json::Value::Null);
193                let cwd = args.get("Cwd").and_then(|s| s.as_str()).map(String::from);
194                (
195                    get_str(tc, "name")?,
196                    args,
197                    cwd,
198                    get_str(&v, "conversationId"),
199                )
200            }
201            // These dialects' hooks only ever deliver a shell command — no content
202            // tool to observe through this surface.
203            Dialect::Cursor | Dialect::OpenCode => return None,
204        };
205        Some(ContentCall {
206            tool,
207            input: args,
208            cwd: cwd_or_current(cwd),
209            session_id: session,
210        })
211    }
212
213    /// Claude/Qwen/Gemini share `{tool_name, tool_input:{command}}`.
214    fn parse_tool_style(self, input: &str) -> Parsed {
215        let p: ToolStyle = match serde_json::from_str(input) {
216            Ok(p) => p,
217            Err(e) => return Parsed::Bad(e.to_string()),
218        };
219        let tool = p.tool_name.as_deref().unwrap_or_default();
220        if !self.is_shell_tool(tool) {
221            return Parsed::NotShell;
222        }
223        match p.tool_input.and_then(|t| t.command) {
224            Some(c) if !c.trim().is_empty() => Parsed::Shell(Shell {
225                command: c,
226                cwd: cwd_or_current(p.cwd),
227                session_id: p.session_id,
228            }),
229            _ => Parsed::NotShell,
230        }
231    }
232
233    /// Is `name` this dialect's shell tool? The canonical name delivered in the
234    /// payload differs per CLI; we also accept the cross-CLI aliases so a
235    /// version that reports a different label still matches.
236    fn is_shell_tool(self, name: &str) -> bool {
237        match self {
238            // Claude reports Bash; accept the lowercase/Shell variants too.
239            Dialect::Claude => matches!(name, "Bash" | "Shell" | "bash" | "shell"),
240            // Qwen's canonical name is run_shell_command, with Claude-compat
241            // aliases Bash/Shell/ShellTool.
242            Dialect::Qwen => matches!(
243                name,
244                "run_shell_command" | "Bash" | "Shell" | "ShellTool" | "bash" | "shell"
245            ),
246            // Gemini only ever reports run_shell_command.
247            Dialect::Gemini => matches!(name, "run_shell_command" | "Shell" | "shell"),
248            // Codex modeled its hooks on Claude Code; its shell tool is Bash.
249            Dialect::Codex => matches!(name, "Bash" | "Shell" | "bash" | "shell"),
250            _ => false,
251        }
252    }
253
254    /// Serialize a resolved decision into this CLI's stdout protocol.
255    pub fn format(self, resolved: &Resolved) -> HookOutcome {
256        // Downgrade Ask -> Deny for dialects without a native ask.
257        let resolved = match (resolved, self.supports_ask()) {
258            (Resolved::Ask(reason), false) => &Resolved::Deny(reason.clone()),
259            (other, _) => other,
260        };
261        match self {
262            Dialect::Claude | Dialect::Qwen | Dialect::Codex => format_claude_style(resolved),
263            Dialect::Gemini => format_gemini(resolved),
264            Dialect::Copilot => format_copilot(resolved),
265            Dialect::Cursor => format_cursor(resolved),
266            Dialect::OpenCode => format_opencode(resolved),
267            Dialect::Antigravity => format_antigravity(resolved),
268        }
269    }
270
271    /// The "allow / no opinion" output used on the fail-open path and for SAFE
272    /// commands. Most CLIs treat empty output as "proceed normally"; Cursor's
273    /// beforeShellExecution gate is answered with an explicit allow.
274    pub fn pass(self) -> HookOutcome {
275        match self {
276            Dialect::Cursor => format_cursor(&Resolved::Allow),
277            // Antigravity's contract is "read a JSON decision object from stdout",
278            // so answer its gate with an explicit allow rather than silence.
279            Dialect::Antigravity => format_antigravity(&Resolved::Allow),
280            _ => HookOutcome::silent(),
281        }
282    }
283}
284
285/// The message Kintsugi surfaces through the agent's OWN approval prompt when it
286/// holds an ambiguous command. It names Kintsugi and the rule that fired, and
287/// folds in the local model's plain-English summary (and risk score) when the
288/// model scored the command — so the human decides with context, not a bare
289/// yes/no. The verbatim command is shown by the agent's prompt itself.
290fn flag_reason(verdict: &Verdict) -> String {
291    let mut msg = format!(
292        "Kintsugi flagged this as {} (rule: {})",
293        verdict.class, verdict.reason
294    );
295    if let Some(summary) = verdict.summary.as_deref().filter(|s| !s.is_empty()) {
296        msg.push_str(" — ");
297        msg.push_str(summary);
298    }
299    if let Some(risk) = verdict.risk {
300        msg.push_str(&format!(" [risk {risk}/100]"));
301    }
302    msg.push_str(". Approve only if you intended this.");
303    msg
304}
305
306/// Map a daemon verdict to the dialect-independent decision.
307///
308/// A catastrophic *hold* becomes a deny, not an ask: letting the CLI's own UI
309/// one-click "allow" it would run it with no Kintsugi snapshot, voiding the
310/// reversibility guarantee. Only ambiguous holds become an ask — and that ask
311/// carries Kintsugi's flag + the model's summary so the human understands it.
312pub fn resolve(verdict: &Verdict) -> Resolved {
313    match verdict.decision {
314        Decision::Allow => Resolved::Allow,
315        Decision::Deny => Resolved::Deny(verdict.reason.clone()),
316        Decision::Hold if verdict.class == Class::Catastrophic => {
317            Resolved::Deny(verdict.reason.clone())
318        }
319        Decision::Hold => Resolved::Ask(flag_reason(verdict)),
320    }
321}
322
323// ----- payload structs -------------------------------------------------------
324
325#[derive(Debug, Deserialize)]
326struct ToolStyle {
327    #[serde(default)]
328    cwd: Option<String>,
329    #[serde(default)]
330    session_id: Option<String>,
331    #[serde(default)]
332    tool_name: Option<String>,
333    #[serde(default)]
334    tool_input: Option<CmdInput>,
335}
336
337#[derive(Debug, Deserialize)]
338struct CmdInput {
339    #[serde(default)]
340    command: Option<String>,
341}
342
343#[derive(Debug, Deserialize)]
344struct CopilotStyle {
345    #[serde(default)]
346    cwd: Option<String>,
347    #[serde(default, rename = "sessionId")]
348    session_id: Option<String>,
349    #[serde(default, rename = "toolName")]
350    tool_name: Option<String>,
351    #[serde(default, rename = "toolArgs")]
352    tool_args: Option<CmdInput>,
353}
354
355#[derive(Debug, Deserialize)]
356struct FlatStyle {
357    #[serde(default)]
358    command: Option<String>,
359    #[serde(default)]
360    cwd: Option<String>,
361    #[serde(default)]
362    conversation_id: Option<String>,
363    #[serde(default)]
364    session_id: Option<String>,
365}
366
367fn parse_copilot(input: &str) -> Parsed {
368    let p: CopilotStyle = match serde_json::from_str(input) {
369        Ok(p) => p,
370        Err(e) => return Parsed::Bad(e.to_string()),
371    };
372    // Copilot's shell tool is named "bash" (and "powershell" on Windows).
373    let tool = p.tool_name.as_deref().unwrap_or_default();
374    if !matches!(tool, "bash" | "shell") {
375        return Parsed::NotShell;
376    }
377    match p.tool_args.and_then(|t| t.command) {
378        Some(c) if !c.trim().is_empty() => Parsed::Shell(Shell {
379            command: c,
380            cwd: cwd_or_current(p.cwd),
381            session_id: p.session_id,
382        }),
383        _ => Parsed::NotShell,
384    }
385}
386
387/// Antigravity's `PreToolUse` payload: the command lives in
388/// `toolCall.arguments.CommandLine` (PascalCase), the tool name in
389/// `toolCall.name`, and the session in `conversationId`.
390#[derive(Debug, Deserialize)]
391struct AntigravityStyle {
392    #[serde(default, rename = "toolCall")]
393    tool_call: Option<AntigravityToolCall>,
394    #[serde(default, rename = "conversationId")]
395    conversation_id: Option<String>,
396}
397
398#[derive(Debug, Deserialize)]
399struct AntigravityToolCall {
400    #[serde(default)]
401    name: Option<String>,
402    #[serde(default)]
403    arguments: Option<AntigravityArgs>,
404}
405
406#[derive(Debug, Deserialize)]
407struct AntigravityArgs {
408    #[serde(default, rename = "CommandLine")]
409    command_line: Option<String>,
410    #[serde(default, rename = "Cwd")]
411    cwd: Option<String>,
412}
413
414fn parse_antigravity(input: &str) -> Parsed {
415    let p: AntigravityStyle = match serde_json::from_str(input) {
416        Ok(p) => p,
417        Err(e) => return Parsed::Bad(e.to_string()),
418    };
419    let Some(tc) = p.tool_call else {
420        return Parsed::NotShell;
421    };
422    // Antigravity's shell tool is `run_command`; accept the common aliases too.
423    let tool = tc.name.as_deref().unwrap_or_default();
424    if !matches!(
425        tool,
426        "run_command" | "run_shell_command" | "Bash" | "bash" | "shell"
427    ) {
428        return Parsed::NotShell;
429    }
430    let Some(args) = tc.arguments else {
431        return Parsed::NotShell;
432    };
433    match args.command_line {
434        Some(c) if !c.trim().is_empty() => Parsed::Shell(Shell {
435            command: c,
436            cwd: cwd_or_current(args.cwd),
437            session_id: p.conversation_id,
438        }),
439        _ => Parsed::NotShell,
440    }
441}
442
443fn parse_flat(input: &str) -> Parsed {
444    let p: FlatStyle = match serde_json::from_str(input) {
445        Ok(p) => p,
446        Err(e) => return Parsed::Bad(e.to_string()),
447    };
448    match p.command {
449        Some(c) if !c.trim().is_empty() => Parsed::Shell(Shell {
450            command: c,
451            cwd: cwd_or_current(p.cwd),
452            session_id: p.session_id.or(p.conversation_id),
453        }),
454        _ => Parsed::NotShell,
455    }
456}
457
458fn cwd_or_current(cwd: Option<String>) -> PathBuf {
459    cwd.filter(|s| !s.is_empty())
460        .map(PathBuf::from)
461        .unwrap_or_else(|| std::env::current_dir().unwrap_or_default())
462}
463
464// ----- output formats --------------------------------------------------------
465
466/// Claude Code & Qwen Code: `hookSpecificOutput.permissionDecision`.
467fn format_claude_style(resolved: &Resolved) -> HookOutcome {
468    let (decision, reason) = match resolved {
469        Resolved::Allow => return HookOutcome::silent(),
470        Resolved::Deny(r) => ("deny", r),
471        Resolved::Ask(r) => ("ask", r),
472    };
473    HookOutcome::json(serde_json::json!({
474        "hookSpecificOutput": {
475            "hookEventName": "PreToolUse",
476            "permissionDecision": decision,
477            "permissionDecisionReason": reason,
478        }
479    }))
480}
481
482/// Gemini CLI: `{decision: allow|deny, reason}` (no ask — already downgraded).
483fn format_gemini(resolved: &Resolved) -> HookOutcome {
484    match resolved {
485        Resolved::Allow => HookOutcome::silent(),
486        Resolved::Deny(r) => HookOutcome::json(serde_json::json!({
487            "decision": "deny",
488            "reason": r,
489            "systemMessage": format!("Kintsugi: {r}"),
490        })),
491        // Unreachable: Gemini doesn't support ask, so resolve→format downgrades
492        // it to Deny before we get here. Treat defensively as a deny.
493        Resolved::Ask(r) => HookOutcome::json(serde_json::json!({
494            "decision": "deny",
495            "reason": r,
496        })),
497    }
498}
499
500/// GitHub Copilot CLI: flat `{permissionDecision, permissionDecisionReason}`.
501fn format_copilot(resolved: &Resolved) -> HookOutcome {
502    let (decision, reason) = match resolved {
503        Resolved::Allow => return HookOutcome::silent(),
504        Resolved::Deny(r) => ("deny", r),
505        Resolved::Ask(r) => ("ask", r),
506    };
507    HookOutcome::json(serde_json::json!({
508        "permissionDecision": decision,
509        "permissionDecisionReason": reason,
510    }))
511}
512
513/// Cursor CLI: `{permission, userMessage, agentMessage}`. We emit both camelCase
514/// and snake_case message keys because Cursor's docs are inconsistent across
515/// versions about which it reads; `permission` is the only load-bearing field.
516fn format_cursor(resolved: &Resolved) -> HookOutcome {
517    let (permission, reason) = match resolved {
518        Resolved::Allow => ("allow", None),
519        Resolved::Deny(r) => ("deny", Some(r)),
520        Resolved::Ask(r) => ("ask", Some(r)),
521    };
522    let mut obj = serde_json::json!({ "permission": permission });
523    if let Some(r) = reason {
524        let map = obj.as_object_mut().unwrap();
525        map.insert(
526            "userMessage".into(),
527            serde_json::json!(format!("Kintsugi: {r}")),
528        );
529        map.insert("agentMessage".into(), serde_json::json!(r));
530        map.insert(
531            "user_message".into(),
532            serde_json::json!(format!("Kintsugi: {r}")),
533        );
534        map.insert("agent_message".into(), serde_json::json!(r));
535    }
536    HookOutcome::json(obj)
537}
538
539/// OpenCode bridge: `{decision: allow|deny|ask, reason}`. The bundled JS plugin
540/// reads this and throws (aborting the tool call) on deny/ask.
541fn format_opencode(resolved: &Resolved) -> HookOutcome {
542    let (decision, reason) = match resolved {
543        Resolved::Allow => ("allow", String::new()),
544        Resolved::Deny(r) => ("deny", r.clone()),
545        Resolved::Ask(r) => ("ask", r.clone()),
546    };
547    HookOutcome::json(serde_json::json!({ "decision": decision, "reason": reason }))
548}
549
550/// Google Antigravity: `{decision: allow|deny, reason}` (no ask — already
551/// downgraded). Allow is explicit (its contract expects a decision object).
552fn format_antigravity(resolved: &Resolved) -> HookOutcome {
553    let (decision, reason) = match resolved {
554        Resolved::Allow => ("allow", None),
555        Resolved::Deny(r) => ("deny", Some(r)),
556        // Unreachable: Antigravity has no ask, so resolve→format downgrades it to
557        // Deny before we get here. Treat defensively as a deny.
558        Resolved::Ask(r) => ("deny", Some(r)),
559    };
560    let mut obj = serde_json::json!({ "decision": decision });
561    if let Some(r) = reason {
562        let map = obj.as_object_mut().unwrap();
563        map.insert("reason".into(), serde_json::json!(r));
564        map.insert(
565            "systemMessage".into(),
566            serde_json::json!(format!("Kintsugi: {r}")),
567        );
568    }
569    HookOutcome::json(obj)
570}
571
572#[cfg(test)]
573mod tests {
574    use super::*;
575
576    fn shell(cmd: &str) -> Parsed {
577        Parsed::Shell(Shell {
578            command: cmd.into(),
579            cwd: std::env::current_dir().unwrap_or_default(),
580            session_id: None,
581        })
582    }
583
584    #[test]
585    fn from_agent_accepts_known_ids() {
586        assert_eq!(Dialect::from_agent("claude"), Some(Dialect::Claude));
587        assert_eq!(Dialect::from_agent("claude-code"), Some(Dialect::Claude));
588        assert_eq!(Dialect::from_agent("qwen"), Some(Dialect::Qwen));
589        assert_eq!(Dialect::from_agent("gemini"), Some(Dialect::Gemini));
590        assert_eq!(Dialect::from_agent("copilot"), Some(Dialect::Copilot));
591        assert_eq!(Dialect::from_agent("cursor"), Some(Dialect::Cursor));
592        assert_eq!(Dialect::from_agent("opencode"), Some(Dialect::OpenCode));
593        assert_eq!(Dialect::from_agent("codex"), Some(Dialect::Codex));
594        assert_eq!(
595            Dialect::from_agent("antigravity"),
596            Some(Dialect::Antigravity)
597        );
598        assert_eq!(Dialect::from_agent("nope"), None);
599    }
600
601    #[test]
602    fn antigravity_parses_run_command_with_pascalcase_args() {
603        let p = Dialect::Antigravity.parse(
604            r#"{"toolCall":{"name":"run_command","arguments":{"CommandLine":"rm -rf /","Cwd":"/work"}},"conversationId":"c9"}"#,
605        );
606        match p {
607            Parsed::Shell(s) => {
608                assert_eq!(s.command, "rm -rf /");
609                assert_eq!(s.cwd, PathBuf::from("/work"));
610                assert_eq!(s.session_id.as_deref(), Some("c9"));
611            }
612            other => panic!("expected shell, got {other:?}"),
613        }
614    }
615
616    #[test]
617    fn antigravity_non_shell_tool_is_not_shell() {
618        let p = Dialect::Antigravity
619            .parse(r#"{"toolCall":{"name":"write_file","arguments":{"Path":"x"}}}"#);
620        assert_eq!(p, Parsed::NotShell);
621    }
622
623    #[test]
624    fn antigravity_denies_and_downgrades_ask_to_deny() {
625        // Deny carries a decision + reason.
626        let out = Dialect::Antigravity.format(&Resolved::Deny("boom".into()));
627        let v: serde_json::Value = serde_json::from_str(&out.stdout.unwrap()).unwrap();
628        assert_eq!(v["decision"], "deny");
629        assert_eq!(v["reason"], "boom");
630        // No native ask → a hold becomes deny.
631        let out = Dialect::Antigravity.format(&Resolved::Ask("held".into()));
632        let v: serde_json::Value = serde_json::from_str(&out.stdout.unwrap()).unwrap();
633        assert_eq!(v["decision"], "deny", "antigravity has no ask; must deny");
634    }
635
636    #[test]
637    fn antigravity_allow_and_pass_are_explicit() {
638        let allow = Dialect::Antigravity.format(&Resolved::Allow);
639        let v: serde_json::Value = serde_json::from_str(&allow.stdout.unwrap()).unwrap();
640        assert_eq!(v["decision"], "allow");
641        assert_eq!(
642            Dialect::Antigravity.pass(),
643            format_antigravity(&Resolved::Allow),
644            "antigravity must answer its gate with an explicit allow"
645        );
646    }
647
648    #[test]
649    fn codex_parses_bash_and_formats_claude_style() {
650        let p = Dialect::Codex.parse(r#"{"tool_name":"Bash","tool_input":{"command":"rm -rf /"}}"#);
651        assert_eq!(p, shell("rm -rf /"));
652        let out = Dialect::Codex.format(&Resolved::Deny("boom".into()));
653        let v: serde_json::Value = serde_json::from_str(&out.stdout.unwrap()).unwrap();
654        assert_eq!(v["hookSpecificOutput"]["permissionDecision"], "deny");
655    }
656
657    #[test]
658    fn claude_parses_bash_command() {
659        let p = Dialect::Claude.parse(r#"{"tool_name":"Bash","tool_input":{"command":"ls"}}"#);
660        match p {
661            Parsed::Shell(s) => assert_eq!(s.command, "ls"),
662            other => panic!("expected shell, got {other:?}"),
663        }
664    }
665
666    #[test]
667    fn claude_non_shell_tool_is_not_shell() {
668        let p = Dialect::Claude.parse(r#"{"tool_name":"Edit","tool_input":{"file_path":"x"}}"#);
669        assert_eq!(p, Parsed::NotShell);
670    }
671
672    #[test]
673    fn qwen_parses_run_shell_command_canonical_name() {
674        let p = Dialect::Qwen
675            .parse(r#"{"tool_name":"run_shell_command","tool_input":{"command":"rm -rf x"}}"#);
676        assert_eq!(p, shell("rm -rf x"));
677    }
678
679    #[test]
680    fn gemini_parses_run_shell_command() {
681        let p = Dialect::Gemini
682            .parse(r#"{"tool_name":"run_shell_command","tool_input":{"command":"git push"}}"#);
683        assert_eq!(p, shell("git push"));
684    }
685
686    #[test]
687    fn gemini_ignores_bash_alias() {
688        // Gemini never emits "Bash"; treat it as not-our-shell-tool.
689        let p = Dialect::Gemini.parse(r#"{"tool_name":"Bash","tool_input":{"command":"ls"}}"#);
690        assert_eq!(p, Parsed::NotShell);
691    }
692
693    #[test]
694    fn copilot_parses_camelcase_toolargs() {
695        let p = Dialect::Copilot
696            .parse(r#"{"toolName":"bash","toolArgs":{"command":"sudo rm"},"sessionId":"s1"}"#);
697        match p {
698            Parsed::Shell(s) => {
699                assert_eq!(s.command, "sudo rm");
700                assert_eq!(s.session_id.as_deref(), Some("s1"));
701            }
702            other => panic!("expected shell, got {other:?}"),
703        }
704    }
705
706    #[test]
707    fn cursor_parses_flat_command() {
708        let p = Dialect::Cursor.parse(
709            r#"{"command":"git status","cwd":"/tmp","hook_event_name":"beforeShellExecution","conversation_id":"c1"}"#,
710        );
711        match p {
712            Parsed::Shell(s) => {
713                assert_eq!(s.command, "git status");
714                assert_eq!(s.cwd, PathBuf::from("/tmp"));
715                assert_eq!(s.session_id.as_deref(), Some("c1"));
716            }
717            other => panic!("expected shell, got {other:?}"),
718        }
719    }
720
721    #[test]
722    fn opencode_bridge_parses_flat_command() {
723        let p = Dialect::OpenCode.parse(r#"{"command":"dd if=/dev/zero","cwd":"/work"}"#);
724        assert_eq!(
725            p,
726            Parsed::Shell(Shell {
727                command: "dd if=/dev/zero".into(),
728                cwd: PathBuf::from("/work"),
729                session_id: None,
730            })
731        );
732    }
733
734    #[test]
735    fn bad_payload_is_bad_for_every_dialect() {
736        for d in [
737            Dialect::Claude,
738            Dialect::Qwen,
739            Dialect::Gemini,
740            Dialect::Copilot,
741            Dialect::Cursor,
742            Dialect::OpenCode,
743            Dialect::Codex,
744            Dialect::Antigravity,
745        ] {
746            assert!(matches!(d.parse("not json"), Parsed::Bad(_)), "{d:?}");
747        }
748    }
749
750    #[test]
751    fn claude_style_allow_is_silent_deny_is_json() {
752        assert_eq!(
753            Dialect::Claude.format(&Resolved::Allow),
754            HookOutcome::silent()
755        );
756        let out = Dialect::Claude.format(&Resolved::Deny("nope".into()));
757        let v: serde_json::Value = serde_json::from_str(&out.stdout.unwrap()).unwrap();
758        assert_eq!(v["hookSpecificOutput"]["permissionDecision"], "deny");
759        assert_eq!(v["hookSpecificOutput"]["permissionDecisionReason"], "nope");
760        assert_eq!(v["hookSpecificOutput"]["hookEventName"], "PreToolUse");
761    }
762
763    #[test]
764    fn qwen_ask_round_trips() {
765        let out = Dialect::Qwen.format(&Resolved::Ask("held".into()));
766        let v: serde_json::Value = serde_json::from_str(&out.stdout.unwrap()).unwrap();
767        assert_eq!(v["hookSpecificOutput"]["permissionDecision"], "ask");
768    }
769
770    #[test]
771    fn gemini_downgrades_ask_to_deny() {
772        let out = Dialect::Gemini.format(&Resolved::Ask("held".into()));
773        let v: serde_json::Value = serde_json::from_str(&out.stdout.unwrap()).unwrap();
774        assert_eq!(v["decision"], "deny", "gemini has no ask; must deny");
775    }
776
777    #[test]
778    fn copilot_flat_decision_shape() {
779        let out = Dialect::Copilot.format(&Resolved::Deny("x".into()));
780        let v: serde_json::Value = serde_json::from_str(&out.stdout.unwrap()).unwrap();
781        assert_eq!(v["permissionDecision"], "deny");
782        assert_eq!(v["permissionDecisionReason"], "x");
783    }
784
785    #[test]
786    fn cursor_allow_is_explicit_and_deny_has_both_message_cases() {
787        let allow = Dialect::Cursor.format(&Resolved::Allow);
788        let v: serde_json::Value = serde_json::from_str(&allow.stdout.unwrap()).unwrap();
789        assert_eq!(v["permission"], "allow");
790
791        let deny = Dialect::Cursor.format(&Resolved::Deny("bad".into()));
792        let v: serde_json::Value = serde_json::from_str(&deny.stdout.unwrap()).unwrap();
793        assert_eq!(v["permission"], "deny");
794        assert_eq!(v["agentMessage"], "bad");
795        assert_eq!(v["agent_message"], "bad");
796    }
797
798    #[test]
799    fn opencode_decision_shape() {
800        let out = Dialect::OpenCode.format(&Resolved::Ask("hold".into()));
801        let v: serde_json::Value = serde_json::from_str(&out.stdout.unwrap()).unwrap();
802        assert_eq!(v["decision"], "ask");
803        assert_eq!(v["reason"], "hold");
804    }
805
806    #[test]
807    fn cursor_pass_is_explicit_allow_others_silent() {
808        assert_eq!(
809            Dialect::Cursor.pass(),
810            format_cursor(&Resolved::Allow),
811            "cursor must answer its gate with an explicit allow"
812        );
813        assert_eq!(Dialect::Claude.pass(), HookOutcome::silent());
814        assert_eq!(Dialect::Gemini.pass(), HookOutcome::silent());
815    }
816
817    #[test]
818    fn resolve_maps_catastrophic_hold_to_deny() {
819        use kintsugi_core::Verdict;
820        let v = Verdict::rules(Class::Catastrophic, Decision::Hold, "boom");
821        assert_eq!(resolve(&v), Resolved::Deny("boom".into()));
822    }
823
824    #[test]
825    fn resolve_maps_ambiguous_hold_to_ask() {
826        use kintsugi_core::Verdict;
827        let v = Verdict::rules(Class::Ambiguous, Decision::Hold, "maybe");
828        assert_eq!(
829            resolve(&v),
830            Resolved::Ask(
831                "Kintsugi flagged this as ambiguous (rule: maybe). Approve only if you intended this."
832                    .into()
833            )
834        );
835    }
836
837    #[test]
838    fn ambiguous_ask_folds_in_the_model_summary() {
839        use kintsugi_core::Verdict;
840        let mut v = Verdict::rules(Class::Ambiguous, Decision::Hold, "ambiguous:cargo");
841        v.summary = Some("updates a dependency and runs its build script".into());
842        v.risk = Some(42);
843        let Resolved::Ask(msg) = resolve(&v) else {
844            panic!("expected ask")
845        };
846        assert!(msg.contains("Kintsugi flagged this"));
847        assert!(msg.contains("updates a dependency and runs its build script"));
848        assert!(msg.contains("risk 42/100"));
849    }
850}