tokenix 0.22.1

Local semantic index CLI for LLM token optimization
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
use anyhow::Result;
use serde::Deserialize;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use crate::chunker::count_tokens;
use crate::query::{format_results, get_file_outline, query_index};
use crate::store::{index_staleness, log_hook_event, search_by_symbol, HookEvent};

const MIN_LINES_FOR_OUTLINE: usize = 200;
const MIN_QUERY_WORDS: usize = 3;

/// Normalized hook input used by tokenix.
///
/// Claude Code sends `tool_name` and `tool_input` on stdin.
/// GitHub Copilot hooks currently send `toolName` and `toolArgs` on stdin.
/// Older Copilot-like runners may set TOOL_NAME/TOOL_INPUT environment vars.
#[derive(Deserialize, Debug, Default)]
pub struct HookInput {
    #[serde(default)]
    pub tool_name: String,
    #[serde(default)]
    pub tool_input: serde_json::Value,
}

#[derive(Deserialize, Debug)]
struct CopilotHookInput {
    #[serde(rename = "toolName")]
    tool_name: String,
    #[serde(rename = "toolArgs", default)]
    tool_args: serde_json::Value,
}

impl HookInput {
    fn from_env() -> Option<Self> {
        // Env vars are a fallback for non-standard tools; Copilot uses stdin.
        // Only support generic TOOL_NAME/TOOL_INPUT (not COPILOT_* which can't normalize).
        let tool_name = std::env::var("TOOL_NAME").ok()?;
        let tool_input_raw = std::env::var("TOOL_INPUT").unwrap_or_default();
        let tool_input = serde_json::from_str(&tool_input_raw).unwrap_or(serde_json::Value::Null);
        Some(HookInput {
            tool_name,
            tool_input,
        })
    }

    fn from_stdin(raw: &str) -> Option<Self> {
        let clean = raw.trim_start_matches('\u{feff}').trim();
        if clean.is_empty() {
            return None;
        }
        if let Ok(input) = serde_json::from_str::<HookInput>(clean) {
            if !input.tool_name.is_empty() {
                // Canonicalize here too: newer Copilot/Codex builds send the snake_case
                // `tool_name`/`tool_input` shape with harness names like "view", which
                // must still map to Read/Grep (and `path` -> `file_path`) or the tool
                // is never recognized and interception is silently skipped.
                let tool_name = canonical_tool_name(&input.tool_name);
                let tool_input = if tool_name == "Read" {
                    normalize_read_args(input.tool_input)
                } else {
                    input.tool_input
                };
                return Some(HookInput {
                    tool_name,
                    tool_input,
                });
            }
        }
        serde_json::from_str::<CopilotHookInput>(clean)
            .ok()
            .map(|input| normalize_copilot_input(&input.tool_name, &input.tool_args))
    }
}

/// Map a harness-specific tool name to tokenix's canonical name.
///
/// Claude Code already sends `Read`/`Grep`/`Bash`; GitHub Copilot (and some Codex
/// builds) send `view`/`read`/`grep` in either the legacy `toolName` field or the
/// newer snake_case `tool_name` field. Canonicalizing in one place means
/// interception no longer depends on which field shape or casing a harness uses.
/// Unrecognized names (Bash variants, Edit, etc.) pass through unchanged.
fn canonical_tool_name(name: &str) -> String {
    match name.to_ascii_lowercase().as_str() {
        "read" | "view" => "Read".to_string(),
        "grep" => "Grep".to_string(),
        _ => name.to_string(),
    }
}

fn normalize_copilot_input(tool_name: &str, tool_args: &serde_json::Value) -> HookInput {
    let args = if let Some(raw) = tool_args.as_str() {
        serde_json::from_str(raw).unwrap_or(serde_json::Value::Null)
    } else {
        tool_args.clone()
    };

    let tool_name = canonical_tool_name(tool_name);
    let tool_input = if tool_name == "Read" {
        normalize_read_args(args)
    } else {
        args
    };
    HookInput {
        tool_name,
        tool_input,
    }
}

fn normalize_read_args(mut args: serde_json::Value) -> serde_json::Value {
    if args.get("file_path").and_then(|v| v.as_str()).is_some() {
        return args;
    }

    let path = args
        .get("path")
        .or_else(|| args.get("file"))
        .and_then(|v| v.as_str())
        .map(str::to_string);

    if let Some(path) = path {
        if let Some(obj) = args.as_object_mut() {
            obj.insert("file_path".to_string(), serde_json::Value::String(path));
        }
    }
    args
}

fn find_repo_root() -> PathBuf {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    crate::store::find_project_root(&cwd)
}

fn now_ts() -> f64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs_f64()
}

fn is_semantic_query(pattern: &str) -> bool {
    pattern.split_whitespace().count() >= MIN_QUERY_WORDS
}

/// True if `s` looks like a plain identifier (no regex metacharacters).
fn looks_like_identifier(s: &str) -> bool {
    s.len() >= 2
        && s.chars()
            .all(|c| c.is_alphanumeric() || matches!(c, '_' | ':' | '.'))
}

fn symbol_lookup(pattern: &str, repo_root: &Path) -> Option<String> {
    let conn = crate::store::open_db(repo_root, false).ok()??;
    let matches = search_by_symbol(&conn, pattern).ok()?;
    if matches.is_empty() {
        return None;
    }
    let mut lines = vec![format!(
        "<!-- tokenix: {} symbol match(es) for '{}' -->",
        matches.len(),
        pattern
    )];
    lines.push(String::new());
    for m in &matches {
        lines.push(format!(
            "{}:{} [{}] {}",
            m.path, m.start_line, m.kind, m.symbol
        ));
    }
    lines.push(String::new());
    lines.push(format!(
        "[Use Read with offset/limit or tokenix read --symbol {} to see content]",
        pattern
    ));
    Some(lines.join("\n"))
}

fn handle_read(tool_input: &serde_json::Value, repo_root: &Path) -> (bool, String, String) {
    let file_path = match tool_input["file_path"].as_str() {
        Some(p) => p,
        None => return (false, String::new(), "missing file_path".to_string()),
    };

    // Let targeted reads through (offset or limit already specified)
    if !tool_input["offset"].is_null() || !tool_input["limit"].is_null() {
        return (
            false,
            String::new(),
            "targeted read (offset/limit specified)".to_string(),
        );
    }

    let full_path = {
        let p = Path::new(file_path);
        if p.exists() {
            p.to_path_buf()
        } else {
            repo_root.join(file_path)
        }
    };

    if !full_path.exists() {
        return (
            false,
            String::new(),
            format!("file not found: {}", file_path),
        );
    }

    let content = match std::fs::read_to_string(&full_path) {
        Ok(c) => c,
        Err(_) => return (false, String::new(), format!("read error: {}", file_path)),
    };

    let line_count = content.lines().count();
    if line_count < MIN_LINES_FOR_OUTLINE {
        return (
            false,
            String::new(),
            format!(
                "small file ({} < {} lines)",
                line_count, MIN_LINES_FOR_OUTLINE
            ),
        );
    }

    let outline = match get_file_outline(&full_path) {
        Some(o) => o,
        None => {
            return (
                false,
                String::new(),
                "failed to generate outline".to_string(),
            )
        }
    };

    let rel = full_path
        .strip_prefix(repo_root)
        .unwrap_or(&full_path)
        .to_string_lossy()
        .replace('\\', "/");

    let ext = full_path.extension().and_then(|e| e.to_str()).unwrap_or("");
    let is_code = matches!(
        ext,
        "rs" | "py" | "ts" | "tsx" | "js" | "jsx" | "mjs" | "cjs" | "go"
    );

    if !is_code {
        return (
            false,
            String::new(),
            format!("unsupported language: .{}", ext),
        );
    }

    let msg = format!(
        "{}\n\n[tokenix] File has {} lines. Showing symbol outline above.\n\
        To read a specific symbol: tokenix read {} --symbol <name>\n\
        To read specific lines:   use Read with offset/limit parameters.",
        outline, line_count, rel
    );
    (true, msg, "generated symbol outline".to_string())
}

/// Returns a path to use as a soft lock file for concurrent embed protection.
fn embed_lock_path() -> Option<std::path::PathBuf> {
    Some(dirs::cache_dir()?.join("tokenix").join("embed.lock"))
}

/// Best-effort concurrency guard for the ONNX embed call.
///
/// The fastembed model uses ~293 MB per process (130 MB model + ORT runtime).
/// If Claude Code fires parallel Grep hooks, each would load a separate model instance.
/// This guard makes concurrent semantic Greps fall through (exit 0) so the original
/// grep runs instead — limiting peak tokenix memory to one model instance at a time.
///
/// Implementation: timestamp file. Not atomically safe, but good enough for the
/// typical pattern of a few concurrent hooks per second. Stale locks (>30s) are
/// automatically overridden so a crashed process never permanently blocks the feature.
fn try_acquire_embed_slot() -> bool {
    let path = match embed_lock_path() {
        Some(p) => p,
        None => return true, // can't determine path → proceed anyway
    };

    if path.exists() {
        let stale = std::fs::metadata(&path)
            .ok()
            .and_then(|m| m.modified().ok())
            .and_then(|t| t.elapsed().ok())
            .map(|e| e.as_secs() >= 30)
            .unwrap_or(true);

        if !stale {
            return false; // another embed is in progress
        }
    }

    // Claim the slot (best-effort write — race window is tiny)
    let _ = std::fs::create_dir_all(path.parent().unwrap_or(&path));
    let _ = std::fs::write(&path, std::process::id().to_string());
    true
}

fn release_embed_slot() {
    if let Some(path) = embed_lock_path() {
        let _ = std::fs::remove_file(path);
    }
}

fn handle_grep(tool_input: &serde_json::Value, repo_root: &Path) -> (bool, String, String) {
    let pattern = match tool_input["pattern"].as_str() {
        Some(p) => p,
        None => return (false, String::new(), "missing pattern".to_string()),
    };

    // Short identifier-like patterns: try index symbol lookup before falling through
    if !is_semantic_query(pattern) {
        if looks_like_identifier(pattern) {
            if let Some(output) = symbol_lookup(pattern, repo_root) {
                return (
                    true,
                    output,
                    format!("matched symbol exact lookup: {}", pattern),
                );
            }
        }
        return (
            false,
            String::new(),
            format!("lexical query: '{}'", pattern),
        );
    }

    // Try daemon first: model stays resident, ~30ms vs ~430ms cold embed.
    if let Some(output) =
        crate::daemon::daemon_search_with_autostart(repo_root, pattern, 20, 2500, None)
    {
        return (true, output, "semantic search via daemon".to_string());
    }

    // Fallback: direct embed (daemon not running or failed to start).
    // Guard prevents N×293MB spikes from parallel hook processes.
    if !try_acquire_embed_slot() {
        return (
            false,
            String::new(),
            "ONNX embed model slot locked".to_string(),
        );
    }
    let results = match query_index(repo_root, pattern, 2500, 20, None) {
        Ok(Some(r)) if !r.is_empty() => r,
        _ => {
            release_embed_slot();
            return (
                false,
                String::new(),
                "semantic search returned empty results".to_string(),
            );
        }
    };
    release_embed_slot();
    (
        true,
        format_results(&results, pattern),
        "semantic search via in-process embed".to_string(),
    )
}

fn estimate_original_tokens(
    tool_name: &str,
    tool_input: &serde_json::Value,
    repo_root: &Path,
) -> i64 {
    if tool_name == "Read" {
        if let Some(fp) = tool_input["file_path"].as_str() {
            let p = Path::new(fp);
            let full = if p.exists() {
                p.to_path_buf()
            } else {
                repo_root.join(fp)
            };
            if let Ok(content) = std::fs::read_to_string(&full) {
                return count_tokens(&content) as i64;
            }
        }
    }
    800
}

/// Build the PreToolUse JSON output that rewrites a Bash command's input.
/// `hookEventName` is required by Claude Code or the whole `hookSpecificOutput`
/// is ignored and the rewrite silently does not apply.
fn bash_rewrite_output(rewritten: &str, reason: &str) -> serde_json::Value {
    serde_json::json!({
        "hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "permissionDecision": "allow",
            "permissionDecisionReason": reason,
            "updatedInput": {
                "command": rewritten,
                "CommandLine": rewritten,
                "commandLine": rewritten,
                "command_line": rewritten,
            }
        }
    })
}

fn is_bash_tool(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    matches!(
        lower.as_str(),
        "bash"
            | "powershell"
            | "shell"
            | "run_shell_command"
            | "default_api:run_shell_command"
            | "run_command"
            | "default_api:run_command"
    )
}

pub fn run_hook() -> Result<()> {
    // Read input: prefer env vars (Copilot), fall back to stdin (Claude Code / Codex)
    let raw_stdin = std::io::read_to_string(std::io::stdin()).unwrap_or_default();

    let input = HookInput::from_env()
        .or_else(|| HookInput::from_stdin(&raw_stdin))
        .unwrap_or_default();

    // Unknown or unsupported tool: pass through silently.
    let is_bash = is_bash_tool(&input.tool_name);
    if input.tool_name != "Read" && input.tool_name != "Grep" && !is_bash {
        std::process::exit(0);
    }

    let repo_root = find_repo_root();

    if is_bash {
        let command = input.tool_input["command"]
            .as_str()
            .or_else(|| input.tool_input["CommandLine"].as_str())
            .or_else(|| input.tool_input["commandLine"].as_str())
            .or_else(|| input.tool_input["command_line"].as_str())
            .unwrap_or("")
            .trim();

        if command.is_empty() {
            std::process::exit(0);
        }

        // Avoid infinite recursion: do not rewrite if it's already a tokenix command execution
        if command.contains("tokenix") {
            std::process::exit(0);
        }

        // 1. Optimize git status -> git status --short. Let it pass through natively
        // on the second pass when the short flag is already present.
        let is_short_git_status = (command.starts_with("git status")
            || command.starts_with("git  status"))
            && (command.contains("-s") || command.contains("--short"));
        if is_short_git_status {
            std::process::exit(0);
        }

        let status_re = regex::Regex::new(r"^git\s+status(\s+.*)?$").unwrap();
        if status_re.is_match(command) && !command.contains("-") {
            let trimmed = command.strip_prefix("git status").unwrap_or("").trim();
            let rewritten = if trimmed.is_empty() {
                "git status --short".to_string()
            } else {
                format!("git status --short {}", trimmed)
            };

            let out = bash_rewrite_output(
                &rewritten,
                "rewrite git status to git status --short for token efficiency",
            );

            let _ = log_hook_event(
                &repo_root,
                &HookEvent {
                    ts: now_ts(),
                    tool: "Bash".to_string(),
                    action: "intercepted".to_string(),
                    phase: "pre".to_string(),
                    reason: "rewrote git status to git status --short".to_string(),
                    saved_tokens: 0,
                    actual_tokens: 0,
                    original_estimate: 0,
                    input_preview: command.chars().take(200).collect(),
                    command: command.to_string(),
                },
            );

            println!("{}", serde_json::to_string(&out).unwrap_or_default());
            std::process::exit(0);
        }

        // 2. Otherwise check for other active filters to wrap in tokenix run
        let filters = crate::filters::load_all_filters();
        let unwrapped =
            crate::filters::unwrap_shell_runner(command).unwrap_or_else(|| command.to_string());

        if crate::filters::find_filter(&unwrapped, &filters).is_some() {
            let exe_path = std::env::current_exe()
                .map(|p| p.to_string_lossy().replace('\\', "/"))
                .unwrap_or_else(|_| "tokenix".to_string());

            let rewritten = format!("{} run {:?}", exe_path, command);

            let out = bash_rewrite_output(&rewritten, "wrapped in tokenix compression run");

            let _ = log_hook_event(
                &repo_root,
                &HookEvent {
                    ts: now_ts(),
                    tool: "Bash".to_string(),
                    action: "intercepted".to_string(),
                    phase: "pre".to_string(),
                    reason: "rewrote command to tokenix run".to_string(),
                    saved_tokens: 0,
                    actual_tokens: 0,
                    original_estimate: 0,
                    input_preview: command.chars().take(200).collect(),
                    command: command.to_string(),
                },
            );

            println!("{}", serde_json::to_string(&out).unwrap_or_default());
            std::process::exit(0);
        }

        std::process::exit(0);
    }

    let staleness = index_staleness(&repo_root);

    if staleness.stale {
        let _ = log_hook_event(
            &repo_root,
            &HookEvent {
                ts: now_ts(),
                tool: input.tool_name,
                action: "pass".to_string(),
                phase: "pre".to_string(),
                reason: staleness.reason,
                saved_tokens: 0,
                actual_tokens: 0,
                original_estimate: 0,
                input_preview: String::new(),
                command: String::new(),
            },
        );
        std::process::exit(0);
    }

    let (intercepted, output, reason) = match input.tool_name.as_str() {
        "Read" => handle_read(&input.tool_input, &repo_root),
        "Grep" => handle_grep(&input.tool_input, &repo_root),
        _ => (false, String::new(), "unsupported tool".to_string()),
    };

    if !intercepted {
        let _ = log_hook_event(
            &repo_root,
            &HookEvent {
                ts: now_ts(),
                tool: input.tool_name,
                action: "pass".to_string(),
                phase: "pre".to_string(),
                reason,
                saved_tokens: 0,
                actual_tokens: 0,
                original_estimate: 0,
                input_preview: String::new(),
                command: String::new(),
            },
        );
        std::process::exit(0);
    }

    let original_tokens = estimate_original_tokens(&input.tool_name, &input.tool_input, &repo_root);
    let actual_tokens = count_tokens(&output) as i64;
    let saved = (original_tokens - actual_tokens).max(0);

    let _ = log_hook_event(
        &repo_root,
        &HookEvent {
            ts: now_ts(),
            tool: input.tool_name.clone(),
            action: "intercepted".to_string(),
            phase: "pre".to_string(),
            reason,
            saved_tokens: saved,
            actual_tokens,
            original_estimate: original_tokens,
            input_preview: raw_stdin.chars().take(200).collect(),
            command: String::new(),
        },
    );

    eprintln!("{}", output);
    std::process::exit(2);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_claude_input() {
        let raw = r#"{"tool_name":"Read","tool_input":{"file_path":"src/main.rs"}}"#;
        let input = HookInput::from_stdin(raw).unwrap();
        assert_eq!(input.tool_name, "Read");
        assert_eq!(input.tool_input["file_path"], "src/main.rs");
    }

    #[test]
    fn parses_copilot_view_input() {
        let raw = r#"{"toolName":"view","toolArgs":"{\"path\":\"src/main.rs\"}"}"#;
        let input = HookInput::from_stdin(raw).unwrap();
        assert_eq!(input.tool_name, "Read");
        assert_eq!(input.tool_input["file_path"], "src/main.rs");
    }

    #[test]
    fn empty_stdin_returns_none() {
        assert!(HookInput::from_stdin("").is_none());
        assert!(HookInput::from_stdin("   ").is_none());
    }

    #[test]
    fn bom_prefix_stripped() {
        let raw =
            "\u{feff}{\"tool_name\":\"Grep\",\"tool_input\":{\"pattern\":\"how does auth work\"}}";
        let input = HookInput::from_stdin(raw).unwrap();
        assert_eq!(input.tool_name, "Grep");
    }

    #[test]
    fn unknown_tool_parses_as_is() {
        let raw = r#"{"tool_name":"Edit","tool_input":{"file_path":"x.rs"}}"#;
        let input = HookInput::from_stdin(raw).unwrap();
        assert_eq!(input.tool_name, "Edit");
    }

    #[test]
    fn is_semantic_query_requires_3_words() {
        assert!(!is_semantic_query("fn main"));
        assert!(!is_semantic_query("embed_query"));
        assert!(is_semantic_query("how does embedding work"));
        assert!(is_semantic_query("database connection pool"));
    }

    #[test]
    fn looks_like_identifier_rules() {
        assert!(looks_like_identifier("embed_query"));
        assert!(looks_like_identifier("MyStruct::new"));
        assert!(!looks_like_identifier("a")); // too short
        assert!(!looks_like_identifier("foo bar")); // has space
        assert!(!looks_like_identifier("fn.*main")); // regex meta
    }

    #[test]
    fn copilot_grep_normalized() {
        let raw = r#"{"toolName":"grep","toolArgs":{"pattern":"how does auth work"}}"#;
        let input = HookInput::from_stdin(raw).unwrap();
        assert_eq!(input.tool_name, "Grep");
        assert_eq!(input.tool_input["pattern"], "how does auth work");
    }

    #[test]
    fn copilot_read_with_path_key() {
        let raw = r#"{"toolName":"view","toolArgs":{"path":"src/lib.rs"}}"#;
        let input = HookInput::from_stdin(raw).unwrap();
        assert_eq!(input.tool_name, "Read");
        assert_eq!(input.tool_input["file_path"], "src/lib.rs");
    }

    #[test]
    fn snake_case_view_normalized_to_read() {
        // Newer Copilot/Codex builds use the snake_case shape with harness tool
        // names; it must canonicalize just like the legacy camelCase shape does.
        let raw = r#"{"tool_name":"view","tool_input":{"path":"src/main.rs"}}"#;
        let input = HookInput::from_stdin(raw).unwrap();
        assert_eq!(input.tool_name, "Read");
        assert_eq!(input.tool_input["file_path"], "src/main.rs");
    }

    #[test]
    fn bash_rewrite_output_has_required_hook_event_name() {
        // Claude Code ignores `hookSpecificOutput` (so the rewrite never applies)
        // unless `hookEventName` is present and set to "PreToolUse".
        let out = bash_rewrite_output("git status --short", "test reason");
        let hso = &out["hookSpecificOutput"];
        assert_eq!(hso["hookEventName"], "PreToolUse");
        assert_eq!(hso["permissionDecision"], "allow");
        assert_eq!(hso["permissionDecisionReason"], "test reason");
        assert_eq!(hso["updatedInput"]["command"], "git status --short");
        // Aliases for non-Claude harnesses (Copilot/Codex) carry the same value.
        assert_eq!(hso["updatedInput"]["CommandLine"], "git status --short");
        assert_eq!(hso["updatedInput"]["commandLine"], "git status --short");
        assert_eq!(hso["updatedInput"]["command_line"], "git status --short");
    }
}