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. Its file-write events
23//!   (`Write`/`StrReplace` pre-tool, `afterFileEdit`) are parsed by
24//!   [`Dialect::parse_write`] for provenance, on the explicit `--event write`
25//!   route.
26//! - OpenCode: no external-command hook — a bundled JS plugin bridges to us with
27//!   a simple `{command, cwd}` in / `{decision: allow|deny|ask, reason}` out, and
28//!   forwards write/edit calls as `{tool, args, session, cwd}` on
29//!   `--event write` ([`Dialect::parse_write`]).
30//! - Google Antigravity: plugin `PreToolUse` hook (matcher `run_command`).
31//!   `{toolCall:{name, arguments:{CommandLine, Cwd}}, conversationId}` in
32//!   (PascalCase argument keys); `{decision: allow|deny, reason}` out — no native
33//!   ask, so an ambiguous hold is mapped to deny.
34//!
35//! V1.1 adds a *post-tool* surface for the dialects that expose one (Claude,
36//! Codex, Antigravity): [`Dialect::parse_post`] normalizes a completed call's
37//! input + opaque result for result-content observation, and a *write* surface
38//! for Cursor and OpenCode ([`Dialect::parse_write`]) so a tainted session's
39//! file writes propagate taint to the path. Shapes are pinned to the fixture
40//! files in `tests/fixtures/` — never to docs alone.
41
42use std::path::PathBuf;
43
44use kintsugi_core::{Class, Decision, Verdict};
45use serde::Deserialize;
46
47/// Which agent CLI's hook protocol to speak.
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub enum Dialect {
50    Claude,
51    Qwen,
52    Gemini,
53    Copilot,
54    Cursor,
55    OpenCode,
56    Codex,
57    Antigravity,
58}
59
60/// A normalized shell command extracted from a hook payload.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct Shell {
63    pub command: String,
64    pub cwd: PathBuf,
65    pub session_id: Option<String>,
66}
67
68/// A non-shell, content-ingesting tool call surfaced for provenance observation
69/// (a `WebFetch`, `Read`, web-search, MCP call). The raw `input` object is handed
70/// to [`crate::observe::classify_tool_ingest`]; we never read the *result* bytes.
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct ContentCall {
73    pub tool: String,
74    pub input: serde_json::Value,
75    pub cwd: PathBuf,
76    pub session_id: Option<String>,
77}
78
79/// A completed tool call surfaced by a `PostToolUse`-style event, normalized for
80/// V1.1 *result-content* observation. `response` is the agent's (opaque) result
81/// payload — only its presence is ever consulted downstream; result bytes are
82/// never persisted or logged (spine #6). The source id for any taint comes from
83/// `input` (url / path / tool name), never from `response`.
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct PostToolCall {
86    pub tool: String,
87    pub input: serde_json::Value,
88    pub response: serde_json::Value,
89    pub cwd: PathBuf,
90    pub session_id: Option<String>,
91}
92
93/// A non-shell **file-write** tool call surfaced for provenance observation: a
94/// Cursor `Write` / `StrReplace` / `afterFileEdit`, or an OpenCode `write` /
95/// `edit`. The raw `input` object is handed to
96/// [`crate::observe::classify_tool_write`], which extracts the target path — the
97/// write *body* (a `content` field, or `old_string`/`new_string` pairs) is never
98/// read, persisted, or logged (spine #6).
99///
100/// The fields are deliberately the same normalized shape as [`ContentCall`]
101/// because both classifiers consume (tool, args, workspace); a distinct type
102/// keeps the ingest and write observation surfaces honest at the call site.
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub struct WriteCall {
105    pub tool: String,
106    pub input: serde_json::Value,
107    pub cwd: PathBuf,
108    pub session_id: Option<String>,
109}
110
111/// Result of parsing a hook payload.
112#[derive(Debug, PartialEq, Eq)]
113pub enum Parsed {
114    /// A shell command to send to the daemon.
115    Shell(Shell),
116    /// A well-formed payload that isn't a shell tool call — out of scope, pass.
117    NotShell,
118    /// An unparseable payload — fail open (never block on our own parse bug).
119    Bad(String),
120}
121
122/// The resolved, dialect-independent decision the daemon's verdict maps to.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub enum Resolved {
125    Allow,
126    Deny(String),
127    Ask(String),
128}
129
130/// What the adapter prints on stdout and exits with for one payload.
131#[derive(Debug, PartialEq, Eq)]
132pub struct HookOutcome {
133    pub stdout: Option<String>,
134    pub exit_code: i32,
135}
136
137impl HookOutcome {
138    /// Emit nothing, exit 0 — "Kintsugi has no opinion, use your default flow."
139    pub fn silent() -> Self {
140        Self {
141            stdout: None,
142            exit_code: 0,
143        }
144    }
145    fn json(value: serde_json::Value) -> Self {
146        Self {
147            stdout: Some(value.to_string()),
148            exit_code: 0,
149        }
150    }
151}
152
153impl Dialect {
154    /// Map an `--agent` value to a dialect. Accepts the CLI's stable id.
155    pub fn from_agent(s: &str) -> Option<Self> {
156        Some(match s {
157            "claude" | "claude-code" => Dialect::Claude,
158            "qwen" => Dialect::Qwen,
159            "gemini" => Dialect::Gemini,
160            "copilot" => Dialect::Copilot,
161            "cursor" => Dialect::Cursor,
162            "opencode" => Dialect::OpenCode,
163            "codex" => Dialect::Codex,
164            "antigravity" => Dialect::Antigravity,
165            _ => return None,
166        })
167    }
168
169    /// The `agent` tag stamped onto the [`kintsugi_core::ProposedCommand`] so the
170    /// log and TUI attribute the command to the right CLI.
171    pub fn agent_id(self) -> &'static str {
172        match self {
173            Dialect::Claude => "claude-code",
174            Dialect::Qwen => "qwen",
175            Dialect::Gemini => "gemini",
176            Dialect::Copilot => "copilot",
177            Dialect::Cursor => "cursor",
178            Dialect::OpenCode => "opencode",
179            Dialect::Codex => "codex",
180            Dialect::Antigravity => "antigravity",
181        }
182    }
183
184    /// Does this CLI have a native "ask the user" decision? If not, an ambiguous
185    /// hold is mapped to deny — safe per the monotonic-caution rule (the model
186    /// may only add caution, never remove it).
187    fn supports_ask(self) -> bool {
188        // Gemini's decision enum is allow/deny/block, and Antigravity's hook
189        // decision is allow/deny — neither has an interactive ask.
190        !matches!(self, Dialect::Gemini | Dialect::Antigravity)
191    }
192
193    /// Parse one CLI's hook payload into a normalized command.
194    pub fn parse(self, input: &str) -> Parsed {
195        match self {
196            Dialect::Claude | Dialect::Qwen | Dialect::Gemini | Dialect::Codex => {
197                self.parse_tool_style(input)
198            }
199            Dialect::Copilot => parse_copilot(input),
200            Dialect::Cursor | Dialect::OpenCode => parse_flat(input),
201            Dialect::Antigravity => parse_antigravity(input),
202        }
203    }
204
205    /// Extract a non-shell content-tool call for provenance observation, if this
206    /// payload is one. Tolerant: returns `None` (rather than erroring) for shell
207    /// tools, unparseable input, or dialects that only ever carry shell commands
208    /// (Cursor / OpenCode). Observation never blocks, so a miss is harmless.
209    pub fn parse_content(self, input: &str) -> Option<ContentCall> {
210        let v: serde_json::Value = serde_json::from_str(input).ok()?;
211        let get_str = |val: &serde_json::Value, k: &str| {
212            val.get(k).and_then(|s| s.as_str()).map(String::from)
213        };
214        let (tool, args, cwd, session) = match self {
215            Dialect::Claude | Dialect::Qwen | Dialect::Gemini | Dialect::Codex => (
216                get_str(&v, "tool_name")?,
217                v.get("tool_input")
218                    .cloned()
219                    .unwrap_or(serde_json::Value::Null),
220                get_str(&v, "cwd"),
221                get_str(&v, "session_id"),
222            ),
223            Dialect::Copilot => (
224                get_str(&v, "toolName")?,
225                v.get("toolArgs")
226                    .cloned()
227                    .unwrap_or(serde_json::Value::Null),
228                get_str(&v, "cwd"),
229                get_str(&v, "sessionId"),
230            ),
231            Dialect::Antigravity => {
232                let tc = v.get("toolCall")?;
233                let args = tc
234                    .get("arguments")
235                    .cloned()
236                    .unwrap_or(serde_json::Value::Null);
237                let cwd = args.get("Cwd").and_then(|s| s.as_str()).map(String::from);
238                (
239                    get_str(tc, "name")?,
240                    args,
241                    cwd,
242                    get_str(&v, "conversationId"),
243                )
244            }
245            // No *ingest* shape is pinned for these dialects: their hooks carry
246            // file writes, not content-tool results. Writes ride the explicit
247            // `--event write` route through [`parse_write`] instead, so nothing
248            // is guessed here (the 0.2.1 lesson).
249            Dialect::Cursor | Dialect::OpenCode => return None,
250        };
251        Some(ContentCall {
252            tool,
253            input: args,
254            cwd: cwd_or_current(cwd),
255            session_id: session,
256        })
257    }
258
259    /// Extract a file-write call from a payload delivered on the explicit
260    /// `--event write` route (the generated OpenCode plugin, or a Cursor write
261    /// matcher). Tolerant like [`parse_content`]: `None` for a non-write payload,
262    /// unparseable input, an unknown tool name, or a dialect with no pinned write
263    /// surface. Observation never blocks, so a miss is harmless.
264    ///
265    /// Every shape parsed here traces to a pinned fixture in `tests/fixtures/`:
266    /// Cursor `cursor-write.json`, `cursor-str-replace.json`,
267    /// `cursor-after-file-edit.json`; OpenCode `opencode-write-v1.json`,
268    /// `opencode-write-v2.json`. This is deliberately separate from
269    /// [`parse_content`]: that surface feeds the *ingest* classifier, and
270    /// emitting a call there for a Cursor payload would claim a Read/WebFetch arg
271    /// shape no fixture pins.
272    pub fn parse_write(self, input: &str) -> Option<WriteCall> {
273        let v: serde_json::Value = serde_json::from_str(input).ok()?;
274        let get_str = |val: &serde_json::Value, k: &str| {
275            val.get(k).and_then(|s| s.as_str()).map(String::from)
276        };
277        let (tool, args, cwd, session) = match self {
278            Dialect::Cursor => {
279                if let Some(tool) = get_str(&v, "tool_name") {
280                    // preToolUse write/edit (fixtures cursor-write.json,
281                    // cursor-str-replace.json). Cursor's exact content-tool name
282                    // set is a live-verification gap, so only the pinned names
283                    // are accepted — an unknown name is a miss, never a guess.
284                    if !matches!(tool.as_str(), "Write" | "StrReplace") {
285                        return None;
286                    }
287                    (
288                        tool,
289                        v.get("tool_input")
290                            .cloned()
291                            .unwrap_or(serde_json::Value::Null),
292                        get_str(&v, "cwd"),
293                        get_str(&v, "conversation_id"),
294                    )
295                } else {
296                    // afterFileEdit (fixture cursor-after-file-edit.json): no tool
297                    // identity, and the path sits at the top level. The whole
298                    // payload is handed over; the classifier reads only the path
299                    // key. No per-call cwd on this surface, so the documented
300                    // workspace root is the closest honest trust boundary.
301                    if get_str(&v, "hook_event_name").as_deref() != Some("afterFileEdit") {
302                        return None;
303                    }
304                    (
305                        "afterFileEdit".to_string(),
306                        v.clone(),
307                        v.get("workspace_roots")
308                            .and_then(|w| w.as_array())
309                            .and_then(|a| a.first())
310                            .and_then(|p| p.as_str())
311                            .map(String::from),
312                        get_str(&v, "conversation_id"),
313                    )
314                }
315            }
316            Dialect::OpenCode => {
317                if let Some(tool) = get_str(&v, "tool") {
318                    // The shape the generated plugin forwards (our own contract:
319                    // tool + args + session + cwd), and V2's raw event shape
320                    // `{tool, input}`. V2 documents no session field, so it stays
321                    // absent and the hook skips it rather than inventing one.
322                    (
323                        tool,
324                        v.get("args")
325                            .or_else(|| v.get("input"))
326                            .cloned()
327                            .unwrap_or(serde_json::Value::Null),
328                        get_str(&v, "cwd"),
329                        get_str(&v, "session").or_else(|| get_str(&v, "sessionID")),
330                    )
331                } else {
332                    // The raw V1 plugin callback (fixture opencode-write-v1.json):
333                    // input{tool, sessionID} + output{args}.
334                    let inner = v.get("input")?;
335                    (
336                        get_str(inner, "tool")?,
337                        v.get("output")
338                            .and_then(|o| o.get("args"))
339                            .cloned()
340                            .unwrap_or(serde_json::Value::Null),
341                        None,
342                        get_str(inner, "sessionID"),
343                    )
344                }
345            }
346            // No write surface is pinned for these dialects (Task 1 pinned Cursor
347            // and OpenCode only); report that honestly rather than guess.
348            Dialect::Claude
349            | Dialect::Qwen
350            | Dialect::Gemini
351            | Dialect::Copilot
352            | Dialect::Codex
353            | Dialect::Antigravity => return None,
354        };
355        Some(WriteCall {
356            tool,
357            input: args,
358            cwd: cwd_or_current(cwd),
359            session_id: session,
360        })
361    }
362
363    /// Extract a completed tool call from a `PostToolUse`-style payload, for
364    /// V1.1 *result-content* observation. Tolerant in the same way as
365    /// [`parse_content`]: returns `None` for unparseable input, missing
366    /// identity/response fields, or a dialect with no pinned post surface —
367    /// observation never blocks, so a miss is harmless. Every shape parsed
368    /// here traces to a pinned fixture in `tests/fixtures/` (the 0.2.1
369    /// lesson: never write to a documented-but-unverified shape).
370    ///
371    /// Divergence note (Antigravity): the documented post payload is camelCase
372    /// `toolCall.args`, which is what this parser reads — while the pre-tool
373    /// parser reads `toolCall.arguments`. At least one of the two is wrong for
374    /// the live wire; only a live CLI can say which. The pre-tool path is
375    /// deliberately left unchanged here; reconciliation rides on the
376    /// live-verification checkbox in the fixtures README.
377    pub fn parse_post(self, input: &str) -> Option<PostToolCall> {
378        let v: serde_json::Value = serde_json::from_str(input).ok()?;
379        let get_str = |val: &serde_json::Value, k: &str| {
380            val.get(k).and_then(|s| s.as_str()).map(String::from)
381        };
382        let (tool, args, response, cwd, session) = match self {
383            // Claude Code & Codex share the PostToolUse envelope:
384            // tool_name / tool_input / tool_response / cwd / session_id
385            // (fixtures: claude-post-tool-use.json, codex-post-tool-use.json).
386            // A post payload without a response is malformed — there is
387            // nothing to observe.
388            Dialect::Claude | Dialect::Codex => (
389                get_str(&v, "tool_name")?,
390                v.get("tool_input")
391                    .cloned()
392                    .unwrap_or(serde_json::Value::Null),
393                v.get("tool_response").cloned()?,
394                get_str(&v, "cwd"),
395                get_str(&v, "session_id"),
396            ),
397            // Antigravity's documented PostToolUse carries `toolCall{name,
398            // args}` and NO result bytes — its hook output is advisory-only, so
399            // the response is honestly null here and result-content
400            // classification for this dialect is act-confirmation at best
401            // (fixture: antigravity-post-tool.json).
402            Dialect::Antigravity => {
403                let tc = v.get("toolCall")?;
404                let args = tc.get("args").cloned().unwrap_or(serde_json::Value::Null);
405                // No per-call cwd on this surface; the session's workspace
406                // roots are the closest honest stand-in.
407                let cwd = v
408                    .get("workspacePaths")
409                    .and_then(|w| w.as_array())
410                    .and_then(|a| a.first())
411                    .and_then(|p| p.as_str())
412                    .map(String::from);
413                (
414                    get_str(tc, "name")?,
415                    args,
416                    serde_json::Value::Null,
417                    cwd,
418                    get_str(&v, "conversationId"),
419                )
420            }
421            // No pinned post fixture exists for these dialects (Qwen's
422            // PostToolUse is unpinned; Cursor/OpenCode write surfaces are
423            // Task 3; Copilot postToolUse has no tool_use_id — open upstream
424            // issue; Gemini uses a different AfterTool contract).
425            Dialect::Qwen
426            | Dialect::Gemini
427            | Dialect::Copilot
428            | Dialect::Cursor
429            | Dialect::OpenCode => return None,
430        };
431        Some(PostToolCall {
432            tool,
433            input: args,
434            response,
435            cwd: cwd_or_current(cwd),
436            session_id: session,
437        })
438    }
439
440    /// Claude/Qwen/Gemini share `{tool_name, tool_input:{command}}`.
441    fn parse_tool_style(self, input: &str) -> Parsed {
442        let p: ToolStyle = match serde_json::from_str(input) {
443            Ok(p) => p,
444            Err(e) => return Parsed::Bad(e.to_string()),
445        };
446        let tool = p.tool_name.as_deref().unwrap_or_default();
447        if !self.is_shell_tool(tool) {
448            return Parsed::NotShell;
449        }
450        match p.tool_input.and_then(|t| t.command) {
451            Some(c) if !c.trim().is_empty() => Parsed::Shell(Shell {
452                command: c,
453                cwd: cwd_or_current(p.cwd),
454                session_id: p.session_id,
455            }),
456            _ => Parsed::NotShell,
457        }
458    }
459
460    /// Is `name` this dialect's shell tool? The canonical name delivered in the
461    /// payload differs per CLI; we also accept the cross-CLI aliases so a
462    /// version that reports a different label still matches.
463    fn is_shell_tool(self, name: &str) -> bool {
464        match self {
465            // Claude reports Bash; accept the lowercase/Shell variants too.
466            Dialect::Claude => matches!(name, "Bash" | "Shell" | "bash" | "shell"),
467            // Qwen's canonical name is run_shell_command, with Claude-compat
468            // aliases Bash/Shell/ShellTool.
469            Dialect::Qwen => matches!(
470                name,
471                "run_shell_command" | "Bash" | "Shell" | "ShellTool" | "bash" | "shell"
472            ),
473            // Gemini only ever reports run_shell_command.
474            Dialect::Gemini => matches!(name, "run_shell_command" | "Shell" | "shell"),
475            // Codex modeled its hooks on Claude Code; its shell tool is Bash.
476            Dialect::Codex => matches!(name, "Bash" | "Shell" | "bash" | "shell"),
477            _ => false,
478        }
479    }
480
481    /// Serialize a resolved decision into this CLI's stdout protocol.
482    pub fn format(self, resolved: &Resolved) -> HookOutcome {
483        // Downgrade Ask -> Deny for dialects without a native ask.
484        let resolved = match (resolved, self.supports_ask()) {
485            (Resolved::Ask(reason), false) => &Resolved::Deny(reason.clone()),
486            (other, _) => other,
487        };
488        match self {
489            Dialect::Claude | Dialect::Qwen | Dialect::Codex => format_claude_style(resolved),
490            Dialect::Gemini => format_gemini(resolved),
491            Dialect::Copilot => format_copilot(resolved),
492            Dialect::Cursor => format_cursor(resolved),
493            Dialect::OpenCode => format_opencode(resolved),
494            Dialect::Antigravity => format_antigravity(resolved),
495        }
496    }
497
498    /// The "allow / no opinion" output used on the fail-open path and for SAFE
499    /// commands. Most CLIs treat empty output as "proceed normally"; Cursor's
500    /// beforeShellExecution gate is answered with an explicit allow.
501    pub fn pass(self) -> HookOutcome {
502        match self {
503            Dialect::Cursor => format_cursor(&Resolved::Allow),
504            // Antigravity's contract is "read a JSON decision object from stdout",
505            // so answer its gate with an explicit allow rather than silence.
506            Dialect::Antigravity => format_antigravity(&Resolved::Allow),
507            _ => HookOutcome::silent(),
508        }
509    }
510}
511
512/// The message Kintsugi surfaces through the agent's OWN approval prompt when it
513/// holds an ambiguous command. It names Kintsugi and the rule that fired, and
514/// folds in the local model's plain-English summary (and risk score) when the
515/// model scored the command — so the human decides with context, not a bare
516/// yes/no. The verbatim command is shown by the agent's prompt itself.
517fn flag_reason(verdict: &Verdict) -> String {
518    let mut msg = format!(
519        "Kintsugi flagged this as {} (rule: {})",
520        verdict.class, verdict.reason
521    );
522    if let Some(summary) = verdict.summary.as_deref().filter(|s| !s.is_empty()) {
523        msg.push_str(" — ");
524        msg.push_str(summary);
525    }
526    if let Some(risk) = verdict.risk {
527        msg.push_str(&format!(" [risk {risk}/100]"));
528    }
529    msg.push_str(". Approve only if you intended this.");
530    msg
531}
532
533/// Map a daemon verdict to the dialect-independent decision.
534///
535/// A catastrophic *hold* becomes a deny, not an ask: letting the CLI's own UI
536/// one-click "allow" it would run it with no Kintsugi snapshot, voiding the
537/// reversibility guarantee. Only ambiguous holds become an ask — and that ask
538/// carries Kintsugi's flag + the model's summary so the human understands it.
539pub fn resolve(verdict: &Verdict) -> Resolved {
540    match verdict.decision {
541        Decision::Allow => Resolved::Allow,
542        Decision::Deny => Resolved::Deny(verdict.reason.clone()),
543        Decision::Hold if verdict.class == Class::Catastrophic => {
544            Resolved::Deny(verdict.reason.clone())
545        }
546        Decision::Hold => Resolved::Ask(flag_reason(verdict)),
547    }
548}
549
550// ----- payload structs -------------------------------------------------------
551
552#[derive(Debug, Deserialize)]
553struct ToolStyle {
554    #[serde(default)]
555    cwd: Option<String>,
556    #[serde(default)]
557    session_id: Option<String>,
558    #[serde(default)]
559    tool_name: Option<String>,
560    #[serde(default)]
561    tool_input: Option<CmdInput>,
562}
563
564#[derive(Debug, Deserialize)]
565struct CmdInput {
566    #[serde(default)]
567    command: Option<String>,
568}
569
570#[derive(Debug, Deserialize)]
571struct CopilotStyle {
572    #[serde(default)]
573    cwd: Option<String>,
574    #[serde(default, rename = "sessionId")]
575    session_id: Option<String>,
576    #[serde(default, rename = "toolName")]
577    tool_name: Option<String>,
578    #[serde(default, rename = "toolArgs")]
579    tool_args: Option<CmdInput>,
580}
581
582#[derive(Debug, Deserialize)]
583struct FlatStyle {
584    #[serde(default)]
585    command: Option<String>,
586    #[serde(default)]
587    cwd: Option<String>,
588    #[serde(default)]
589    conversation_id: Option<String>,
590    #[serde(default)]
591    session_id: Option<String>,
592}
593
594fn parse_copilot(input: &str) -> Parsed {
595    let p: CopilotStyle = match serde_json::from_str(input) {
596        Ok(p) => p,
597        Err(e) => return Parsed::Bad(e.to_string()),
598    };
599    // Copilot's shell tool is named "bash" (and "powershell" on Windows).
600    let tool = p.tool_name.as_deref().unwrap_or_default();
601    if !matches!(tool, "bash" | "shell") {
602        return Parsed::NotShell;
603    }
604    match p.tool_args.and_then(|t| t.command) {
605        Some(c) if !c.trim().is_empty() => Parsed::Shell(Shell {
606            command: c,
607            cwd: cwd_or_current(p.cwd),
608            session_id: p.session_id,
609        }),
610        _ => Parsed::NotShell,
611    }
612}
613
614/// Antigravity's `PreToolUse` payload: the command lives in
615/// `toolCall.arguments.CommandLine` (PascalCase), the tool name in
616/// `toolCall.name`, and the session in `conversationId`.
617#[derive(Debug, Deserialize)]
618struct AntigravityStyle {
619    #[serde(default, rename = "toolCall")]
620    tool_call: Option<AntigravityToolCall>,
621    #[serde(default, rename = "conversationId")]
622    conversation_id: Option<String>,
623}
624
625#[derive(Debug, Deserialize)]
626struct AntigravityToolCall {
627    #[serde(default)]
628    name: Option<String>,
629    /// The shape the gate documents.
630    #[serde(default)]
631    arguments: Option<AntigravityArgs>,
632    /// The shape the post-tool surface documents (`toolCall.args`). Both are
633    /// accepted because a mismatch here means the gate parses no command and
634    /// silently allows every `run_command` — a catastrophic-classified-as-safe
635    /// outcome. Widening the parser can only add classification.
636    #[serde(default)]
637    args: Option<AntigravityArgs>,
638}
639
640#[derive(Debug, Deserialize)]
641struct AntigravityArgs {
642    #[serde(default, rename = "CommandLine")]
643    command_line: Option<String>,
644    #[serde(default, rename = "Cwd")]
645    cwd: Option<String>,
646}
647
648fn parse_antigravity(input: &str) -> Parsed {
649    let p: AntigravityStyle = match serde_json::from_str(input) {
650        Ok(p) => p,
651        Err(e) => return Parsed::Bad(e.to_string()),
652    };
653    let Some(tc) = p.tool_call else {
654        return Parsed::NotShell;
655    };
656    // Antigravity's shell tool is `run_command`; accept the common aliases too.
657    let tool = tc.name.as_deref().unwrap_or_default();
658    if !matches!(
659        tool,
660        "run_command" | "run_shell_command" | "Bash" | "bash" | "shell"
661    ) {
662        return Parsed::NotShell;
663    }
664    let Some(args) = tc.arguments.or(tc.args) else {
665        return Parsed::NotShell;
666    };
667    match args.command_line {
668        Some(c) if !c.trim().is_empty() => Parsed::Shell(Shell {
669            command: c,
670            cwd: cwd_or_current(args.cwd),
671            session_id: p.conversation_id,
672        }),
673        _ => Parsed::NotShell,
674    }
675}
676
677fn parse_flat(input: &str) -> Parsed {
678    let p: FlatStyle = match serde_json::from_str(input) {
679        Ok(p) => p,
680        Err(e) => return Parsed::Bad(e.to_string()),
681    };
682    match p.command {
683        Some(c) if !c.trim().is_empty() => Parsed::Shell(Shell {
684            command: c,
685            cwd: cwd_or_current(p.cwd),
686            session_id: p.session_id.or(p.conversation_id),
687        }),
688        _ => Parsed::NotShell,
689    }
690}
691
692fn cwd_or_current(cwd: Option<String>) -> PathBuf {
693    cwd.filter(|s| !s.is_empty())
694        .map(PathBuf::from)
695        .unwrap_or_else(|| std::env::current_dir().unwrap_or_default())
696}
697
698// ----- output formats --------------------------------------------------------
699
700/// Claude Code & Qwen Code: `hookSpecificOutput.permissionDecision`.
701fn format_claude_style(resolved: &Resolved) -> HookOutcome {
702    let (decision, reason) = match resolved {
703        Resolved::Allow => return HookOutcome::silent(),
704        Resolved::Deny(r) => ("deny", r),
705        Resolved::Ask(r) => ("ask", r),
706    };
707    HookOutcome::json(serde_json::json!({
708        "hookSpecificOutput": {
709            "hookEventName": "PreToolUse",
710            "permissionDecision": decision,
711            "permissionDecisionReason": reason,
712        }
713    }))
714}
715
716/// Gemini CLI: `{decision: allow|deny, reason}` (no ask — already downgraded).
717fn format_gemini(resolved: &Resolved) -> HookOutcome {
718    match resolved {
719        Resolved::Allow => HookOutcome::silent(),
720        Resolved::Deny(r) => HookOutcome::json(serde_json::json!({
721            "decision": "deny",
722            "reason": r,
723            "systemMessage": format!("Kintsugi: {r}"),
724        })),
725        // Unreachable: Gemini doesn't support ask, so resolve→format downgrades
726        // it to Deny before we get here. Treat defensively as a deny.
727        Resolved::Ask(r) => HookOutcome::json(serde_json::json!({
728            "decision": "deny",
729            "reason": r,
730        })),
731    }
732}
733
734/// GitHub Copilot CLI: flat `{permissionDecision, permissionDecisionReason}`.
735fn format_copilot(resolved: &Resolved) -> HookOutcome {
736    let (decision, reason) = match resolved {
737        Resolved::Allow => return HookOutcome::silent(),
738        Resolved::Deny(r) => ("deny", r),
739        Resolved::Ask(r) => ("ask", r),
740    };
741    HookOutcome::json(serde_json::json!({
742        "permissionDecision": decision,
743        "permissionDecisionReason": reason,
744    }))
745}
746
747/// Cursor CLI: `{permission, userMessage, agentMessage}`. We emit both camelCase
748/// and snake_case message keys because Cursor's docs are inconsistent across
749/// versions about which it reads; `permission` is the only load-bearing field.
750fn format_cursor(resolved: &Resolved) -> HookOutcome {
751    let (permission, reason) = match resolved {
752        Resolved::Allow => ("allow", None),
753        Resolved::Deny(r) => ("deny", Some(r)),
754        Resolved::Ask(r) => ("ask", Some(r)),
755    };
756    let mut obj = serde_json::json!({ "permission": permission });
757    if let Some(r) = reason {
758        let map = obj.as_object_mut().unwrap();
759        map.insert(
760            "userMessage".into(),
761            serde_json::json!(format!("Kintsugi: {r}")),
762        );
763        map.insert("agentMessage".into(), serde_json::json!(r));
764        map.insert(
765            "user_message".into(),
766            serde_json::json!(format!("Kintsugi: {r}")),
767        );
768        map.insert("agent_message".into(), serde_json::json!(r));
769    }
770    HookOutcome::json(obj)
771}
772
773/// OpenCode bridge: `{decision: allow|deny|ask, reason}`. The bundled JS plugin
774/// reads this and throws (aborting the tool call) on deny/ask.
775fn format_opencode(resolved: &Resolved) -> HookOutcome {
776    let (decision, reason) = match resolved {
777        Resolved::Allow => ("allow", String::new()),
778        Resolved::Deny(r) => ("deny", r.clone()),
779        Resolved::Ask(r) => ("ask", r.clone()),
780    };
781    HookOutcome::json(serde_json::json!({ "decision": decision, "reason": reason }))
782}
783
784/// Google Antigravity: `{decision: allow|deny, reason}` (no ask — already
785/// downgraded). Allow is explicit (its contract expects a decision object).
786fn format_antigravity(resolved: &Resolved) -> HookOutcome {
787    let (decision, reason) = match resolved {
788        Resolved::Allow => ("allow", None),
789        Resolved::Deny(r) => ("deny", Some(r)),
790        // Unreachable: Antigravity has no ask, so resolve→format downgrades it to
791        // Deny before we get here. Treat defensively as a deny.
792        Resolved::Ask(r) => ("deny", Some(r)),
793    };
794    let mut obj = serde_json::json!({ "decision": decision });
795    if let Some(r) = reason {
796        let map = obj.as_object_mut().unwrap();
797        map.insert("reason".into(), serde_json::json!(r));
798        map.insert(
799            "systemMessage".into(),
800            serde_json::json!(format!("Kintsugi: {r}")),
801        );
802    }
803    HookOutcome::json(obj)
804}
805
806#[cfg(test)]
807mod tests {
808    use super::*;
809
810    fn shell(cmd: &str) -> Parsed {
811        Parsed::Shell(Shell {
812            command: cmd.into(),
813            cwd: std::env::current_dir().unwrap_or_default(),
814            session_id: None,
815        })
816    }
817
818    #[test]
819    fn from_agent_accepts_known_ids() {
820        assert_eq!(Dialect::from_agent("claude"), Some(Dialect::Claude));
821        assert_eq!(Dialect::from_agent("claude-code"), Some(Dialect::Claude));
822        assert_eq!(Dialect::from_agent("qwen"), Some(Dialect::Qwen));
823        assert_eq!(Dialect::from_agent("gemini"), Some(Dialect::Gemini));
824        assert_eq!(Dialect::from_agent("copilot"), Some(Dialect::Copilot));
825        assert_eq!(Dialect::from_agent("cursor"), Some(Dialect::Cursor));
826        assert_eq!(Dialect::from_agent("opencode"), Some(Dialect::OpenCode));
827        assert_eq!(Dialect::from_agent("codex"), Some(Dialect::Codex));
828        assert_eq!(
829            Dialect::from_agent("antigravity"),
830            Some(Dialect::Antigravity)
831        );
832        assert_eq!(Dialect::from_agent("nope"), None);
833    }
834
835    #[test]
836    fn antigravity_parses_run_command_with_pascalcase_args() {
837        let p = Dialect::Antigravity.parse(
838            r#"{"toolCall":{"name":"run_command","arguments":{"CommandLine":"rm -rf /","Cwd":"/work"}},"conversationId":"c9"}"#,
839        );
840        match p {
841            Parsed::Shell(s) => {
842                assert_eq!(s.command, "rm -rf /");
843                assert_eq!(s.cwd, PathBuf::from("/work"));
844                assert_eq!(s.session_id.as_deref(), Some("c9"));
845            }
846            other => panic!("expected shell, got {other:?}"),
847        }
848    }
849
850    #[test]
851    fn antigravity_non_shell_tool_is_not_shell() {
852        let p = Dialect::Antigravity
853            .parse(r#"{"toolCall":{"name":"write_file","arguments":{"Path":"x"}}}"#);
854        assert_eq!(p, Parsed::NotShell);
855    }
856
857    #[test]
858    fn antigravity_denies_and_downgrades_ask_to_deny() {
859        // Deny carries a decision + reason.
860        let out = Dialect::Antigravity.format(&Resolved::Deny("boom".into()));
861        let v: serde_json::Value = serde_json::from_str(&out.stdout.unwrap()).unwrap();
862        assert_eq!(v["decision"], "deny");
863        assert_eq!(v["reason"], "boom");
864        // No native ask → a hold becomes deny.
865        let out = Dialect::Antigravity.format(&Resolved::Ask("held".into()));
866        let v: serde_json::Value = serde_json::from_str(&out.stdout.unwrap()).unwrap();
867        assert_eq!(v["decision"], "deny", "antigravity has no ask; must deny");
868    }
869
870    #[test]
871    fn antigravity_allow_and_pass_are_explicit() {
872        let allow = Dialect::Antigravity.format(&Resolved::Allow);
873        let v: serde_json::Value = serde_json::from_str(&allow.stdout.unwrap()).unwrap();
874        assert_eq!(v["decision"], "allow");
875        assert_eq!(
876            Dialect::Antigravity.pass(),
877            format_antigravity(&Resolved::Allow),
878            "antigravity must answer its gate with an explicit allow"
879        );
880    }
881
882    #[test]
883    fn codex_parses_bash_and_formats_claude_style() {
884        let p = Dialect::Codex.parse(r#"{"tool_name":"Bash","tool_input":{"command":"rm -rf /"}}"#);
885        assert_eq!(p, shell("rm -rf /"));
886        let out = Dialect::Codex.format(&Resolved::Deny("boom".into()));
887        let v: serde_json::Value = serde_json::from_str(&out.stdout.unwrap()).unwrap();
888        assert_eq!(v["hookSpecificOutput"]["permissionDecision"], "deny");
889    }
890
891    #[test]
892    fn claude_parses_bash_command() {
893        let p = Dialect::Claude.parse(r#"{"tool_name":"Bash","tool_input":{"command":"ls"}}"#);
894        match p {
895            Parsed::Shell(s) => assert_eq!(s.command, "ls"),
896            other => panic!("expected shell, got {other:?}"),
897        }
898    }
899
900    #[test]
901    fn claude_non_shell_tool_is_not_shell() {
902        let p = Dialect::Claude.parse(r#"{"tool_name":"Edit","tool_input":{"file_path":"x"}}"#);
903        assert_eq!(p, Parsed::NotShell);
904    }
905
906    #[test]
907    fn qwen_parses_run_shell_command_canonical_name() {
908        let p = Dialect::Qwen
909            .parse(r#"{"tool_name":"run_shell_command","tool_input":{"command":"rm -rf x"}}"#);
910        assert_eq!(p, shell("rm -rf x"));
911    }
912
913    #[test]
914    fn gemini_parses_run_shell_command() {
915        let p = Dialect::Gemini
916            .parse(r#"{"tool_name":"run_shell_command","tool_input":{"command":"git push"}}"#);
917        assert_eq!(p, shell("git push"));
918    }
919
920    #[test]
921    fn gemini_ignores_bash_alias() {
922        // Gemini never emits "Bash"; treat it as not-our-shell-tool.
923        let p = Dialect::Gemini.parse(r#"{"tool_name":"Bash","tool_input":{"command":"ls"}}"#);
924        assert_eq!(p, Parsed::NotShell);
925    }
926
927    #[test]
928    fn copilot_parses_camelcase_toolargs() {
929        let p = Dialect::Copilot
930            .parse(r#"{"toolName":"bash","toolArgs":{"command":"sudo rm"},"sessionId":"s1"}"#);
931        match p {
932            Parsed::Shell(s) => {
933                assert_eq!(s.command, "sudo rm");
934                assert_eq!(s.session_id.as_deref(), Some("s1"));
935            }
936            other => panic!("expected shell, got {other:?}"),
937        }
938    }
939
940    #[test]
941    fn cursor_parses_flat_command() {
942        let p = Dialect::Cursor.parse(
943            r#"{"command":"git status","cwd":"/tmp","hook_event_name":"beforeShellExecution","conversation_id":"c1"}"#,
944        );
945        match p {
946            Parsed::Shell(s) => {
947                assert_eq!(s.command, "git status");
948                assert_eq!(s.cwd, PathBuf::from("/tmp"));
949                assert_eq!(s.session_id.as_deref(), Some("c1"));
950            }
951            other => panic!("expected shell, got {other:?}"),
952        }
953    }
954
955    #[test]
956    fn opencode_bridge_parses_flat_command() {
957        let p = Dialect::OpenCode.parse(r#"{"command":"dd if=/dev/zero","cwd":"/work"}"#);
958        assert_eq!(
959            p,
960            Parsed::Shell(Shell {
961                command: "dd if=/dev/zero".into(),
962                cwd: PathBuf::from("/work"),
963                session_id: None,
964            })
965        );
966    }
967
968    #[test]
969    fn bad_payload_is_bad_for_every_dialect() {
970        for d in [
971            Dialect::Claude,
972            Dialect::Qwen,
973            Dialect::Gemini,
974            Dialect::Copilot,
975            Dialect::Cursor,
976            Dialect::OpenCode,
977            Dialect::Codex,
978            Dialect::Antigravity,
979        ] {
980            assert!(matches!(d.parse("not json"), Parsed::Bad(_)), "{d:?}");
981        }
982    }
983
984    #[test]
985    fn claude_style_allow_is_silent_deny_is_json() {
986        assert_eq!(
987            Dialect::Claude.format(&Resolved::Allow),
988            HookOutcome::silent()
989        );
990        let out = Dialect::Claude.format(&Resolved::Deny("nope".into()));
991        let v: serde_json::Value = serde_json::from_str(&out.stdout.unwrap()).unwrap();
992        assert_eq!(v["hookSpecificOutput"]["permissionDecision"], "deny");
993        assert_eq!(v["hookSpecificOutput"]["permissionDecisionReason"], "nope");
994        assert_eq!(v["hookSpecificOutput"]["hookEventName"], "PreToolUse");
995    }
996
997    #[test]
998    fn qwen_ask_round_trips() {
999        let out = Dialect::Qwen.format(&Resolved::Ask("held".into()));
1000        let v: serde_json::Value = serde_json::from_str(&out.stdout.unwrap()).unwrap();
1001        assert_eq!(v["hookSpecificOutput"]["permissionDecision"], "ask");
1002    }
1003
1004    #[test]
1005    fn gemini_downgrades_ask_to_deny() {
1006        let out = Dialect::Gemini.format(&Resolved::Ask("held".into()));
1007        let v: serde_json::Value = serde_json::from_str(&out.stdout.unwrap()).unwrap();
1008        assert_eq!(v["decision"], "deny", "gemini has no ask; must deny");
1009    }
1010
1011    #[test]
1012    fn copilot_flat_decision_shape() {
1013        let out = Dialect::Copilot.format(&Resolved::Deny("x".into()));
1014        let v: serde_json::Value = serde_json::from_str(&out.stdout.unwrap()).unwrap();
1015        assert_eq!(v["permissionDecision"], "deny");
1016        assert_eq!(v["permissionDecisionReason"], "x");
1017    }
1018
1019    #[test]
1020    fn cursor_allow_is_explicit_and_deny_has_both_message_cases() {
1021        let allow = Dialect::Cursor.format(&Resolved::Allow);
1022        let v: serde_json::Value = serde_json::from_str(&allow.stdout.unwrap()).unwrap();
1023        assert_eq!(v["permission"], "allow");
1024
1025        let deny = Dialect::Cursor.format(&Resolved::Deny("bad".into()));
1026        let v: serde_json::Value = serde_json::from_str(&deny.stdout.unwrap()).unwrap();
1027        assert_eq!(v["permission"], "deny");
1028        assert_eq!(v["agentMessage"], "bad");
1029        assert_eq!(v["agent_message"], "bad");
1030    }
1031
1032    #[test]
1033    fn opencode_decision_shape() {
1034        let out = Dialect::OpenCode.format(&Resolved::Ask("hold".into()));
1035        let v: serde_json::Value = serde_json::from_str(&out.stdout.unwrap()).unwrap();
1036        assert_eq!(v["decision"], "ask");
1037        assert_eq!(v["reason"], "hold");
1038    }
1039
1040    #[test]
1041    fn cursor_pass_is_explicit_allow_others_silent() {
1042        assert_eq!(
1043            Dialect::Cursor.pass(),
1044            format_cursor(&Resolved::Allow),
1045            "cursor must answer its gate with an explicit allow"
1046        );
1047        assert_eq!(Dialect::Claude.pass(), HookOutcome::silent());
1048        assert_eq!(Dialect::Gemini.pass(), HookOutcome::silent());
1049    }
1050
1051    #[test]
1052    fn resolve_maps_catastrophic_hold_to_deny() {
1053        use kintsugi_core::Verdict;
1054        let v = Verdict::rules(Class::Catastrophic, Decision::Hold, "boom");
1055        assert_eq!(resolve(&v), Resolved::Deny("boom".into()));
1056    }
1057
1058    #[test]
1059    fn resolve_maps_ambiguous_hold_to_ask() {
1060        use kintsugi_core::Verdict;
1061        let v = Verdict::rules(Class::Ambiguous, Decision::Hold, "maybe");
1062        assert_eq!(
1063            resolve(&v),
1064            Resolved::Ask(
1065                "Kintsugi flagged this as ambiguous (rule: maybe). Approve only if you intended this."
1066                    .into()
1067            )
1068        );
1069    }
1070
1071    #[test]
1072    fn ambiguous_ask_folds_in_the_model_summary() {
1073        use kintsugi_core::Verdict;
1074        let mut v = Verdict::rules(Class::Ambiguous, Decision::Hold, "ambiguous:cargo");
1075        v.summary = Some("updates a dependency and runs its build script".into());
1076        v.risk = Some(42);
1077        let Resolved::Ask(msg) = resolve(&v) else {
1078            panic!("expected ask")
1079        };
1080        assert!(msg.contains("Kintsugi flagged this"));
1081        assert!(msg.contains("updates a dependency and runs its build script"));
1082        assert!(msg.contains("risk 42/100"));
1083    }
1084
1085    // ----- PostToolUse result observation (V1.1) ------------------------------
1086    // Every post-tool parse must trace to a pinned fixture in tests/fixtures/
1087    // (the 0.2.1 lesson: adapters written to documented shapes, never
1088    // round-trip-verified). No inline duplication of the pinned shapes: the
1089    // files on disk are the contract.
1090
1091    fn fixture_text(name: &str) -> String {
1092        std::fs::read_to_string(
1093            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1094                .join("tests/fixtures")
1095                .join(name),
1096        )
1097        .unwrap_or_else(|e| panic!("fixture {name}: {e}"))
1098    }
1099
1100    /// A programmatic mutation of a pinned fixture (single source of truth:
1101    /// the file on disk), for the adversarial variants.
1102    fn mutated_fixture(name: &str, edit: impl FnOnce(&mut serde_json::Value)) -> String {
1103        let mut v: serde_json::Value =
1104            serde_json::from_str(&fixture_text(name)).unwrap_or_else(|e| panic!("{e}"));
1105        edit(&mut v);
1106        v.to_string()
1107    }
1108
1109    #[test]
1110    fn all_pinned_fixture_files_are_valid_json() {
1111        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
1112        let mut checked = 0;
1113        for entry in std::fs::read_dir(&dir).unwrap() {
1114            let path = entry.unwrap().path();
1115            if path.extension().and_then(|e| e.to_str()) == Some("json") {
1116                let text = std::fs::read_to_string(&path).unwrap();
1117                serde_json::from_str::<serde_json::Value>(&text)
1118                    .unwrap_or_else(|e| panic!("{}: {e}", path.display()));
1119                checked += 1;
1120            }
1121        }
1122        assert!(
1123            checked >= 8,
1124            "expected the pinned V1.1 fixture set, found {checked}"
1125        );
1126    }
1127
1128    #[test]
1129    fn claude_post_tool_fixture_parses() {
1130        let call = Dialect::Claude
1131            .parse_post(&fixture_text("claude-post-tool-use.json"))
1132            .expect("pinned claude post fixture must round-trip");
1133        assert_eq!(call.tool, "WebFetch");
1134        assert_eq!(call.input["url"], "https://example.com/advisory");
1135        // The response rides along opaquely — parsed, never interpreted here.
1136        assert!(call.response.is_string());
1137        assert_eq!(call.cwd, PathBuf::from("/work/repo"));
1138        assert_eq!(
1139            call.session_id.as_deref(),
1140            Some("e3f8a1c2-7b49-4d62-9a15-6c2d8e4f9b01")
1141        );
1142    }
1143
1144    #[test]
1145    fn codex_post_tool_fixture_parses() {
1146        let call = Dialect::Codex
1147            .parse_post(&fixture_text("codex-post-tool-use.json"))
1148            .expect("pinned codex post fixture must round-trip");
1149        assert_eq!(call.tool, "mcp__webdocs__fetch_page");
1150        assert_eq!(call.input["url"], "https://example.com/advisory");
1151        assert!(call.response.is_string());
1152        assert_eq!(call.cwd, PathBuf::from("/work/repo"));
1153        assert_eq!(
1154            call.session_id.as_deref(),
1155            Some("b1e5d0a2-3f47-4c98-9d62-1a7b8c5e2f30")
1156        );
1157    }
1158
1159    #[test]
1160    fn antigravity_post_tool_fixture_parses_the_documented_args_shape() {
1161        let call = Dialect::Antigravity
1162            .parse_post(&fixture_text("antigravity-post-tool.json"))
1163            .expect("pinned antigravity post fixture must round-trip");
1164        assert_eq!(call.tool, "read_url_content");
1165        // The DOCUMENTED `toolCall.args` shape. Divergence note: the pre-tool
1166        // Antigravity parser reads `toolCall.arguments` — at least one of the
1167        // two is wrong for the live wire, and only a live CLI can say which
1168        // (open checkbox in the fixtures README). The pre-tool path is left
1169        // unchanged by this task; reconciliation rides on that checkbox.
1170        assert_eq!(call.input["Url"], "https://example.com/advisory");
1171        // No result bytes exist on this surface (its output is advisory-only
1172        // `{}`), so the response is honestly null — never invented content.
1173        assert_eq!(call.response, serde_json::Value::Null);
1174        assert_eq!(call.cwd, PathBuf::from("/work/repo"));
1175        assert_eq!(
1176            call.session_id.as_deref(),
1177            Some("ec33ebf9-0cba-4100-8142-c61503f6c587")
1178        );
1179    }
1180
1181    #[test]
1182    fn post_tool_malformed_variants_parse_to_none() {
1183        // Truncated JSON — an adversarial variant of every pinned fixture
1184        // (char-safe halving: fixtures contain multi-byte characters).
1185        for (dialect, name) in [
1186            (Dialect::Claude, "claude-post-tool-use.json"),
1187            (Dialect::Codex, "codex-post-tool-use.json"),
1188            (Dialect::Antigravity, "antigravity-post-tool.json"),
1189        ] {
1190            let text = fixture_text(name);
1191            let truncated: String = text.chars().take(text.chars().count() / 2).collect();
1192            assert_eq!(dialect.parse_post(&truncated), None, "truncated {name}");
1193        }
1194
1195        // Missing tool identity.
1196        let no_tool = mutated_fixture("claude-post-tool-use.json", |v| {
1197            v.as_object_mut().unwrap().remove("tool_name");
1198        });
1199        assert_eq!(Dialect::Claude.parse_post(&no_tool), None);
1200
1201        // Missing response (the plan's malformed case): a post payload with
1202        // no result to observe is malformed, not a silent success.
1203        for dialect in [Dialect::Claude, Dialect::Codex] {
1204            let name = if dialect == Dialect::Claude {
1205                "claude-post-tool-use.json"
1206            } else {
1207                "codex-post-tool-use.json"
1208            };
1209            let no_response = mutated_fixture(name, |v| {
1210                v.as_object_mut().unwrap().remove("tool_response");
1211            });
1212            assert_eq!(dialect.parse_post(&no_response), None, "{dialect:?}");
1213        }
1214
1215        // Missing toolCall (Antigravity).
1216        let no_tc = mutated_fixture("antigravity-post-tool.json", |v| {
1217            v.as_object_mut().unwrap().remove("toolCall");
1218        });
1219        assert_eq!(Dialect::Antigravity.parse_post(&no_tc), None);
1220
1221        // Wrong types.
1222        let bad_type = mutated_fixture("claude-post-tool-use.json", |v| {
1223            v["tool_name"] = serde_json::json!(7);
1224        });
1225        assert_eq!(Dialect::Claude.parse_post(&bad_type), None);
1226        let bad_type = mutated_fixture("antigravity-post-tool.json", |v| {
1227            v["toolCall"] = serde_json::json!("not-an-object");
1228        });
1229        assert_eq!(Dialect::Antigravity.parse_post(&bad_type), None);
1230    }
1231
1232    #[test]
1233    fn an_explicitly_null_post_response_parses_but_carries_no_content() {
1234        // Present-but-null is NOT malformed (absent vs null are different
1235        // states on the wire); it just observes nothing, per the classifier.
1236        let null_response = mutated_fixture("claude-post-tool-use.json", |v| {
1237            v["tool_response"] = serde_json::Value::Null;
1238        });
1239        assert!(Dialect::Claude.parse_post(&null_response).is_some());
1240    }
1241
1242    // ----- File-write observation (V1.1 Task 3) -------------------------------
1243    // Every write parse must trace to a pinned fixture in tests/fixtures/ (the
1244    // cursor-write / cursor-str-replace / cursor-after-file-edit /
1245    // opencode-write-v1 / opencode-write-v2 files). No inline shapes.
1246
1247    #[test]
1248    fn cursor_write_fixture_normalizes_to_a_write_call() {
1249        let call = Dialect::Cursor
1250            .parse_write(&fixture_text("cursor-write.json"))
1251            .expect("pinned cursor Write fixture must parse");
1252        assert_eq!(call.tool, "Write");
1253        assert_eq!(call.input["file_path"], "/work/repo/src/notes.rs");
1254        // The per-call cwd is the trust boundary the classifier resolves against.
1255        assert_eq!(call.cwd, PathBuf::from("/work/repo"));
1256        assert_eq!(call.session_id.as_deref(), Some("conv-4d2f9a1c"));
1257    }
1258
1259    #[test]
1260    fn cursor_str_replace_fixture_normalizes_to_a_write_call() {
1261        let call = Dialect::Cursor
1262            .parse_write(&fixture_text("cursor-str-replace.json"))
1263            .expect("pinned cursor StrReplace fixture must parse");
1264        assert_eq!(call.tool, "StrReplace");
1265        assert_eq!(call.input["file_path"], "/work/repo/src/lib.rs");
1266        assert_eq!(call.session_id.as_deref(), Some("conv-4d2f9a1c"));
1267    }
1268
1269    #[test]
1270    fn cursor_after_file_edit_fixture_normalizes_to_a_write_call() {
1271        let call = Dialect::Cursor
1272            .parse_write(&fixture_text("cursor-after-file-edit.json"))
1273            .expect("pinned cursor afterFileEdit fixture must parse");
1274        // No tool identity on this event; the event name is the honest label.
1275        assert_eq!(call.tool, "afterFileEdit");
1276        // The path is top-level on this surface (pinned shape).
1277        assert_eq!(call.input["file_path"], "/work/repo/src/notes.rs");
1278        // No `cwd` field: the documented workspace root is the closest honest root.
1279        assert_eq!(call.cwd, PathBuf::from("/work/repo"));
1280        assert_eq!(call.session_id.as_deref(), Some("conv-4d2f9a1c"));
1281    }
1282
1283    #[test]
1284    fn opencode_v1_write_fixture_normalizes_with_its_session() {
1285        // The pinned V1 plugin callback shape: input{tool, sessionID} + output{args}.
1286        let call = Dialect::OpenCode
1287            .parse_write(&fixture_text("opencode-write-v1.json"))
1288            .expect("pinned opencode V1 write fixture must parse");
1289        assert_eq!(call.tool, "write");
1290        assert_eq!(call.input["filePath"], "/work/repo/src/notes.rs");
1291        assert_eq!(call.session_id.as_deref(), Some("ses_9f2a41"));
1292    }
1293
1294    #[test]
1295    fn opencode_v2_write_fixture_parses_but_carries_no_session() {
1296        // V2's documented before-event has `tool` + `input` and NO session field.
1297        // We parse the shape honestly and leave the session absent: the hook then
1298        // skips the observation (sessionless by design) rather than inventing an
1299        // identifier. Tracked as a live-verification gap in the fixtures README.
1300        let call = Dialect::OpenCode
1301            .parse_write(&fixture_text("opencode-write-v2.json"))
1302            .expect("pinned opencode V2 write fixture must parse");
1303        assert_eq!(call.tool, "write");
1304        assert_eq!(call.input["filePath"], "/work/repo/src/notes.rs");
1305        assert_eq!(call.session_id, None, "V2 documents no session field");
1306    }
1307
1308    #[test]
1309    fn the_generated_opencode_bridge_shape_normalizes() {
1310        // What the generated plugin forwards on `--event write` (our own contract,
1311        // pinned by the init.rs unit test): tool + args + session + cwd.
1312        let payload = r#"{
1313            "tool": "write",
1314            "args": { "filePath": "/work/repo/src/notes.rs" },
1315            "session": "ses_9f2a41",
1316            "cwd": "/work/repo"
1317        }"#;
1318        let call = Dialect::OpenCode
1319            .parse_write(payload)
1320            .expect("bridge shape");
1321        assert_eq!(call.tool, "write");
1322        assert_eq!(call.input["filePath"], "/work/repo/src/notes.rs");
1323        assert_eq!(call.cwd, PathBuf::from("/work/repo"));
1324        assert_eq!(call.session_id.as_deref(), Some("ses_9f2a41"));
1325    }
1326
1327    #[test]
1328    fn shell_payloads_are_never_mistaken_for_writes() {
1329        // The flat `{command, cwd}` contract both dialects already speak is
1330        // untouched: it carries no write identity, so the write route declines it.
1331        let cursor_shell = r#"{"command":"git status","cwd":"/tmp","hook_event_name":"beforeShellExecution","conversation_id":"c1"}"#;
1332        assert_eq!(Dialect::Cursor.parse_write(cursor_shell), None);
1333        let opencode_shell = r#"{"command":"dd if=/dev/zero","cwd":"/work"}"#;
1334        assert_eq!(Dialect::OpenCode.parse_write(opencode_shell), None);
1335        // …and their PRE-tool shell parsing still works exactly as before.
1336        assert!(matches!(
1337            Dialect::Cursor.parse(cursor_shell),
1338            Parsed::Shell(_)
1339        ));
1340        assert!(matches!(
1341            Dialect::OpenCode.parse(opencode_shell),
1342            Parsed::Shell(_)
1343        ));
1344    }
1345
1346    #[test]
1347    fn only_the_pinned_cursor_content_tools_are_writes() {
1348        // The exact Cursor content-tool name set is a live-verification gap, so
1349        // only the fixture-pinned names are accepted (0.2.1 lesson: never guess a
1350        // shape). An unknown tool is a miss, never a wrong parse.
1351        let read = mutated_fixture("cursor-write.json", |v| {
1352            v["tool_name"] = serde_json::json!("Read");
1353        });
1354        assert_eq!(Dialect::Cursor.parse_write(&read), None);
1355        let delete = mutated_fixture("cursor-write.json", |v| {
1356            v["tool_name"] = serde_json::json!("Delete");
1357        });
1358        assert_eq!(Dialect::Cursor.parse_write(&delete), None);
1359    }
1360
1361    #[test]
1362    fn write_parse_is_tolerant_of_malformed_payloads() {
1363        for (dialect, name) in [
1364            (Dialect::Cursor, "cursor-write.json"),
1365            (Dialect::Cursor, "cursor-after-file-edit.json"),
1366            (Dialect::OpenCode, "opencode-write-v1.json"),
1367            (Dialect::OpenCode, "opencode-write-v2.json"),
1368        ] {
1369            let text = fixture_text(name);
1370            let truncated: String = text.chars().take(text.chars().count() / 2).collect();
1371            assert_eq!(dialect.parse_write(&truncated), None, "truncated {name}");
1372        }
1373        // Missing identity.
1374        let no_tool = mutated_fixture("cursor-write.json", |v| {
1375            v.as_object_mut().unwrap().remove("tool_name");
1376        });
1377        assert_eq!(Dialect::Cursor.parse_write(&no_tool), None);
1378        // An `afterFileEdit` payload without the event marker is not a write.
1379        let no_event = mutated_fixture("cursor-after-file-edit.json", |v| {
1380            v.as_object_mut().unwrap().remove("hook_event_name");
1381        });
1382        assert_eq!(Dialect::Cursor.parse_write(&no_event), None);
1383        // Wrong types.
1384        let bad_type = mutated_fixture("cursor-write.json", |v| {
1385            v["tool_name"] = serde_json::json!(7);
1386        });
1387        assert_eq!(Dialect::Cursor.parse_write(&bad_type), None);
1388    }
1389
1390    #[test]
1391    fn dialects_without_a_pinned_write_surface_return_none() {
1392        // Task 1 pinned write shapes for Cursor and OpenCode only. Every other
1393        // dialect reports "no write surface" rather than guessing (its post-tool
1394        // or shell coverage is unaffected).
1395        let cursor_write = fixture_text("cursor-write.json");
1396        for d in [
1397            Dialect::Claude,
1398            Dialect::Qwen,
1399            Dialect::Gemini,
1400            Dialect::Copilot,
1401            Dialect::Codex,
1402            Dialect::Antigravity,
1403        ] {
1404            assert_eq!(d.parse_write(&cursor_write), None, "{d:?}");
1405        }
1406    }
1407
1408    #[test]
1409    fn dialects_without_a_pinned_post_surface_return_none() {
1410        // No Task-1 fixture pins these dialects' post shapes, so Kintsugi
1411        // honestly reports "no post surface" rather than guessing at a wire
1412        // format (the 0.2.1 lesson). Qwen's PostToolUse exists upstream but is
1413        // unpinned; Cursor/OpenCode write surfaces are Task 3; Copilot's
1414        // postToolUse lacks a tool_use_id (open issue, out of scope); Gemini
1415        // uses AfterTool, a different contract entirely.
1416        let claude_fixture = fixture_text("claude-post-tool-use.json");
1417        for d in [
1418            Dialect::Qwen,
1419            Dialect::Gemini,
1420            Dialect::Copilot,
1421            Dialect::Cursor,
1422            Dialect::OpenCode,
1423        ] {
1424            assert_eq!(d.parse_post(&claude_fixture), None, "{d:?}");
1425        }
1426        // Their PRE-tool shell payloads parse exactly as before.
1427        let cursor_shell = r#"{"command":"git status","cwd":"/tmp","hook_event_name":"beforeShellExecution","conversation_id":"c1"}"#;
1428        assert!(matches!(
1429            Dialect::Cursor.parse(cursor_shell),
1430            Parsed::Shell(_)
1431        ));
1432        assert_eq!(Dialect::Cursor.parse_post(cursor_shell), None);
1433    }
1434}