catenary-mcp 1.6.1

A high-performance multiplexing bridge between MCP (Model Context Protocol) and LSP (Language Server Protocol). Enables LLMs to access IDE-grade code intelligence across multiple languages simultaneously with smart routing and UTF-8 accuracy.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 Mark Wells <contact@markwells.dev>

//! Hook handlers for host CLI integration.
//!
//! Each function is a thin transport: read stdin from the host CLI,
//! connect to the running Catenary session's IPC socket, forward the
//! request as a `HookRequest`, and format the response for the host.
//!
//! All hook logic runs server-side in `HookServer` (`src/hook.rs`).
//!
//! Function names mirror the hook lifecycle:
//! - `run_pre_agent` — root sync (`UserPromptSubmit` / `BeforeAgent`)
//! - `run_pre_tool` — editing state enforcement (`PreToolUse` / `BeforeTool`)
//! - `run_post_tool` — diagnostics (`PostToolUse` / `AfterTool`)
//! - `run_post_agent` — force `done_editing` (`Stop` / `AfterAgent`)
//! - `run_session_start` — clear stale editing state (`SessionStart`)

#![allow(clippy::print_stdout, reason = "CLI tool needs to output to stdout")]
#![allow(clippy::print_stderr, reason = "CLI tool needs to output to stderr")]

use std::path::PathBuf;
use std::time::Duration;

use crate::cli::HostFormat;
use crate::{db, session};

/// Returns the IPC endpoint path for a session.
///
/// On Unix this is the Unix socket path in the session directory.
/// On Windows this is a named pipe in the kernel namespace.
fn notify_endpoint(session_id: &str) -> PathBuf {
    #[cfg(unix)]
    {
        session::sessions_dir().join(session_id).join("notify.sock")
    }
    #[cfg(windows)]
    {
        PathBuf::from(format!(r"\\.\pipe\catenary-{session_id}"))
    }
}

/// Connects to a notify IPC endpoint and returns a stream for I/O.
///
/// Returns `None` silently on failure (hooks must not break Claude Code's flow).
#[cfg(unix)]
fn notify_connect(endpoint: &std::path::Path) -> Option<std::os::unix::net::UnixStream> {
    if !endpoint.exists() {
        return None;
    }
    let stream = std::os::unix::net::UnixStream::connect(endpoint).ok()?;
    let _ = stream.set_read_timeout(Some(Duration::from_secs(60)));
    let _ = stream.set_write_timeout(Some(Duration::from_secs(5)));
    Some(stream)
}

/// Connects to a notify IPC endpoint and returns a stream for I/O.
///
/// Returns `None` silently on failure (hooks must not break Claude Code's flow).
#[cfg(windows)]
fn notify_connect(endpoint: &std::path::Path) -> Option<std::fs::File> {
    use std::os::windows::fs::OpenOptionsExt;
    // SECURITY_IDENTIFICATION (0x0001_0000) prevents impersonation attacks
    std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .security_qos_flags(0x0001_0000)
        .open(endpoint)
        .ok()
}

/// Sends a JSON request over an IPC stream and reads response lines.
fn ipc_exchange(
    mut stream: impl std::io::Read + std::io::Write,
    request: &serde_json::Value,
) -> Vec<String> {
    use std::io::BufRead;

    if serde_json::to_writer(&mut stream, request).is_err() {
        return Vec::new();
    }
    if stream.write_all(b"\n").is_err() || stream.flush().is_err() {
        return Vec::new();
    }

    let reader = std::io::BufReader::new(stream);
    let mut lines = Vec::new();
    for line in reader.lines() {
        match line {
            Ok(text) if !text.is_empty() => lines.push(text),
            _ => break,
        }
    }
    lines
}

/// Format a `PreToolUse` deny response for the host CLI.
fn format_deny(reason: &str, format: HostFormat) -> String {
    match format {
        HostFormat::Claude => serde_json::json!({
            "hookSpecificOutput": {
                "hookEventName": "PreToolUse",
                "permissionDecision": "deny",
                "permissionDecisionReason": reason
            }
        })
        .to_string(),
        HostFormat::Gemini => serde_json::json!({
            "decision": "deny",
            "reason": reason
        })
        .to_string(),
    }
}

/// Format a Stop/AfterAgent block response for the host CLI.
fn format_stop_block(reason: &str, format: HostFormat) -> String {
    match format {
        HostFormat::Claude => serde_json::json!({
            "decision": "block",
            "reason": reason
        })
        .to_string(),
        HostFormat::Gemini => serde_json::json!({
            "decision": "retry",
            "reason": reason
        })
        .to_string(),
    }
}

/// Find the Catenary session ID for a hook payload, using the working directory
/// to match against workspace roots. Returns `None` if no matching session.
fn find_session_id(hook_json: &serde_json::Value, conn: &rusqlite::Connection) -> Option<String> {
    let cwd = hook_json.get("cwd").and_then(|v| v.as_str()).map_or_else(
        || std::env::current_dir().unwrap_or_default(),
        PathBuf::from,
    );
    let cwd_str = cwd.to_string_lossy();
    let sessions = session::list_sessions_with_conn(conn).unwrap_or_default();
    sessions
        .into_iter()
        .find(|(s, alive)| *alive && cwd_str.starts_with(&s.workspace))
        .map(|(s, _)| s.id)
}

/// Extract `agent_id` from hook payload. Defaults to empty string (main agent).
fn extract_agent_id(hook_json: &serde_json::Value) -> &str {
    hook_json
        .get("agent_id")
        .and_then(|v| v.as_str())
        .unwrap_or("")
}

/// Extracts the file path from hook JSON's `tool_input`.
fn extract_file_path(hook_json: &serde_json::Value) -> Option<String> {
    let file_path = hook_json
        .get("tool_input")
        .and_then(|ti| ti.get("file_path").or_else(|| ti.get("file")))
        .and_then(|fp| fp.as_str())?;

    // Resolve to absolute path
    let abs_path = if std::path::Path::new(file_path).is_absolute() {
        PathBuf::from(file_path)
    } else {
        let cwd = hook_json.get("cwd").and_then(|v| v.as_str()).map_or_else(
            || std::env::current_dir().unwrap_or_default(),
            PathBuf::from,
        );
        cwd.join(file_path)
    };

    Some(abs_path.to_string_lossy().into_owned())
}

// ── Hook transport functions ────────────────────────────────────────────

/// Clear all editing state for a session (`SessionStart` hook handler).
///
/// Called on session start, resume, `/clear`, and `/compact`. The agent's
/// context is gone, so stale editing state must be cleared. No diagnostics
/// are delivered.
///
/// Also validates the configuration at session start. If the config is
/// invalid, emits a `systemMessage` directing the user to `catenary doctor`.
pub fn run_session_start(format: HostFormat) {
    // Config validation — runs before anything else, no session needed.
    if let Err(e) = crate::config::Config::check() {
        let msg =
            format!("Catenary configuration error: {e:#}. Run `catenary doctor` for details.");
        let output = format_session_message(&msg, format);
        print!("{output}");
        return;
    }

    let Ok(stdin_data) = std::io::read_to_string(std::io::stdin()) else {
        return;
    };
    let Ok(hook_json) = serde_json::from_str::<serde_json::Value>(&stdin_data) else {
        return;
    };

    let Ok(conn) = db::open_and_migrate() else {
        return;
    };
    let Some(catenary_sid) = find_session_id(&hook_json, &conn) else {
        return;
    };

    let endpoint = notify_endpoint(&catenary_sid);
    let Some(stream) = notify_connect(&endpoint) else {
        return;
    };

    let session_id = hook_json.get("session_id").and_then(|v| v.as_str());
    let mut request = serde_json::json!({"method": "session-start/clear-editing"});
    if let Some(sid) = session_id {
        request["session_id"] = serde_json::json!(sid);
    }

    let lines = ipc_exchange(stream, &request);

    if let Some(line) = lines.first()
        && let Ok(crate::hook::HookResult::Cleared(count)) =
            serde_json::from_str::<crate::hook::HookResult>(line)
    {
        let msg = format!("Catenary: cleared {count} stale editing state entries");
        let output = format_session_message(&msg, format);
        print!("{output}");
    }
}

/// Format a `systemMessage` for session-start hooks.
fn format_session_message(msg: &str, format: HostFormat) -> String {
    match format {
        HostFormat::Claude | HostFormat::Gemini => {
            serde_json::json!({ "systemMessage": msg }).to_string()
        }
    }
}

/// Force `done_editing` before the agent finishes responding (`Stop` / `AfterAgent`
/// hook handler).
///
/// If the agent has files in editing state, blocks the stop with a message
/// directing the agent to call `done_editing`. If `stop_hook_active` is true
/// (retry after agent failed to comply), force-clears the stale editing state
/// and allows the stop.
pub fn run_post_agent(format: HostFormat) {
    let Ok(stdin_data) = std::io::read_to_string(std::io::stdin()) else {
        return;
    };
    let Ok(hook_json) = serde_json::from_str::<serde_json::Value>(&stdin_data) else {
        return;
    };

    let Ok(conn) = db::open_and_migrate() else {
        return;
    };
    let Some(catenary_sid) = find_session_id(&hook_json, &conn) else {
        return;
    };

    let endpoint = notify_endpoint(&catenary_sid);
    let Some(stream) = notify_connect(&endpoint) else {
        return;
    };

    let stop_hook_active = hook_json
        .get("stop_hook_active")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false);
    let agent_id = extract_agent_id(&hook_json);

    let request = serde_json::json!({
        "method": "post-agent/require-release",
        "agent_id": agent_id,
        "stop_hook_active": stop_hook_active,
    });

    let lines = ipc_exchange(stream, &request);

    if let Some(line) = lines.first()
        && let Ok(crate::hook::HookResult::Block(reason)) =
            serde_json::from_str::<crate::hook::HookResult>(line)
    {
        print!("{}", format_stop_block(&reason, format));
    }
}

/// Run diagnostics after reading or editing (`PostToolUse` / `AfterTool` hook handler).
///
/// Reads hook JSON from stdin, finds the session for the file's workspace,
/// connects to the IPC socket, and returns diagnostics for the model's
/// context. Emits `systemMessage` JSON on infrastructure errors so the user
/// sees failures in their terminal.
///
/// For `done_editing`, sends a `post-tool/done-editing` IPC request instead
/// of the per-file `post-tool/diagnostics` — the server drains accumulated
/// files and returns batch diagnostics.
pub fn run_post_tool(format: HostFormat) {
    let Ok(stdin_data) = std::io::read_to_string(std::io::stdin()) else {
        return;
    };
    let Ok(hook_json) = serde_json::from_str::<serde_json::Value>(&stdin_data) else {
        return;
    };

    let tool_name = hook_json
        .get("tool_name")
        .and_then(|v| v.as_str())
        .unwrap_or("");

    // done_editing: batch diagnostics (no file path needed).
    if tool_name.contains("done_editing") {
        run_post_tool_done_editing(&hook_json, format);
        return;
    }

    // Per-file diagnostics: requires a file path.
    let Some(file_path) = extract_file_path(&hook_json) else {
        print!(
            "{}",
            notify_error(
                "missing file path in hook input — diagnostics skipped",
                format,
            )
        );
        return;
    };

    let Ok(conn) = db::open_and_migrate() else {
        print!(
            "{}",
            notify_error(
                "state database unavailable — try running: catenary list",
                format
            )
        );
        return;
    };
    let Some(catenary_sid) = find_session_id(&hook_json, &conn) else {
        return;
    };

    let endpoint = notify_endpoint(&catenary_sid);
    let Some(stream) = notify_connect(&endpoint) else {
        print!(
            "{}",
            notify_error(
                &format!("session {catenary_sid} is not responding — it may have crashed"),
                format,
            )
        );
        return;
    };

    let agent_id = extract_agent_id(&hook_json);
    let session_id = hook_json.get("session_id").and_then(|v| v.as_str());

    let mut request = serde_json::json!({
        "method": "post-tool/diagnostics",
        "file": file_path,
        "agent_id": agent_id,
    });
    if !tool_name.is_empty() {
        request["tool"] = serde_json::json!(tool_name);
    }
    if let Some(sid) = session_id {
        request["session_id"] = serde_json::json!(sid);
    }

    let lines = ipc_exchange(stream, &request);
    format_post_tool_response(&lines, &file_path, format);
}

/// Format and print the IPC response from `post-tool/diagnostics`.
fn format_post_tool_response(lines: &[String], file_path: &str, format: HostFormat) {
    let Some(line) = lines.first() else {
        return; // Empty response = suppress (self-editing)
    };

    let filename = std::path::Path::new(file_path)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or(file_path);

    let Ok(result) = serde_json::from_str::<crate::hook::HookResult>(line) else {
        print!(
            "{}",
            format_diagnostics(&format!("{filename}\n\t{line}"), format, "PostToolUse")
        );
        return;
    };

    match result {
        crate::hook::HookResult::Content(content) => {
            print!(
                "{}",
                format_diagnostics(&format!("{filename}\n\t{content}"), format, "PostToolUse")
            );
        }
        crate::hook::HookResult::Courtesy(content) => {
            let courtesy = "\n\t[diagnostics for this file are being deferred by another agent]";
            print!(
                "{}",
                format_diagnostics(
                    &format!("{filename}\n\t{content}{courtesy}"),
                    format,
                    "PostToolUse"
                )
            );
        }
        crate::hook::HookResult::Error(msg) => {
            print!("{}", notify_error(&msg, format));
        }
        _ => {} // unexpected variant for this hook
    }
}

/// Handle `done_editing` `PostToolUse`: send `post-tool/done-editing` IPC
/// request to drain accumulated files and return batch diagnostics.
fn run_post_tool_done_editing(hook_json: &serde_json::Value, format: HostFormat) {
    let Ok(conn) = db::open_and_migrate() else {
        print!(
            "{}",
            notify_error(
                "state database unavailable — try running: catenary list",
                format,
            )
        );
        return;
    };
    let Some(catenary_sid) = find_session_id(hook_json, &conn) else {
        return;
    };

    let endpoint = notify_endpoint(&catenary_sid);
    let Some(stream) = notify_connect(&endpoint) else {
        print!(
            "{}",
            notify_error(
                &format!("session {catenary_sid} is not responding — it may have crashed"),
                format,
            )
        );
        return;
    };

    let agent_id = extract_agent_id(hook_json);
    let session_id = hook_json.get("session_id").and_then(|v| v.as_str());

    let mut request = serde_json::json!({
        "method": "post-tool/done-editing",
        "agent_id": agent_id,
    });
    if let Some(sid) = session_id {
        request["session_id"] = serde_json::json!(sid);
    }

    let lines = ipc_exchange(stream, &request);
    let Some(line) = lines.first() else {
        return;
    };

    let Ok(result) = serde_json::from_str::<crate::hook::HookResult>(line) else {
        print!("{}", format_diagnostics(line, format, "PostToolUse"));
        return;
    };

    if let crate::hook::HookResult::Content(content) = result {
        print!("{}", format_diagnostics(&content, format, "PostToolUse"));
    }
}

/// Refresh workspace roots (`UserPromptSubmit` / `BeforeAgent` hook handler).
///
/// Sends a `pre-agent/roots-sync` IPC request to the running Catenary session
/// so `/add-dir` workspace additions are picked up. Runs once per user prompt
/// rather than on every tool call.
///
/// Silently succeeds on any error to avoid breaking the host CLI's flow.
pub fn run_pre_agent(format: HostFormat) {
    let _ = format; // Reserved for future per-host output formatting.

    let Ok(stdin_data) = std::io::read_to_string(std::io::stdin()) else {
        return;
    };

    let Ok(hook_json) = serde_json::from_str::<serde_json::Value>(&stdin_data) else {
        return;
    };

    let Ok(conn) = db::open_and_migrate() else {
        return;
    };

    if let Some(catenary_sid) = find_session_id(&hook_json, &conn) {
        let endpoint = notify_endpoint(&catenary_sid);
        if let Some(stream) = notify_connect(&endpoint) {
            let request = serde_json::json!({"method": "pre-agent/roots-sync"});
            let _ = ipc_exchange(stream, &request);
        }
    }
}

/// Editing state enforcement (`PreToolUse` / `BeforeTool` hook handler).
///
/// Sends a `pre-tool/enforce-editing` IPC request and formats any deny
/// response for the host CLI.
///
/// Silently succeeds on any error to avoid breaking the host CLI's flow.
pub fn run_pre_tool(format: HostFormat) {
    let Ok(stdin_data) = std::io::read_to_string(std::io::stdin()) else {
        return;
    };

    let Ok(hook_json) = serde_json::from_str::<serde_json::Value>(&stdin_data) else {
        return;
    };

    let Ok(conn) = db::open_and_migrate() else {
        return;
    };
    let Some(catenary_sid) = find_session_id(&hook_json, &conn) else {
        return;
    };

    let endpoint = notify_endpoint(&catenary_sid);
    let Some(stream) = notify_connect(&endpoint) else {
        return;
    };

    let tool_name = hook_json
        .get("tool_name")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    let file_path = extract_file_path(&hook_json);
    let agent_id = extract_agent_id(&hook_json);
    let session_id = hook_json.get("session_id").and_then(|v| v.as_str());

    let mut request = serde_json::json!({
        "method": "pre-tool/enforce-editing",
        "tool_name": tool_name,
        "agent_id": agent_id,
    });
    if let Some(path) = &file_path {
        request["file_path"] = serde_json::json!(path);
    }
    if let Some(sid) = session_id {
        request["session_id"] = serde_json::json!(sid);
    }

    let lines = ipc_exchange(stream, &request);

    if let Some(line) = lines.first()
        && let Ok(crate::hook::HookResult::Deny(reason)) =
            serde_json::from_str::<crate::hook::HookResult>(line)
    {
        print!("{}", format_deny(&reason, format));
    }
}

// ── Formatting helpers ──────────────────────────────────────────────────

/// Format diagnostic content for the model via `additionalContext`.
///
/// Both formats wrap content in a `hookSpecificOutput` JSON envelope
/// so the host CLI can inject it into the model's context:
///
/// - Claude: includes `hookEventName` + `additionalContext` (required by
///   the Claude Code hook contract).
/// - Gemini: uses `additionalContext` only (no `hookEventName`).
fn format_diagnostics(content: &str, format: HostFormat, hook_event: &str) -> String {
    match format {
        HostFormat::Gemini => serde_json::json!({
            "hookSpecificOutput": {
                "additionalContext": content
            }
        })
        .to_string(),
        HostFormat::Claude => serde_json::json!({
            "hookSpecificOutput": {
                "hookEventName": hook_event,
                "additionalContext": content
            }
        })
        .to_string(),
    }
}

/// GitHub issues URL for user-facing bug report suggestions.
const BUG_REPORT_URL: &str = "https://github.com/TwoWells/Catenary/issues";

/// Format an internal error for the user via `systemMessage`, with a bug
/// report link appended.
///
/// The error is shown to the user in their terminal but not injected into
/// the model's context — the model cannot act on internal Catenary failures.
fn notify_error(message: &str, format: HostFormat) -> String {
    let full =
        format!("Catenary: {message}. If this persists, please file a bug: {BUG_REPORT_URL}");
    format_error(&full, format)
}

/// Format an internal error for the user via `systemMessage`.
///
/// The error is shown to the user in their terminal but not injected into
/// the model's context — the model cannot act on internal Catenary failures.
fn format_error(message: &str, format: HostFormat) -> String {
    match format {
        HostFormat::Claude => serde_json::json!({
            "hookSpecificOutput": {
                "hookEventName": "PostToolUse",
            },
            "systemMessage": message
        })
        .to_string(),
        HostFormat::Gemini => serde_json::json!({
            "hookSpecificOutput": {},
            "systemMessage": message
        })
        .to_string(),
    }
}

#[cfg(test)]
#[allow(
    clippy::expect_used,
    reason = "tests use expect for readable assertions"
)]
#[allow(
    clippy::similar_names,
    reason = "content/context are distinct concepts in hook output tests"
)]
mod tests {
    use super::*;
    use anyhow::{Context, Result};

    #[test]
    fn test_format_diagnostics_claude() -> Result<()> {
        let content = "error[E0308]: mismatched types\n  --> src/main.rs:5:10";
        let output = format_diagnostics(content, HostFormat::Claude, "PostToolUse");
        let parsed: serde_json::Value =
            serde_json::from_str(&output).context("claude format should produce valid JSON")?;

        let hook_output = &parsed["hookSpecificOutput"];
        assert_eq!(hook_output["hookEventName"], "PostToolUse");
        let context = hook_output["additionalContext"]
            .as_str()
            .expect("additionalContext should be a string");
        assert!(context.contains("error[E0308]: mismatched types"));
        assert!(context.contains("  --> src/main.rs:5:10"));
        Ok(())
    }

    #[test]
    fn test_format_diagnostics_gemini() -> Result<()> {
        let content = "error[E0308]: mismatched types";
        let output = format_diagnostics(content, HostFormat::Gemini, "PostToolUse");
        let parsed: serde_json::Value =
            serde_json::from_str(&output).context("gemini format should produce valid JSON")?;

        let context = parsed["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .expect("additionalContext should be a string");
        assert_eq!(context, content);
        // Gemini format should NOT have hookEventName
        assert!(parsed["hookSpecificOutput"]["hookEventName"].is_null());
        Ok(())
    }

    #[test]
    fn test_format_diagnostics_gemini_multiline() -> Result<()> {
        let content = "warning: unused variable\n  --> lib.rs:3:9";
        let output = format_diagnostics(content, HostFormat::Gemini, "PostToolUse");
        let parsed: serde_json::Value =
            serde_json::from_str(&output).context("should produce valid JSON")?;
        let context = parsed["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .expect("additionalContext should be a string");
        assert!(context.contains("warning: unused variable\n  --> lib.rs:3:9"));
        Ok(())
    }

    #[test]
    fn test_format_diagnostics_claude_propagates_hook_event() -> Result<()> {
        let content = "Added roots: /tmp/foo";
        let output = format_diagnostics(content, HostFormat::Claude, "PreToolUse");
        let parsed: serde_json::Value =
            serde_json::from_str(&output).context("should produce valid JSON")?;

        assert_eq!(parsed["hookSpecificOutput"]["hookEventName"], "PreToolUse");
        Ok(())
    }

    #[test]
    fn test_format_error_claude() -> Result<()> {
        let output = format_error("Catenary: database unavailable", HostFormat::Claude);
        let parsed: serde_json::Value =
            serde_json::from_str(&output).context("should produce valid JSON")?;

        assert_eq!(parsed["systemMessage"], "Catenary: database unavailable");
        assert_eq!(parsed["hookSpecificOutput"]["hookEventName"], "PostToolUse");
        assert!(parsed["hookSpecificOutput"]["additionalContext"].is_null());
        Ok(())
    }

    #[test]
    fn test_format_error_gemini() -> Result<()> {
        let output = format_error("Catenary: database unavailable", HostFormat::Gemini);
        let parsed: serde_json::Value =
            serde_json::from_str(&output).context("should produce valid JSON")?;

        assert_eq!(parsed["systemMessage"], "Catenary: database unavailable");
        assert!(parsed["hookSpecificOutput"]["hookEventName"].is_null());
        assert!(parsed["hookSpecificOutput"]["additionalContext"].is_null());
        Ok(())
    }
}