Skip to main content

lean_ctx_proxy/
tool_kind.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Classifies what produced a `tool_result` so the proxy never lossy-compresses
3//! a file/source-code read the model still needs (e.g. mid-refactor).
4//!
5//! The request body only carries the tool *result* plus an id linking it to the
6//! originating tool *call*. We resolve that id → tool name from the assistant's
7//! `tool_use` / `tool_calls` / `function_call` items, then map the name to a
8//! [`ToolResultKind`]. A content heuristic ([`looks_like_source_code`]) is the
9//! fallback for unknown/custom tools so a file read through a non-standard tool
10//! is still protected.
11
12use std::collections::HashMap;
13
14use serde_json::Value;
15
16/// What kind of tool produced a `tool_result`.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum ToolResultKind {
19    /// A file/source read — must reach the model intact (it is what gets edited).
20    FileRead,
21    /// Shell/command output — safe to run through the pattern compressors.
22    Shell,
23    /// Search/listing output — safe to compress.
24    Search,
25    /// Unknown — fall back to the content heuristic before compressing.
26    Other,
27}
28
29/// Maps a tool name (from any agent) to a [`ToolResultKind`].
30///
31/// Matching is case-insensitive and substring-based so vendor prefixes
32/// (`mcp__fs__read_file`, `functions.read`) and casing variants are covered.
33pub fn classify_tool_name(name: &str) -> ToolResultKind {
34    let n = name.to_ascii_lowercase();
35
36    // Order matters: a "read_file" must not be caught by a generic "file".
37    const FILE_READ: &[&str] = &[
38        "read_file",
39        "readfile",
40        "file_read",
41        "fsread",
42        "fs_read",
43        "view_file",
44        "viewfile",
45        "open_file",
46        "notebookread",
47        "notebook_read",
48        "cat_file",
49        "get_file",
50        "fetch_file",
51        "ctx_read",
52        "ctx_multi_read",
53        "multi_read",
54        "multiread",
55        "read_many", // Gemini CLI `read_many_files`
56        "read_files",
57        "str_replace_editor", // view sub-mode returns file content
58        "ctx_patch",          // #818: diff previews are code — never abbreviate
59        "ctx_refactor",       // symbol edits return code diffs
60        "ctx_callgraph",      // callers/callees contain source snippets
61    ];
62    if FILE_READ.iter().any(|k| n.contains(k)) {
63        return ToolResultKind::FileRead;
64    }
65    // Bare "read"/"view"/"cat" as a whole token (Claude Code `Read`, Pi `read`).
66    if matches!(n.as_str(), "read" | "view" | "cat" | "open") {
67        return ToolResultKind::FileRead;
68    }
69
70    const SEARCH: &[&str] = &[
71        "grep",
72        "ripgrep",
73        "search",
74        "find",
75        "glob",
76        "list_dir",
77        "listdir",
78        "list_files",
79        "listfiles",
80        "ls",
81        "codebase_search",
82        "ctx_search",
83        "ctx_tree",
84    ];
85    if SEARCH.iter().any(|k| n.contains(k)) {
86        return ToolResultKind::Search;
87    }
88
89    const SHELL: &[&str] = &[
90        "bash",
91        "shell",
92        "terminal",
93        "run_command",
94        "run_terminal",
95        "runterminal",
96        "execute_command",
97        "exec_command",
98        "command_exec",
99        "ctx_shell",
100    ];
101    if SHELL.iter().any(|k| n.contains(k)) {
102        return ToolResultKind::Shell;
103    }
104    if matches!(n.as_str(), "run" | "exec" | "execute" | "command" | "sh") {
105        return ToolResultKind::Shell;
106    }
107
108    // Vendor-prefix fallback. Foreign harnesses namespace their tools
109    // (`forge_read`, `pi.shell`, `fs:grep`), which the substring lists above
110    // miss. Matching the name's path-like *segments* as whole words catches
111    // those without the false positives a bare substring would cause
112    // (`thread`, `research`, `already`). FileRead is checked first so a read is
113    // never misclassified as compressible.
114    for seg in n.split(|c: char| !c.is_ascii_alphanumeric()) {
115        match seg {
116            "read" | "view" | "cat" | "open" => return ToolResultKind::FileRead,
117            "grep" | "search" | "find" | "glob" | "ls" | "rg" => return ToolResultKind::Search,
118            "shell" | "bash" | "exec" | "run" | "terminal" | "cmd" => return ToolResultKind::Shell,
119            _ => {}
120        }
121    }
122
123    ToolResultKind::Other
124}
125
126/// Builds a `tool_use_id → tool_name` map from Anthropic `messages`.
127///
128/// Scans every assistant content block of `type:"tool_use"`.
129pub fn anthropic_tool_names(messages: &[Value]) -> HashMap<String, String> {
130    let mut map = HashMap::new();
131    for msg in messages {
132        let Some(blocks) = msg.get("content").and_then(|c| c.as_array()) else {
133            continue;
134        };
135        for block in blocks {
136            if block.get("type").and_then(|t| t.as_str()) != Some("tool_use") {
137                continue;
138            }
139            if let (Some(id), Some(name)) = (
140                block.get("id").and_then(|v| v.as_str()),
141                block.get("name").and_then(|v| v.as_str()),
142            ) {
143                map.insert(id.to_string(), name.to_string());
144            }
145        }
146    }
147    map
148}
149
150/// Builds a `tool_call_id → function_name` map from OpenAI Chat Completions
151/// `messages` (assistant `tool_calls[]`).
152pub fn openai_tool_names(messages: &[Value]) -> HashMap<String, String> {
153    let mut map = HashMap::new();
154    for msg in messages {
155        let Some(calls) = msg.get("tool_calls").and_then(|c| c.as_array()) else {
156            continue;
157        };
158        for call in calls {
159            let id = call.get("id").and_then(|v| v.as_str());
160            let name = call
161                .get("function")
162                .and_then(|f| f.get("name"))
163                .and_then(|v| v.as_str());
164            if let (Some(id), Some(name)) = (id, name) {
165                map.insert(id.to_string(), name.to_string());
166            }
167        }
168    }
169    map
170}
171
172/// Builds a `call_id → name` map from OpenAI Responses `input` items
173/// (`type:"function_call"`).
174pub fn responses_tool_names(input: &[Value]) -> HashMap<String, String> {
175    let mut map = HashMap::new();
176    for item in input {
177        if item.get("type").and_then(|t| t.as_str()) != Some("function_call") {
178            continue;
179        }
180        if let (Some(id), Some(name)) = (
181            item.get("call_id").and_then(|v| v.as_str()),
182            item.get("name").and_then(|v| v.as_str()),
183        ) {
184            map.insert(id.to_string(), name.to_string());
185        }
186    }
187    map
188}
189
190/// The shell command a tool call's arguments name: `command` or `cmd`, as a
191/// string or an argv array. An argv that runs a shell script (`bash -lc
192/// "<script>"`) names that script; any other argv is joined by spaces.
193fn command_of(arguments: &Value) -> Option<String> {
194    let arguments = match arguments {
195        Value::String(raw) => &serde_json::from_str::<Value>(raw).ok()?,
196        other => other,
197    };
198    let command = arguments.get("command").or_else(|| arguments.get("cmd"))?;
199    match command {
200        Value::String(command) => Some(command.clone()),
201        Value::Array(argv) => {
202            let argv: Vec<&str> = argv.iter().filter_map(Value::as_str).collect();
203            match argv.as_slice() {
204                [] => None,
205                [shell, flag, script]
206                    if matches!(
207                        shell.rsplit('/').next(),
208                        Some("sh" | "bash" | "zsh" | "dash" | "ksh")
209                    ) && flag.starts_with('-')
210                        && flag.ends_with('c') =>
211                {
212                    Some((*script).to_string())
213                }
214                parts => Some(parts.join(" ")),
215            }
216        }
217        _ => None,
218    }
219}
220
221/// `tool_use_id → command` for the Anthropic `tool_use` blocks whose input
222/// names a shell command (`Bash {command}`).
223pub fn anthropic_tool_commands(messages: &[Value]) -> HashMap<String, String> {
224    let mut map = HashMap::new();
225    for msg in messages {
226        let Some(blocks) = msg.get("content").and_then(|c| c.as_array()) else {
227            continue;
228        };
229        for block in blocks {
230            if block.get("type").and_then(|t| t.as_str()) != Some("tool_use") {
231                continue;
232            }
233            if let (Some(id), Some(command)) = (
234                block.get("id").and_then(|v| v.as_str()),
235                block.get("input").and_then(command_of),
236            ) {
237                map.insert(id.to_string(), command);
238            }
239        }
240    }
241    map
242}
243
244/// `tool_call_id → command` for the Chat Completions `tool_calls[]` whose
245/// `function.arguments` name a shell command.
246pub fn openai_tool_commands(messages: &[Value]) -> HashMap<String, String> {
247    let mut map = HashMap::new();
248    for msg in messages {
249        let Some(calls) = msg.get("tool_calls").and_then(|c| c.as_array()) else {
250            continue;
251        };
252        for call in calls {
253            let id = call.get("id").and_then(|v| v.as_str());
254            let command = call
255                .get("function")
256                .and_then(|f| f.get("arguments"))
257                .and_then(command_of);
258            if let (Some(id), Some(command)) = (id, command) {
259                map.insert(id.to_string(), command);
260            }
261        }
262    }
263    map
264}
265
266/// `call_id → command` for the Responses `function_call` items whose
267/// `arguments` name a shell command, and `local_shell_call` items
268/// (`action.command`).
269pub fn responses_tool_commands(input: &[Value]) -> HashMap<String, String> {
270    let mut map = HashMap::new();
271    for item in input {
272        let command = match item.get("type").and_then(|t| t.as_str()) {
273            Some("function_call") => item.get("arguments").and_then(command_of),
274            Some("local_shell_call") => item.get("action").and_then(command_of),
275            _ => None,
276        };
277        if let (Some(id), Some(command)) = (item.get("call_id").and_then(|v| v.as_str()), command) {
278            map.insert(id.to_string(), command);
279        }
280    }
281    map
282}
283
284/// `(contents index, parts index) → command` for the Gemini
285/// `functionResponse` parts whose `functionCall` names a shell command in its
286/// `args` (Gemini CLI's `run_shell_command {command}`). A response answers
287/// the call with its `id` when it carries one; without an `id`, Gemini pairs
288/// calls and responses by name in order, so it answers the first unanswered
289/// call of its name. A response that matches no call gets no command — and
290/// is compressed like any other result (with its re-read hint).
291///
292/// Fail-safe by construction: an `id` on one side only matches nothing (an
293/// id-carrying call waits for its id; an id-less response pops only id-less
294/// calls), and parallel id-less calls of one name answered out of order can
295/// swap their commands — either way a result is at worst kept whole or
296/// compressed with its re-read hint, never shortened without a way back.
297pub fn gemini_tool_commands(contents: &[Value]) -> HashMap<(usize, usize), String> {
298    let mut by_id: HashMap<&str, Option<String>> = HashMap::new();
299    let mut by_name: HashMap<&str, std::collections::VecDeque<Option<String>>> = HashMap::new();
300    let mut map = HashMap::new();
301    for (content_idx, content) in contents.iter().enumerate() {
302        let Some(parts) = content.get("parts").and_then(Value::as_array) else {
303            continue;
304        };
305        for (part_idx, part) in parts.iter().enumerate() {
306            if let Some(call) = part.get("functionCall") {
307                let command = call.get("args").and_then(command_of);
308                if let Some(id) = call.get("id").and_then(Value::as_str) {
309                    by_id.insert(id, command);
310                } else if let Some(name) = call.get("name").and_then(Value::as_str) {
311                    by_name.entry(name).or_default().push_back(command);
312                }
313            } else if let Some(response) = part.get("functionResponse") {
314                let command = match response.get("id").and_then(Value::as_str) {
315                    Some(id) => by_id.remove(id).flatten(),
316                    None => response
317                        .get("name")
318                        .and_then(Value::as_str)
319                        .and_then(|name| by_name.get_mut(name))
320                        .and_then(std::collections::VecDeque::pop_front)
321                        .flatten(),
322                };
323                if let Some(command) = command {
324                    map.insert((content_idx, part_idx), command);
325                }
326            }
327        }
328    }
329    map
330}
331
332/// Whether a `tool_result` with the given resolved kind and content must be
333/// preserved intact (never lossy-compressed) by the proxy.
334///
335/// File reads are always protected; unknown tools are protected only when the
336/// content heuristically looks like source code. Shell/search output is never
337/// protected here — it flows through the normal pattern compressors.
338pub fn should_protect(kind: ToolResultKind, content: &str) -> bool {
339    match kind {
340        ToolResultKind::FileRead => true,
341        ToolResultKind::Other => looks_like_source_code(content),
342        ToolResultKind::Shell | ToolResultKind::Search => false,
343    }
344}
345
346/// Heuristic fallback: does this text look like source code (vs command output)?
347///
348/// Deliberately conservative — it only returns `true` when code signals clearly
349/// dominate and shell/log signals are essentially absent, so genuine logs and
350/// build output are still compressed. Used only when the tool name is unknown.
351///
352/// GH #628: the previous version under-counted real source — a decorative
353/// separator comment (`// ————`, `// ====`) and the call-shaped scaffolding of a
354/// test file (`describe(…) {`, `});`) scored as non-code, so a genuine source
355/// read routed through an unrecognized tool was lossy-compressed and silently
356/// lost those separator lines, breaking the model's subsequent exact-match edit.
357/// The fix: comment lines are *neutral* (never dilute the ratio) and top-level
358/// call/closer shapes count as code even at column 0. The shell-signal veto is
359/// untouched, so genuine logs and build output are still compressed.
360pub fn looks_like_source_code(content: &str) -> bool {
361    let mut code_signals = 0usize;
362    let mut shell_signals = 0usize;
363    let mut considered = 0usize;
364
365    for raw in content.lines().take(200) {
366        let line = raw.trim_end();
367        let trimmed = line.trim_start();
368        if trimmed.is_empty() {
369            continue;
370        }
371
372        // Comment lines are part of source but carry no compress-vs-keep signal
373        // on their own, and a decorative separator (`// ————`, `// ====`) or a
374        // doc-block continuation (` * @param`) must never *dilute* the code ratio
375        // — that false-negative is what let the proxy strip those lines (#628).
376        // Treat C-style comments as neutral: skip without counting. `#` is
377        // deliberately excluded (ambiguous with shell prompts / log levels /
378        // Python) so genuine shell output is still detected and compressed.
379        if trimmed.starts_with("//")
380            || trimmed.starts_with("/*")
381            || trimmed.starts_with("*/")
382            || trimmed.starts_with("* ")
383        {
384            continue;
385        }
386
387        considered += 1;
388
389        // Command/log markers — strong evidence this is NOT a file read.
390        if trimmed.starts_with("$ ")
391            || trimmed.starts_with("% ")
392            || trimmed.starts_with(">>> ")
393            || trimmed.starts_with("warning:")
394            || trimmed.starts_with("error:")
395            || trimmed.starts_with("error[")
396            || trimmed.starts_with("INFO ")
397            || trimmed.starts_with("WARN ")
398            || trimmed.starts_with("DEBUG ")
399            || trimmed.starts_with("ERROR ")
400            || trimmed.starts_with("Compiling ")
401            || trimmed.starts_with("Downloaded ")
402            || trimmed.starts_with("test result:")
403        {
404            shell_signals += 1;
405            continue;
406        }
407
408        // Code markers.
409        let is_indented = line.len() != trimmed.len();
410        let has_code_punct = trimmed.ends_with('{')
411            || trimmed.ends_with('}')
412            || trimmed.ends_with(';')
413            || trimmed.ends_with("=>")
414            || trimmed.ends_with("->")
415            || trimmed.ends_with(':');
416        // Top-level declarations, call statements and block closers carry code
417        // punctuation even at column 0 (`describe("x", () => {`, `});`), so the
418        // bare `is_indented && has_code_punct` test missed them — the exact
419        // test-DSL shape (`describe`/`it`/`expect`) behind the #628 false-negative.
420        // A call/closer *shape* with code punctuation is a strong code signal
421        // regardless of indentation.
422        let is_call_or_closer = (trimmed.contains('(') && trimmed.contains(')'))
423            || trimmed.starts_with('}')
424            || trimmed.starts_with(')');
425        let has_keyword = [
426            "fn ",
427            "def ",
428            "class ",
429            "import ",
430            "from ",
431            "function ",
432            "func ",
433            "pub ",
434            "const ",
435            "let ",
436            "var ",
437            "package ",
438            "public ",
439            "private ",
440            "struct ",
441            "enum ",
442            "impl ",
443            "#include",
444            "return ",
445            "async ",
446            "export ",
447        ]
448        .iter()
449        .any(|k| trimmed.starts_with(k) || trimmed.contains(k));
450
451        // Code punctuation counts when the line is indented (a statement in a
452        // block) OR is a top-level call/closer shape (`describe(…) {`, `});`).
453        let has_code_shape = has_code_punct && (is_indented || is_call_or_closer);
454        if has_code_shape || has_keyword {
455            code_signals += 1;
456        }
457    }
458
459    if considered < 5 || shell_signals > 0 {
460        return false;
461    }
462    // Require a clear majority of code-shaped lines.
463    code_signals * 2 >= considered
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469
470    #[test]
471    fn classifies_file_read_tools() {
472        for name in [
473            "Read",
474            "read_file",
475            "view_file",
476            "ctx_read",
477            "mcp__fs__readFile",
478            // Multi-file reads return file content and must be protected too.
479            "ctx_multi_read",
480            "read_many_files",
481        ] {
482            assert_eq!(
483                classify_tool_name(name),
484                ToolResultKind::FileRead,
485                "{name} should be FileRead"
486            );
487        }
488    }
489
490    #[test]
491    fn classifies_shell_and_search() {
492        assert_eq!(classify_tool_name("Bash"), ToolResultKind::Shell);
493        assert_eq!(
494            classify_tool_name("run_terminal_cmd"),
495            ToolResultKind::Shell
496        );
497        assert_eq!(classify_tool_name("Grep"), ToolResultKind::Search);
498        assert_eq!(
499            classify_tool_name("codebase_search"),
500            ToolResultKind::Search
501        );
502    }
503
504    #[test]
505    fn unknown_tool_is_other() {
506        assert_eq!(classify_tool_name("submit_pr"), ToolResultKind::Other);
507    }
508
509    #[test]
510    fn classifies_vendor_prefixed_foreign_tools() {
511        // Foreign harnesses (forge / pi) namespace their tools; the segment
512        // fallback must still route them so source reads stay protected and
513        // shell/search output stays compressible.
514        assert_eq!(classify_tool_name("forge_read"), ToolResultKind::FileRead);
515        assert_eq!(classify_tool_name("pi.read"), ToolResultKind::FileRead);
516        assert_eq!(classify_tool_name("forge_shell"), ToolResultKind::Shell);
517        assert_eq!(classify_tool_name("forge_exec"), ToolResultKind::Shell);
518        assert_eq!(classify_tool_name("fs:grep"), ToolResultKind::Search);
519    }
520
521    #[test]
522    fn segment_fallback_has_no_substring_false_positives() {
523        // Whole-word segments only: "thread" contains "read", "spread" contains
524        // "read" — neither may be misclassified as a file read.
525        assert_eq!(classify_tool_name("thread_create"), ToolResultKind::Other);
526        assert_eq!(classify_tool_name("spread_values"), ToolResultKind::Other);
527        assert_eq!(
528            classify_tool_name("readme_generator"),
529            ToolResultKind::Other
530        );
531        assert_eq!(classify_tool_name("submit_pull"), ToolResultKind::Other);
532    }
533
534    #[test]
535    fn anthropic_names_resolve_from_tool_use() {
536        let messages = vec![
537            serde_json::json!({
538                "role": "assistant",
539                "content": [
540                    {"type": "text", "text": "reading"},
541                    {"type": "tool_use", "id": "toolu_1", "name": "Read", "input": {}}
542                ]
543            }),
544            serde_json::json!({
545                "role": "user",
546                "content": [{"type": "tool_result", "tool_use_id": "toolu_1", "content": "x"}]
547            }),
548        ];
549        let names = anthropic_tool_names(&messages);
550        assert_eq!(names.get("toolu_1").map(String::as_str), Some("Read"));
551    }
552
553    #[test]
554    fn openai_names_resolve_from_tool_calls() {
555        let messages = vec![serde_json::json!({
556            "role": "assistant",
557            "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "read_file"}}]
558        })];
559        let names = openai_tool_names(&messages);
560        assert_eq!(names.get("call_1").map(String::as_str), Some("read_file"));
561    }
562
563    #[test]
564    fn responses_names_resolve_from_function_call() {
565        let input = vec![serde_json::json!({
566            "type": "function_call", "call_id": "call_1", "name": "Read", "arguments": "{}"
567        })];
568        let names = responses_tool_names(&input);
569        assert_eq!(names.get("call_1").map(String::as_str), Some("Read"));
570    }
571
572    #[test]
573    fn source_code_detected() {
574        let code = "pub fn build(cfg: &Config) -> Result<App> {\n    let mut app = App::new();\n    app.configure(cfg);\n    for route in cfg.routes() {\n        app.register(route);\n    }\n    Ok(app)\n}";
575        assert!(looks_like_source_code(code));
576    }
577
578    #[test]
579    fn command_output_not_code() {
580        let log = "$ cargo build\n   Compiling foo v0.1.0\n   Compiling bar v0.2.0\nwarning: unused variable\n    Finished dev target\nerror: could not compile";
581        assert!(!looks_like_source_code(log));
582    }
583
584    #[test]
585    fn plain_prose_not_code() {
586        let prose = "This is a normal paragraph of text.\nIt has several sentences.\nNone of them are code.\nThey are just words on lines.\nMore words follow here.";
587        assert!(!looks_like_source_code(prose));
588    }
589
590    /// Regression for GH #628: a real test file whose only "non-code-shaped"
591    /// lines are decorative separator comments must be recognized as source, so
592    /// the proxy protects it (when routed through an unrecognized tool) instead
593    /// of lossy-compressing it and silently dropping the `// ————` separators —
594    /// the exact divergence that made the model's `ctx_edit` fail on a whitespace
595    /// mismatch.
596    #[test]
597    fn test_file_with_separator_comments_is_source() {
598        let code = "import { describe, it, expect } from \"vitest\";\n\
599            \n\
600            // ————————————————————————————————————————————————————————\n\
601            // Section: arithmetic\n\
602            // ————————————————————————————————————————————————————————\n\
603            describe(\"add\", () => {\n\
604            \x20 it(\"adds\", () => {\n\
605            \x20   expect(1 + 1).toBe(2);\n\
606            \x20 });\n\
607            });\n\
608            \n\
609            // ----------------------------------------------------------\n\
610            // Section: strings\n\
611            // ----------------------------------------------------------\n\
612            describe(\"concat\", () => {\n\
613            \x20 it(\"joins\", () => {\n\
614            \x20   expect(\"a\" + \"b\").toBe(\"ab\");\n\
615            \x20 });\n\
616            });\n";
617        assert!(
618            looks_like_source_code(code),
619            "a .test.ts with decorative separator comments must read as source"
620        );
621        assert!(
622            should_protect(ToolResultKind::Other, code),
623            "an unrecognized tool returning this source must still be protected"
624        );
625    }
626
627    /// A comment-heavy source file (license header, doc block) is still source:
628    /// the neutral-comment rule must not let comments dilute the code ratio.
629    #[test]
630    fn comment_heavy_source_still_detected() {
631        let code = "/*\n\
632            \x20* Copyright (c) 2026. All rights reserved.\n\
633            \x20* This module wires the request pipeline.\n\
634            \x20*/\n\
635            export function build(cfg) {\n\
636            \x20 const app = create();\n\
637            \x20 app.use(cfg);\n\
638            \x20 return app;\n\
639            }\n";
640        assert!(looks_like_source_code(code));
641    }
642
643    /// The loosened call/closer signal must NOT start treating parenthesized log
644    /// output as code — the shell-signal veto and the punctuation requirement keep
645    /// genuine command output compressible.
646    #[test]
647    fn parenthesized_log_output_still_not_code() {
648        let log = "INFO  starting worker (pid=4211)\n\
649            processing batch (size=128) ok\n\
650            processing batch (size=64) ok\n\
651            WARN  slow response (842ms) from upstream\n\
652            done in 3.2s (0 errors)\n";
653        assert!(!looks_like_source_code(log));
654    }
655
656    /// #818: ctx_patch and ctx_refactor must be classified as FileRead
657    /// so their diff previews are never abbreviation-compressed.
658    #[test]
659    fn ctx_patch_and_refactor_classified_as_file_read() {
660        assert_eq!(classify_tool_name("ctx_patch"), ToolResultKind::FileRead);
661        assert_eq!(classify_tool_name("ctx_refactor"), ToolResultKind::FileRead);
662        assert_eq!(
663            classify_tool_name("ctx_callgraph"),
664            ToolResultKind::FileRead
665        );
666    }
667
668    /// #818: diff preview with - /+ prefixes must be protected.
669    #[test]
670    fn diff_preview_is_protected_when_kind_is_file_read() {
671        let diff = "--- src/main.rs\n\
672            - fn check_all_segments(command: &str, allowlist: &[String]) -> Result<(), ShellError> {\n\
673            -     if allowlist.is_empty() {\n\
674            -         return Ok(());\n\
675            + fn check_all_segments(cmd: &str, list: &[String]) -> Result<(), ShellError> {\n\
676            +     if list.is_empty() {\n\
677            +         return Ok(());\n";
678        assert!(
679            should_protect(ToolResultKind::FileRead, diff),
680            "diff preview must be protected when kind is FileRead"
681        );
682    }
683}