1use crate::compound_lexer;
2use crate::rewrite_registry;
3use std::io::Read;
4use std::sync::mpsc;
5use std::time::Duration;
6
7const HOOK_STDIN_TIMEOUT: Duration = Duration::from_secs(3);
8
9pub fn handle_observe() {
17 if is_disabled() {
18 return;
19 }
20 let Some(input) = read_stdin_with_timeout(HOOK_STDIN_TIMEOUT) else {
21 return;
22 };
23 let Some(event) = parse_observe_event(&input) else {
24 return;
25 };
26 append_radar_event(&event);
27}
28
29#[derive(serde::Serialize)]
30struct ObserveEvent {
31 ts: u64,
32 event_type: &'static str,
33 tokens: usize,
34 #[serde(skip_serializing_if = "Option::is_none")]
35 tool_name: Option<String>,
36 #[serde(skip_serializing_if = "Option::is_none")]
37 detail: Option<String>,
38 #[serde(skip_serializing_if = "Option::is_none")]
39 content: Option<String>,
40 #[serde(skip_serializing_if = "Option::is_none")]
41 model: Option<String>,
42 #[serde(skip_serializing_if = "Option::is_none")]
43 conversation_id: Option<String>,
44}
45
46const MAX_CONTENT_CHARS: usize = 50_000;
47
48fn parse_observe_event(input: &str) -> Option<ObserveEvent> {
49 let v: serde_json::Value = serde_json::from_str(input).ok()?;
50
51 let ts = std::time::SystemTime::now()
52 .duration_since(std::time::UNIX_EPOCH)
53 .unwrap_or_default()
54 .as_secs();
55
56 let model = v
57 .get("model")
58 .and_then(|m| m.as_str())
59 .filter(|m| !m.is_empty())
60 .map(String::from);
61 let conversation_id = v
62 .get("conversation_id")
63 .and_then(|c| c.as_str())
64 .filter(|c| !c.is_empty())
65 .map(String::from);
66
67 let transcript_path = v
68 .get("transcript_path")
69 .and_then(|t| t.as_str())
70 .filter(|t| !t.is_empty())
71 .map(String::from);
72
73 if let Some(ref m) = model {
74 persist_detected_model(m);
75 }
76 if let Some(ref tp) = transcript_path {
77 persist_transcript_path(tp, conversation_id.as_deref());
78 }
79
80 let mut event = detect_event_type(&v, ts)?;
81 event.model = model;
82 event.conversation_id = conversation_id;
83 Some(event)
84}
85
86fn detect_event_type(v: &serde_json::Value, ts: u64) -> Option<ObserveEvent> {
87 if let Some(result) = v
88 .get("result_json")
89 .or_else(|| v.get("result"))
90 .or_else(|| v.get("tool_response"))
91 .or_else(|| v.get("tool_output"))
92 {
93 let tool = v
94 .get("tool_name")
95 .and_then(|t| t.as_str())
96 .unwrap_or("unknown");
97 let tokens = estimate_tokens_json(result);
98 let content_str = match result {
99 serde_json::Value::String(s) => s.clone(),
100 other => other.to_string(),
101 };
102 return Some(ObserveEvent {
103 ts,
104 event_type: "mcp_call",
105 tokens,
106 tool_name: Some(tool.to_string()),
107 detail: v
108 .get("server_name")
109 .and_then(|s| s.as_str())
110 .map(String::from),
111 content: Some(cap_content(&content_str)),
112 model: None,
113 conversation_id: None,
114 });
115 }
116
117 if let Some(output) = v.get("output") {
118 let cmd = v
119 .get("command")
120 .and_then(|c| c.as_str())
121 .unwrap_or("")
122 .to_string();
123 let tokens = estimate_tokens_value(output);
124 let out_str = match output {
125 serde_json::Value::String(s) => s.clone(),
126 other => other.to_string(),
127 };
128 return Some(ObserveEvent {
129 ts,
130 event_type: "shell",
131 tokens,
132 tool_name: None,
133 detail: Some(truncate_str(&cmd, 80)),
134 content: Some(cap_content(&format!("$ {cmd}\n{out_str}"))),
135 model: None,
136 conversation_id: None,
137 });
138 }
139
140 if v.get("content").is_some() && v.get("file_path").is_some() {
141 let path = v
142 .get("file_path")
143 .and_then(|p| p.as_str())
144 .unwrap_or("")
145 .to_string();
146 let file_content = v.get("content").and_then(|c| c.as_str()).unwrap_or("");
147 let tokens = file_content.len() / 4;
148 return Some(ObserveEvent {
149 ts,
150 event_type: "file_read",
151 tokens,
152 tool_name: None,
153 detail: Some(truncate_str(&path, 120)),
154 content: Some(cap_content(file_content)),
155 model: None,
156 conversation_id: None,
157 });
158 }
159
160 if let Some(text) = v.get("text").and_then(|t| t.as_str()) {
161 let has_duration = v.get("duration_ms").is_some();
162 let event_type = if has_duration {
163 "thinking"
164 } else {
165 "agent_response"
166 };
167 let tokens = text.len() / 4;
168 return Some(ObserveEvent {
169 ts,
170 event_type,
171 tokens,
172 tool_name: None,
173 detail: None,
174 content: Some(cap_content(text)),
175 model: None,
176 conversation_id: None,
177 });
178 }
179
180 if let Some(prompt) = v.get("prompt").and_then(|p| p.as_str()) {
181 let tokens = prompt.len() / 4;
182 let mut full = prompt.to_string();
183 if let Some(attachments) = v.get("attachments").and_then(|a| a.as_array()) {
184 if !attachments.is_empty() {
185 full.push_str(&format!("\n\n[{} attachments]", attachments.len()));
186 for att in attachments {
187 if let Some(name) = att.get("name").and_then(|n| n.as_str()) {
188 full.push_str(&format!("\n - {name}"));
189 }
190 }
191 }
192 }
193 return Some(ObserveEvent {
194 ts,
195 event_type: "user_message",
196 tokens,
197 tool_name: None,
198 detail: v
199 .get("attachments")
200 .and_then(|a| a.as_array())
201 .map(|a| format!("{} attachments", a.len())),
202 content: Some(cap_content(&full)),
203 model: None,
204 conversation_id: None,
205 });
206 }
207
208 if v.get("tool_name").is_some() || v.get("tool_input").is_some() {
209 let tool = v
210 .get("tool_name")
211 .and_then(|t| t.as_str())
212 .unwrap_or("unknown")
213 .to_string();
214 let is_lctx = tool.starts_with("ctx_") || tool.starts_with("mcp__lean-ctx__");
215 let tokens = v.get("tool_input").map_or(0, estimate_tokens_json);
216 let input_str = v
217 .get("tool_input")
218 .map(std::string::ToString::to_string)
219 .unwrap_or_default();
220 return Some(ObserveEvent {
221 ts,
222 event_type: if is_lctx { "mcp_call" } else { "native_tool" },
223 tokens,
224 tool_name: Some(tool),
225 detail: None,
226 content: if input_str.is_empty() {
227 None
228 } else {
229 Some(cap_content(&input_str))
230 },
231 model: None,
232 conversation_id: None,
233 });
234 }
235
236 if v.get("session_id").is_some() {
237 return Some(ObserveEvent {
238 ts,
239 event_type: "session",
240 tokens: 0,
241 tool_name: None,
242 detail: v
243 .get("session_id")
244 .and_then(|s| s.as_str())
245 .map(String::from),
246 content: None,
247 model: None,
248 conversation_id: None,
249 });
250 }
251
252 let is_compaction = v.get("compaction").is_some()
253 || v.get("messages_count").is_some()
254 || v.get("event")
255 .and_then(|e| e.as_str())
256 .is_some_and(|e| e == "compaction" || e == "compact");
257 if is_compaction {
258 return Some(ObserveEvent {
259 ts,
260 event_type: "compaction",
261 tokens: 0,
262 tool_name: None,
263 detail: None,
264 content: None,
265 model: None,
266 conversation_id: None,
267 });
268 }
269
270 None
271}
272
273fn estimate_tokens_json(v: &serde_json::Value) -> usize {
274 match v {
275 serde_json::Value::String(s) => s.len() / 4,
276 _ => v.to_string().len() / 4,
277 }
278}
279
280fn estimate_tokens_value(v: &serde_json::Value) -> usize {
281 match v {
282 serde_json::Value::String(s) => s.len() / 4,
283 _ => v.to_string().len() / 4,
284 }
285}
286
287fn persist_detected_model(model: &str) {
288 let m = model.to_lowercase();
289 let is_bg_model = m.contains("flash")
290 || m.contains("mini")
291 || m.contains("haiku")
292 || m.contains("fast")
293 || m.contains("nano")
294 || m.contains("small");
295 if is_bg_model {
296 return;
297 }
298
299 let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
300 return;
301 };
302 let path = data_dir.join("detected_model.json");
303 let ts = std::time::SystemTime::now()
304 .duration_since(std::time::UNIX_EPOCH)
305 .unwrap_or_default()
306 .as_secs();
307 let window = model_context_window(model);
308 let payload = serde_json::json!({
309 "model": model,
310 "window_size": window,
311 "detected_at": ts,
312 });
313 if let Ok(json) = serde_json::to_string_pretty(&payload) {
314 let tmp = path.with_extension("tmp");
315 if std::fs::write(&tmp, &json).is_ok() {
316 let _ = std::fs::rename(&tmp, &path);
317 }
318 }
319}
320
321pub fn model_context_window(model: &str) -> usize {
322 crate::core::model_registry::context_window_for_model(model)
323}
324
325pub fn load_detected_model() -> Option<(String, usize)> {
326 let data_dir = crate::core::data_dir::lean_ctx_data_dir().ok()?;
327 let path = data_dir.join("detected_model.json");
328 let content = std::fs::read_to_string(&path).ok()?;
329 let v: serde_json::Value = serde_json::from_str(&content).ok()?;
330 let model = v.get("model")?.as_str()?.to_string();
331 let window = v.get("window_size")?.as_u64()? as usize;
332 let detected_at = v.get("detected_at")?.as_u64()?;
333 let now = std::time::SystemTime::now()
334 .duration_since(std::time::UNIX_EPOCH)
335 .unwrap_or_default()
336 .as_secs();
337 if now.saturating_sub(detected_at) > 7200 {
338 return None;
339 }
340 Some((model, window))
341}
342
343fn persist_transcript_path(path: &str, conversation_id: Option<&str>) {
344 let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
345 return;
346 };
347 let meta_path = data_dir.join("active_transcript.json");
348 let ts = std::time::SystemTime::now()
349 .duration_since(std::time::UNIX_EPOCH)
350 .unwrap_or_default()
351 .as_secs();
352 let payload = serde_json::json!({
353 "transcript_path": path,
354 "conversation_id": conversation_id,
355 "updated_at": ts,
356 });
357 if let Ok(json) = serde_json::to_string_pretty(&payload) {
358 let tmp = meta_path.with_extension("tmp");
359 if std::fs::write(&tmp, &json).is_ok() {
360 let _ = std::fs::rename(&tmp, &meta_path);
361 }
362 }
363}
364
365pub fn load_active_transcript() -> Option<(String, Option<String>)> {
366 let data_dir = crate::core::data_dir::lean_ctx_data_dir().ok()?;
367 let path = data_dir.join("active_transcript.json");
368 let content = std::fs::read_to_string(&path).ok()?;
369 let v: serde_json::Value = serde_json::from_str(&content).ok()?;
370 let tp = v.get("transcript_path")?.as_str()?.to_string();
371 let conv = v
372 .get("conversation_id")
373 .and_then(|c| c.as_str())
374 .map(String::from);
375 let updated = v.get("updated_at")?.as_u64()?;
376 let now = std::time::SystemTime::now()
377 .duration_since(std::time::UNIX_EPOCH)
378 .unwrap_or_default()
379 .as_secs();
380 if now.saturating_sub(updated) > 7200 {
381 return None;
382 }
383 Some((tp, conv))
384}
385
386fn cap_content(s: &str) -> String {
387 if s.len() <= MAX_CONTENT_CHARS {
388 s.to_string()
389 } else {
390 let truncated = safe_truncate(s, MAX_CONTENT_CHARS);
391 format!("{}…\n\n[truncated: {} total chars]", truncated, s.len())
392 }
393}
394
395fn truncate_str(s: &str, max: usize) -> String {
396 if s.len() <= max {
397 s.to_string()
398 } else {
399 format!("{}...", safe_truncate(s, max))
400 }
401}
402
403fn safe_truncate(s: &str, max: usize) -> &str {
405 if max >= s.len() {
406 return s;
407 }
408 let mut end = max;
409 while end > 0 && !s.is_char_boundary(end) {
410 end -= 1;
411 }
412 &s[..end]
413}
414
415fn append_radar_event(event: &ObserveEvent) {
416 let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
417 return;
418 };
419 let radar_path = data_dir.join("context_radar.jsonl");
420
421 if event.event_type == "session" {
422 if let Ok(meta) = std::fs::metadata(&radar_path) {
423 const MAX_RADAR_SIZE: u64 = 10 * 1024 * 1024; if meta.len() > MAX_RADAR_SIZE {
425 let prev = data_dir.join("context_radar.prev.jsonl");
426 let _ = std::fs::rename(&radar_path, &prev);
427 }
428 }
429 }
430
431 let Ok(line) = serde_json::to_string(event) else {
432 return;
433 };
434
435 use std::fs::OpenOptions;
436 use std::io::Write;
437 if let Ok(mut f) = OpenOptions::new()
438 .create(true)
439 .append(true)
440 .open(&radar_path)
441 {
442 let _ = writeln!(f, "{line}");
443 }
444}
445
446fn is_disabled() -> bool {
447 std::env::var("LEAN_CTX_DISABLED").is_ok()
448}
449
450fn is_harden_active() -> bool {
451 matches!(std::env::var("LEAN_CTX_HARDEN"), Ok(v) if v.trim() == "1")
452}
453
454fn is_quiet() -> bool {
455 matches!(std::env::var("LEAN_CTX_QUIET"), Ok(v) if v.trim() == "1")
456}
457
458pub fn mark_hook_environment() {
461 std::env::set_var("LEAN_CTX_HOOK_CHILD", "1");
462}
463
464pub fn arm_watchdog(timeout: Duration) {
469 std::thread::spawn(move || {
470 std::thread::sleep(timeout);
471 eprintln!(
472 "[lean-ctx hook] watchdog timeout after {}s — force exit",
473 timeout.as_secs()
474 );
475 std::process::exit(1);
476 });
477}
478
479fn read_stdin_with_timeout(timeout: Duration) -> Option<String> {
481 let (tx, rx) = mpsc::channel();
482 std::thread::spawn(move || {
483 let mut buf = String::new();
484 let result = std::io::stdin().read_to_string(&mut buf);
485 let _ = tx.send(result.ok().map(|_| buf));
486 });
487 match rx.recv_timeout(timeout) {
488 Ok(Some(s)) if !s.is_empty() => Some(s),
489 _ => None,
490 }
491}
492
493fn build_dual_deny_output(reason: &str) -> String {
494 serde_json::json!({
495 "permission": "deny",
496 "reason": reason,
497 "hookSpecificOutput": {
498 "hookEventName": "PreToolUse",
499 "permissionDecision": "deny",
500 }
501 })
502 .to_string()
503}
504
505fn build_dual_allow_output() -> String {
506 serde_json::json!({
507 "permission": "allow",
508 "hookSpecificOutput": {
509 "hookEventName": "PreToolUse",
510 "permissionDecision": "allow"
511 }
512 })
513 .to_string()
514}
515
516fn build_dual_rewrite_output(tool_input: Option<&serde_json::Value>, rewritten: &str) -> String {
517 let updated_input = if let Some(obj) = tool_input.and_then(|v| v.as_object()) {
518 let mut m = obj.clone();
519 m.insert(
520 "command".to_string(),
521 serde_json::Value::String(rewritten.to_string()),
522 );
523 serde_json::Value::Object(m)
524 } else {
525 serde_json::json!({ "command": rewritten })
526 };
527
528 serde_json::json!({
529 "permission": "allow",
531 "updated_input": updated_input,
532 "hookSpecificOutput": {
534 "hookEventName": "PreToolUse",
535 "permissionDecision": "allow",
536 "updatedInput": {
537 "command": rewritten
538 }
539 }
540 })
541 .to_string()
542}
543
544pub fn handle_rewrite() {
545 if is_disabled() {
546 return;
547 }
548 let binary = resolve_binary();
549 let Some(input) = read_stdin_with_timeout(HOOK_STDIN_TIMEOUT) else {
550 return;
551 };
552
553 let v: serde_json::Value = if let Ok(v) = serde_json::from_str(&input) {
554 v
555 } else {
556 print!("{}", build_dual_deny_output("invalid JSON hook payload"));
557 return;
558 };
559
560 let tool = v.get("tool_name").and_then(|t| t.as_str());
561 let Some(tool_name) = tool else {
562 return;
563 };
564
565 let is_shell_tool = matches!(
567 tool_name,
568 "Bash" | "bash" | "Shell" | "shell" | "runInTerminal" | "run_in_terminal" | "terminal"
569 );
570 if !is_shell_tool {
571 return;
572 }
573
574 let tool_input = v.get("tool_input");
575 let Some(cmd) = tool_input
576 .and_then(|ti| ti.get("command"))
577 .and_then(|c| c.as_str())
578 .or_else(|| v.get("command").and_then(|c| c.as_str()))
579 else {
580 return;
581 };
582
583 if let Some(rewritten) = rewrite_candidate(cmd, &binary) {
584 print!("{}", build_dual_rewrite_output(tool_input, &rewritten));
585 } else {
586 print!("{}", build_dual_allow_output());
588 }
589}
590
591fn is_rewritable(cmd: &str) -> bool {
592 rewrite_registry::is_rewritable_command(cmd)
593}
594
595fn wrap_single_command(cmd: &str, binary: &str) -> String {
596 if cfg!(windows) {
597 let escaped = cmd.replace('"', "\\\"");
598 format!("{binary} -c \"{escaped}\"")
599 } else {
600 let shell_escaped = cmd.replace('\'', "'\\''");
601 format!("{binary} -c '{shell_escaped}'")
602 }
603}
604
605fn rewrite_candidate(cmd: &str, binary: &str) -> Option<String> {
606 if cmd.starts_with("lean-ctx ") || cmd.starts_with(&format!("{binary} ")) {
607 return None;
608 }
609
610 if cmd.contains("<<") {
613 return None;
614 }
615
616 if let Some(rewritten) = rewrite_file_read_command(cmd, binary) {
617 return Some(rewritten);
618 }
619
620 if let Some(rewritten) = rewrite_search_command(cmd, binary) {
621 return Some(rewritten);
622 }
623
624 if let Some(rewritten) = rewrite_dir_list_command(cmd, binary) {
625 return Some(rewritten);
626 }
627
628 if let Some(rewritten) = build_rewrite_compound(cmd, binary) {
629 return Some(rewritten);
630 }
631
632 if is_rewritable(cmd) {
633 return Some(wrap_single_command(cmd, binary));
634 }
635
636 None
637}
638
639fn rewrite_file_read_command(cmd: &str, binary: &str) -> Option<String> {
642 if !rewrite_registry::is_file_read_command(cmd) {
643 return None;
644 }
645
646 if cmd.contains('|') || cmd.contains("&&") || cmd.contains("||") || cmd.contains(';') {
648 return None;
649 }
650
651 if cmd.contains(">&") || cmd.contains(">>") || cmd.contains(" >") {
653 return None;
654 }
655
656 let parts = shell_tokenize(cmd);
657 if parts.len() < 2 {
658 return None;
659 }
660
661 match parts[0].as_str() {
662 "cat" => {
663 let path = parts[1..].join(" ");
664 if is_outside_project_path(&path) {
665 return None;
666 }
667 Some(format!("{binary} read {}", shell_quote(&path)))
668 }
669 "head" => {
670 let refs: Vec<&str> = parts[1..].iter().map(String::as_str).collect();
671 let (n, path) = parse_head_tail_args(&refs);
672 let path = path?;
673 if is_outside_project_path(path) {
674 return None;
675 }
676 let qp = shell_quote(path);
677 match n {
678 Some(lines) => Some(format!("{binary} read {qp} -m lines:1-{lines}")),
679 None => Some(format!("{binary} read {qp} -m lines:1-10")),
680 }
681 }
682 "tail" => {
683 let refs: Vec<&str> = parts[1..].iter().map(String::as_str).collect();
684 let (n, path) = parse_head_tail_args(&refs);
685 let path = path?;
686 if is_outside_project_path(path) {
687 return None;
688 }
689 let qp = shell_quote(path);
690 let lines = n.unwrap_or(10);
691 Some(format!("{binary} read {qp} -m lines:-{lines}"))
692 }
693 _ => None,
694 }
695}
696
697fn is_outside_project_path(path: &str) -> bool {
701 let trimmed = path.trim();
702
703 if trimmed.starts_with('~') {
705 return true;
706 }
707
708 if trimmed.starts_with('$') {
710 return true;
711 }
712
713 if trimmed.starts_with("/proc/")
715 || trimmed.starts_with("/sys/")
716 || trimmed.starts_with("/dev/")
717 || trimmed.starts_with("/tmp/")
718 || trimmed.starts_with("/var/")
719 {
720 return true;
721 }
722
723 if trimmed.starts_with('/') {
727 if trimmed.contains("/Library/") || trimmed.contains("/.config/") {
729 return true;
730 }
731 if trimmed.contains("/.lean-ctx/") || trimmed.contains("/lean-ctx/logs/") {
733 return true;
734 }
735 }
736
737 false
738}
739
740fn rewrite_search_command(cmd: &str, binary: &str) -> Option<String> {
742 let parts = shell_tokenize(cmd);
743 if parts.first().map(String::as_str) != Some("rg") {
744 return None;
745 }
746 if parts.len() < 2 || parts.len() > 3 {
747 return None;
748 }
749 if parts[1].starts_with('-') {
750 return None;
751 }
752 let pattern = &parts[1];
753 match parts.get(2) {
754 Some(p) if p.starts_with('-') => None,
755 Some(p) => Some(format!("{binary} grep {pattern} {}", shell_quote(p))),
756 None => Some(format!("{binary} grep {pattern}")),
757 }
758}
759
760fn rewrite_dir_list_command(cmd: &str, binary: &str) -> Option<String> {
762 let parts = shell_tokenize(cmd);
763 if parts.first().map(String::as_str) != Some("ls") {
764 return None;
765 }
766 match parts.len() {
767 1 => Some(format!("{binary} ls")),
768 2 if !parts[1].starts_with('-') => Some(format!("{binary} ls {}", shell_quote(&parts[1]))),
769 _ => None,
770 }
771}
772
773pub fn shell_tokenize(input: &str) -> Vec<String> {
775 let mut tokens = Vec::new();
776 let mut current = String::new();
777 let mut chars = input.chars().peekable();
778 let mut in_single = false;
779 let mut in_double = false;
780
781 while let Some(c) = chars.next() {
782 match c {
783 '\'' if !in_double => in_single = !in_single,
784 '"' if !in_single => in_double = !in_double,
785 '\\' if !in_single => {
786 if let Some(next) = chars.next() {
787 current.push(next);
788 }
789 }
790 c if c.is_whitespace() && !in_single && !in_double => {
791 if !current.is_empty() {
792 tokens.push(std::mem::take(&mut current));
793 }
794 }
795 _ => current.push(c),
796 }
797 }
798 if !current.is_empty() {
799 tokens.push(current);
800 }
801 tokens
802}
803
804pub fn shell_quote(s: &str) -> String {
806 if s.contains(|c: char| c.is_whitespace() || c == '\'' || c == '"' || c == '\\') {
807 format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
808 } else {
809 s.to_string()
810 }
811}
812
813fn parse_head_tail_args<'a>(args: &[&'a str]) -> (Option<usize>, Option<&'a str>) {
814 let mut n: Option<usize> = None;
815 let mut path: Option<&str> = None;
816
817 let mut i = 0;
818 while i < args.len() {
819 if args[i] == "-n" && i + 1 < args.len() {
820 n = args[i + 1].parse().ok();
821 i += 2;
822 } else if let Some(num) = args[i].strip_prefix("-n") {
823 n = num.parse().ok();
824 i += 1;
825 } else if args[i].starts_with('-') && args[i].len() > 1 {
826 if let Ok(num) = args[i][1..].parse::<usize>() {
827 n = Some(num);
828 }
829 i += 1;
830 } else {
831 path = Some(args[i]);
832 i += 1;
833 }
834 }
835
836 (n, path)
837}
838
839fn build_rewrite_compound(cmd: &str, binary: &str) -> Option<String> {
840 compound_lexer::rewrite_compound(cmd, |segment| {
841 if segment.starts_with("lean-ctx ") || segment.starts_with(&format!("{binary} ")) {
842 return None;
843 }
844 if is_rewritable(segment) {
845 Some(wrap_single_command(segment, binary))
846 } else {
847 None
848 }
849 })
850}
851
852fn emit_rewrite(rewritten: &str) {
853 let json_escaped = rewritten.replace('\\', "\\\\").replace('"', "\\\"");
854 print!(
855 "{{\"hookSpecificOutput\":{{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"allow\",\"updatedInput\":{{\"command\":\"{json_escaped}\"}}}}}}"
856 );
857}
858
859pub fn handle_redirect() {
860 if is_disabled() {
861 let _ = read_stdin_with_timeout(HOOK_STDIN_TIMEOUT);
862 print!("{}", build_dual_allow_output());
863 return;
864 }
865
866 let Some(input) = read_stdin_with_timeout(HOOK_STDIN_TIMEOUT) else {
867 return;
868 };
869
870 let Ok(v) = serde_json::from_str::<serde_json::Value>(&input) else {
871 print!("{}", build_dual_deny_output("invalid JSON hook payload"));
872 return;
873 };
874
875 let tool_name = v.get("tool_name").and_then(|t| t.as_str()).unwrap_or("");
876 let tool_input = v.get("tool_input");
877
878 match tool_name {
879 "Read" | "read" | "read_file" => redirect_read(tool_input),
880 "Grep" | "grep" | "search" | "ripgrep" => redirect_grep(tool_input),
881 _ => print!("{}", build_dual_allow_output()),
882 }
883}
884
885fn redirect_read(tool_input: Option<&serde_json::Value>) {
889 let path = tool_input
890 .and_then(|ti| ti.get("path"))
891 .and_then(|p| p.as_str())
892 .unwrap_or("");
893
894 if path.is_empty() || should_passthrough(path) {
895 print!("{}", build_dual_allow_output());
896 return;
897 }
898
899 if is_harden_active() {
900 print!(
901 "{}",
902 build_dual_deny_output(
903 "Use ctx_read instead of native Read. lean-ctx harden mode is active."
904 )
905 );
906 return;
907 }
908
909 let binary = resolve_binary();
910 let temp_path = redirect_temp_path(path);
911
912 if let Some(output) = run_with_timeout(&binary, &["read", path], REDIRECT_SUBPROCESS_TIMEOUT) {
913 if !output.is_empty() && std::fs::write(&temp_path, &output).is_ok() {
914 let temp_str = temp_path.to_str().unwrap_or("");
915 print!("{}", build_redirect_output(tool_input, "path", temp_str));
916 return;
917 }
918 }
919
920 print!("{}", build_dual_allow_output());
921}
922
923fn redirect_grep(tool_input: Option<&serde_json::Value>) {
925 let pattern = tool_input
926 .and_then(|ti| ti.get("pattern"))
927 .and_then(|p| p.as_str())
928 .unwrap_or("");
929 let search_path = tool_input
930 .and_then(|ti| ti.get("path"))
931 .and_then(|p| p.as_str())
932 .unwrap_or(".");
933
934 if pattern.is_empty() {
935 print!("{}", build_dual_allow_output());
936 return;
937 }
938
939 if is_harden_active() {
940 print!(
941 "{}",
942 build_dual_deny_output(
943 "Use ctx_search instead of native Grep. lean-ctx harden mode is active."
944 )
945 );
946 return;
947 }
948
949 let binary = resolve_binary();
950 let key = format!("grep:{pattern}:{search_path}");
951 let temp_path = redirect_temp_path(&key);
952
953 if let Some(output) = run_with_timeout(
954 &binary,
955 &["grep", pattern, search_path],
956 REDIRECT_SUBPROCESS_TIMEOUT,
957 ) {
958 if !output.is_empty() && std::fs::write(&temp_path, &output).is_ok() {
959 let temp_str = temp_path.to_str().unwrap_or("");
960 print!("{}", build_redirect_output(tool_input, "path", temp_str));
961 return;
962 }
963 }
964
965 print!("{}", build_dual_allow_output());
966}
967
968const REDIRECT_SUBPROCESS_TIMEOUT: Duration = Duration::from_secs(10);
969
970fn run_with_timeout(binary: &str, args: &[&str], timeout: Duration) -> Option<Vec<u8>> {
973 let mut child = std::process::Command::new(binary)
974 .args(args)
975 .stdout(std::process::Stdio::piped())
976 .stderr(std::process::Stdio::null())
977 .spawn()
978 .ok()?;
979
980 let deadline = std::time::Instant::now() + timeout;
981 loop {
982 match child.try_wait() {
983 Ok(Some(status)) if status.success() => {
984 let mut stdout = Vec::new();
985 if let Some(mut out) = child.stdout.take() {
986 let _ = out.read_to_end(&mut stdout);
987 }
988 return if stdout.is_empty() {
989 None
990 } else {
991 Some(stdout)
992 };
993 }
994 Ok(Some(_)) | Err(_) => return None,
995 Ok(None) => {
996 if std::time::Instant::now() > deadline {
997 let _ = child.kill();
998 let _ = child.wait();
999 return None;
1000 }
1001 std::thread::sleep(Duration::from_millis(10));
1002 }
1003 }
1004 }
1005}
1006
1007fn redirect_temp_path(key: &str) -> std::path::PathBuf {
1008 use std::collections::hash_map::DefaultHasher;
1009 use std::hash::{Hash, Hasher};
1010
1011 let mut hasher = DefaultHasher::new();
1012 key.hash(&mut hasher);
1013 std::process::id().hash(&mut hasher);
1014 let hash = hasher.finish();
1015
1016 let temp_dir = std::env::temp_dir().join("lean-ctx-hook");
1017 let _ = std::fs::create_dir_all(&temp_dir);
1018 #[cfg(unix)]
1019 {
1020 use std::os::unix::fs::PermissionsExt;
1021 let _ = std::fs::set_permissions(&temp_dir, std::fs::Permissions::from_mode(0o700));
1022 }
1023 temp_dir.join(format!("{hash:016x}.lctx"))
1024}
1025
1026fn build_redirect_output(
1027 tool_input: Option<&serde_json::Value>,
1028 field: &str,
1029 temp_path: &str,
1030) -> String {
1031 let updated_input = if let Some(obj) = tool_input.and_then(|v| v.as_object()) {
1032 let mut m = obj.clone();
1033 m.insert(
1034 field.to_string(),
1035 serde_json::Value::String(temp_path.to_string()),
1036 );
1037 serde_json::Value::Object(m)
1038 } else {
1039 serde_json::json!({ field: temp_path })
1040 };
1041
1042 serde_json::json!({
1043 "permission": "allow",
1044 "updated_input": updated_input,
1045 "hookSpecificOutput": {
1046 "hookEventName": "PreToolUse",
1047 "permissionDecision": "allow",
1048 "updatedInput": { field: temp_path }
1049 }
1050 })
1051 .to_string()
1052}
1053
1054const PASSTHROUGH_SUBSTRINGS: &[&str] = &[
1055 ".cursorrules",
1056 ".cursor/rules",
1057 ".cursor/hooks",
1058 "skill.md",
1059 "agents.md",
1060 ".env",
1061 "hooks.json",
1062 "node_modules",
1063];
1064
1065const PASSTHROUGH_EXTENSIONS: &[&str] = &[
1066 "lock", "png", "jpg", "jpeg", "gif", "webp", "pdf", "ico", "svg", "woff", "woff2", "ttf", "eot",
1067];
1068
1069fn should_passthrough(path: &str) -> bool {
1070 let p = path.to_lowercase();
1071
1072 if PASSTHROUGH_SUBSTRINGS.iter().any(|s| p.contains(s)) {
1073 return true;
1074 }
1075
1076 std::path::Path::new(&p)
1077 .extension()
1078 .and_then(|ext| ext.to_str())
1079 .is_some_and(|ext| {
1080 PASSTHROUGH_EXTENSIONS
1081 .iter()
1082 .any(|e| ext.eq_ignore_ascii_case(e))
1083 })
1084}
1085
1086fn codex_reroute_message(rewritten: &str) -> String {
1087 format!(
1088 "Command should run via lean-ctx for compact output. Do not retry the original command. Re-run with: {rewritten}"
1089 )
1090}
1091
1092pub fn handle_codex_pretooluse() {
1093 if is_disabled() {
1094 return;
1095 }
1096 let binary = resolve_binary();
1097 let Some(input) = read_stdin_with_timeout(HOOK_STDIN_TIMEOUT) else {
1098 return;
1099 };
1100
1101 let tool = extract_json_field(&input, "tool_name");
1102 if !matches!(tool.as_deref(), Some("Bash" | "bash")) {
1103 return;
1104 }
1105
1106 let Some(cmd) = extract_json_field(&input, "command") else {
1107 return;
1108 };
1109
1110 if let Some(rewritten) = rewrite_candidate(&cmd, &binary) {
1111 if is_quiet() {
1112 eprintln!("Re-run: {rewritten}");
1113 } else {
1114 eprintln!("{}", codex_reroute_message(&rewritten));
1115 }
1116 std::process::exit(2);
1117 }
1118}
1119
1120pub fn handle_codex_session_start() {
1121 if is_quiet() {
1122 return;
1123 }
1124 println!(
1125 "For shell commands matched by lean-ctx compression rules, prefer `lean-ctx -c \"<command>\"`. If a Bash call is blocked, rerun it with the exact command suggested by the hook."
1126 );
1127}
1128
1129pub fn handle_copilot() {
1133 if is_disabled() {
1134 return;
1135 }
1136 let binary = resolve_binary();
1137 let Some(input) = read_stdin_with_timeout(HOOK_STDIN_TIMEOUT) else {
1138 return;
1139 };
1140
1141 let tool = extract_json_field(&input, "tool_name");
1142 let Some(tool_name) = tool.as_deref() else {
1143 return;
1144 };
1145
1146 let is_shell_tool = matches!(
1147 tool_name,
1148 "Bash" | "bash" | "runInTerminal" | "run_in_terminal" | "terminal" | "shell"
1149 );
1150 if !is_shell_tool {
1151 return;
1152 }
1153
1154 let Some(cmd) = extract_json_field(&input, "command") else {
1155 return;
1156 };
1157
1158 if let Some(rewritten) = rewrite_candidate(&cmd, &binary) {
1159 emit_rewrite(&rewritten);
1160 }
1161}
1162
1163pub fn handle_rewrite_inline() {
1168 if is_disabled() {
1169 return;
1170 }
1171 let binary = resolve_binary_native();
1172 let args: Vec<String> = std::env::args().collect();
1173 if args.len() < 4 {
1175 return;
1176 }
1177 let cmd = args[3..].join(" ");
1178
1179 if let Some(rewritten) = rewrite_candidate(&cmd, &binary) {
1180 print!("{rewritten}");
1181 return;
1182 }
1183
1184 if cmd.starts_with("lean-ctx ") || cmd.starts_with(&format!("{binary} ")) {
1185 print!("{cmd}");
1186 return;
1187 }
1188
1189 print!("{cmd}");
1190}
1191
1192fn resolve_binary() -> String {
1193 let path = crate::core::portable_binary::resolve_portable_binary();
1194 crate::hooks::to_bash_compatible_path(&path)
1195}
1196
1197fn resolve_binary_native() -> String {
1198 crate::core::portable_binary::resolve_portable_binary()
1199}
1200
1201fn extract_json_field(input: &str, field: &str) -> Option<String> {
1202 let key = format!("\"{field}\":");
1203 let key_pos = input.find(&key)?;
1204 let after_colon = &input[key_pos + key.len()..];
1205 let trimmed = after_colon.trim_start();
1206 if !trimmed.starts_with('"') {
1207 return None;
1208 }
1209 let rest = &trimmed[1..];
1210 let bytes = rest.as_bytes();
1211 let mut end = 0;
1212 while end < bytes.len() {
1213 if bytes[end] == b'\\' && end + 1 < bytes.len() {
1214 end += 2;
1215 continue;
1216 }
1217 if bytes[end] == b'"' {
1218 break;
1219 }
1220 end += 1;
1221 }
1222 if end >= bytes.len() {
1223 return None;
1224 }
1225 let raw = &rest[..end];
1226 Some(raw.replace("\\\"", "\"").replace("\\\\", "\\"))
1227}
1228
1229#[cfg(test)]
1230mod tests {
1231 use super::*;
1232
1233 fn expect_wrapped(cmd: &str, binary: &str) -> String {
1234 if cfg!(windows) {
1235 let escaped = cmd.replace('"', "\\\"");
1236 format!("{binary} -c \"{escaped}\"")
1237 } else {
1238 let shell_escaped = cmd.replace('\'', "'\\''");
1239 format!("{binary} -c '{shell_escaped}'")
1240 }
1241 }
1242
1243 #[test]
1244 fn is_rewritable_basic() {
1245 assert!(is_rewritable("git status"));
1246 assert!(is_rewritable("cargo test --lib"));
1247 assert!(is_rewritable("npm run build"));
1248 assert!(!is_rewritable("echo hello"));
1249 assert!(!is_rewritable("cd src"));
1250 assert!(!is_rewritable("cat file.rs"));
1251 }
1252
1253 #[test]
1254 fn file_read_rewrite_cat() {
1255 let r = rewrite_file_read_command("cat src/main.rs", "lean-ctx");
1256 assert_eq!(r, Some("lean-ctx read src/main.rs".to_string()));
1257 }
1258
1259 #[test]
1260 fn file_read_rewrite_head_with_n() {
1261 let r = rewrite_file_read_command("head -n 20 src/main.rs", "lean-ctx");
1262 assert_eq!(
1263 r,
1264 Some("lean-ctx read src/main.rs -m lines:1-20".to_string())
1265 );
1266 }
1267
1268 #[test]
1269 fn file_read_rewrite_head_short() {
1270 let r = rewrite_file_read_command("head -50 src/main.rs", "lean-ctx");
1271 assert_eq!(
1272 r,
1273 Some("lean-ctx read src/main.rs -m lines:1-50".to_string())
1274 );
1275 }
1276
1277 #[test]
1278 fn file_read_rewrite_tail() {
1279 let r = rewrite_file_read_command("tail -n 10 src/main.rs", "lean-ctx");
1280 assert_eq!(
1281 r,
1282 Some("lean-ctx read src/main.rs -m lines:-10".to_string())
1283 );
1284 }
1285
1286 #[test]
1287 fn file_read_rewrite_not_git() {
1288 assert_eq!(rewrite_file_read_command("git status", "lean-ctx"), None);
1289 }
1290
1291 #[test]
1292 fn file_read_skips_home_relative_paths() {
1293 assert_eq!(
1294 rewrite_file_read_command("cat ~/Library/Logs/proxy.log", "lean-ctx"),
1295 None
1296 );
1297 assert_eq!(
1298 rewrite_file_read_command("head -20 ~/.lean-ctx/logs/proxy.stderr.log", "lean-ctx"),
1299 None
1300 );
1301 assert_eq!(
1302 rewrite_file_read_command("tail -50 ~/some/file.txt", "lean-ctx"),
1303 None
1304 );
1305 }
1306
1307 #[test]
1308 fn file_read_skips_system_paths() {
1309 assert_eq!(
1310 rewrite_file_read_command("cat /tmp/test.log", "lean-ctx"),
1311 None
1312 );
1313 assert_eq!(
1314 rewrite_file_read_command("cat /var/log/syslog", "lean-ctx"),
1315 None
1316 );
1317 assert_eq!(
1318 rewrite_file_read_command("cat /proc/cpuinfo", "lean-ctx"),
1319 None
1320 );
1321 }
1322
1323 #[test]
1324 fn file_read_skips_env_var_paths() {
1325 assert_eq!(
1326 rewrite_file_read_command("cat $HOME/.bashrc", "lean-ctx"),
1327 None
1328 );
1329 }
1330
1331 #[test]
1332 fn file_read_skips_library_and_config_paths() {
1333 assert_eq!(
1334 rewrite_file_read_command(
1335 "cat /Users/user/Library/LaunchAgents/com.leanctx.proxy.plist",
1336 "lean-ctx"
1337 ),
1338 None
1339 );
1340 assert_eq!(
1341 rewrite_file_read_command("cat /home/user/.config/lean-ctx/config.toml", "lean-ctx"),
1342 None
1343 );
1344 }
1345
1346 #[test]
1347 fn file_read_skips_pipes_and_redirects() {
1348 assert_eq!(
1349 rewrite_file_read_command("cat file.rs | grep fn", "lean-ctx"),
1350 None
1351 );
1352 assert_eq!(
1353 rewrite_file_read_command("cat file.rs 2>&1", "lean-ctx"),
1354 None
1355 );
1356 assert_eq!(
1357 rewrite_file_read_command("cat file.rs >> output.log", "lean-ctx"),
1358 None
1359 );
1360 assert_eq!(
1361 rewrite_file_read_command("cat a.rs && cat b.rs", "lean-ctx"),
1362 None
1363 );
1364 assert_eq!(
1365 rewrite_file_read_command("cat a.rs; echo done", "lean-ctx"),
1366 None
1367 );
1368 }
1369
1370 #[test]
1371 fn file_read_still_rewrites_project_relative_paths() {
1372 assert_eq!(
1373 rewrite_file_read_command("cat src/main.rs", "lean-ctx"),
1374 Some("lean-ctx read src/main.rs".to_string())
1375 );
1376 assert_eq!(
1377 rewrite_file_read_command("cat ./Cargo.toml", "lean-ctx"),
1378 Some("lean-ctx read ./Cargo.toml".to_string())
1379 );
1380 assert_eq!(
1381 rewrite_file_read_command("head -20 src/lib.rs", "lean-ctx"),
1382 Some("lean-ctx read src/lib.rs -m lines:1-20".to_string())
1383 );
1384 }
1385
1386 #[test]
1387 fn is_outside_project_path_tests() {
1388 assert!(is_outside_project_path("~/foo"));
1389 assert!(is_outside_project_path("~/.lean-ctx/config.toml"));
1390 assert!(is_outside_project_path("$HOME/.bashrc"));
1391 assert!(is_outside_project_path("/tmp/test"));
1392 assert!(is_outside_project_path("/var/log/syslog"));
1393 assert!(is_outside_project_path("/proc/cpuinfo"));
1394 assert!(is_outside_project_path("/Users/x/Library/Logs/foo.log"));
1395 assert!(is_outside_project_path("/home/x/.config/app/conf"));
1396 assert!(is_outside_project_path("/root/.lean-ctx/logs/proxy.log"));
1397
1398 assert!(!is_outside_project_path("src/main.rs"));
1399 assert!(!is_outside_project_path("./Cargo.toml"));
1400 assert!(!is_outside_project_path("../sibling/file.rs"));
1401 assert!(!is_outside_project_path("file.txt"));
1402 }
1403
1404 #[test]
1405 fn parse_head_tail_args_basic() {
1406 let (n, path) = parse_head_tail_args(&["-n", "20", "file.rs"]);
1407 assert_eq!(n, Some(20));
1408 assert_eq!(path, Some("file.rs"));
1409 }
1410
1411 #[test]
1412 fn parse_head_tail_args_combined() {
1413 let (n, path) = parse_head_tail_args(&["-n20", "file.rs"]);
1414 assert_eq!(n, Some(20));
1415 assert_eq!(path, Some("file.rs"));
1416 }
1417
1418 #[test]
1419 fn parse_head_tail_args_short_flag() {
1420 let (n, path) = parse_head_tail_args(&["-50", "file.rs"]);
1421 assert_eq!(n, Some(50));
1422 assert_eq!(path, Some("file.rs"));
1423 }
1424
1425 #[test]
1426 fn should_passthrough_rules_files() {
1427 assert!(should_passthrough("/home/user/.cursorrules"));
1428 assert!(should_passthrough("/project/.cursor/rules/test.mdc"));
1429 assert!(should_passthrough("/home/.cursor/hooks/hooks.json"));
1430 assert!(should_passthrough("/project/SKILL.md"));
1431 assert!(should_passthrough("/project/AGENTS.md"));
1432 assert!(should_passthrough("/project/icon.png"));
1433 assert!(!should_passthrough("/project/src/main.rs"));
1434 assert!(!should_passthrough("/project/src/lib.ts"));
1435 }
1436
1437 #[test]
1438 fn wrap_single() {
1439 let r = wrap_single_command("git status", "lean-ctx");
1440 assert_eq!(r, expect_wrapped("git status", "lean-ctx"));
1441 }
1442
1443 #[test]
1444 fn wrap_with_quotes() {
1445 let r = wrap_single_command(r#"curl -H "Auth" https://api.com"#, "lean-ctx");
1446 assert_eq!(
1447 r,
1448 expect_wrapped(r#"curl -H "Auth" https://api.com"#, "lean-ctx")
1449 );
1450 }
1451
1452 #[test]
1453 fn rewrite_candidate_returns_none_for_existing_lean_ctx_command() {
1454 assert_eq!(
1455 rewrite_candidate("lean-ctx -c git status", "lean-ctx"),
1456 None
1457 );
1458 }
1459
1460 #[test]
1461 fn rewrite_candidate_wraps_single_command() {
1462 assert_eq!(
1463 rewrite_candidate("git status", "lean-ctx"),
1464 Some(expect_wrapped("git status", "lean-ctx"))
1465 );
1466 }
1467
1468 #[test]
1469 fn rewrite_candidate_passes_through_heredoc() {
1470 assert_eq!(
1471 rewrite_candidate(
1472 "git commit -m \"$(cat <<'EOF'\nfix: something\nEOF\n)\"",
1473 "lean-ctx"
1474 ),
1475 None
1476 );
1477 }
1478
1479 #[test]
1480 fn rewrite_candidate_passes_through_heredoc_compound() {
1481 assert_eq!(
1482 rewrite_candidate(
1483 "git add . && git commit -m \"$(cat <<EOF\nfeat: add\nEOF\n)\"",
1484 "lean-ctx"
1485 ),
1486 None
1487 );
1488 }
1489
1490 #[test]
1491 fn codex_reroute_message_includes_exact_rewritten_command() {
1492 let message = codex_reroute_message("lean-ctx -c 'git status'");
1493 assert_eq!(
1494 message,
1495 "Command should run via lean-ctx for compact output. Do not retry the original command. Re-run with: lean-ctx -c 'git status'"
1496 );
1497 }
1498
1499 #[test]
1500 fn compound_rewrite_and_chain() {
1501 let result = build_rewrite_compound("cd src && git status && echo done", "lean-ctx");
1502 let w = expect_wrapped("git status", "lean-ctx");
1503 assert_eq!(result, Some(format!("cd src && {w} && echo done")));
1504 }
1505
1506 #[test]
1507 fn compound_rewrite_pipe() {
1508 let result = build_rewrite_compound("git log --oneline | head -5", "lean-ctx");
1509 let w = expect_wrapped("git log --oneline", "lean-ctx");
1510 assert_eq!(result, Some(format!("{w} | head -5")));
1511 }
1512
1513 #[test]
1514 fn compound_rewrite_no_match() {
1515 let result = build_rewrite_compound("cd src && echo done", "lean-ctx");
1516 assert_eq!(result, None);
1517 }
1518
1519 #[test]
1520 fn compound_rewrite_multiple_rewritable() {
1521 let result = build_rewrite_compound("git add . && cargo test && npm run lint", "lean-ctx");
1522 let w1 = expect_wrapped("git add .", "lean-ctx");
1523 let w2 = expect_wrapped("cargo test", "lean-ctx");
1524 let w3 = expect_wrapped("npm run lint", "lean-ctx");
1525 assert_eq!(result, Some(format!("{w1} && {w2} && {w3}")));
1526 }
1527
1528 #[test]
1529 fn compound_rewrite_semicolons() {
1530 let result = build_rewrite_compound("git add .; git commit -m 'fix'", "lean-ctx");
1531 let w1 = expect_wrapped("git add .", "lean-ctx");
1532 let w2 = expect_wrapped("git commit -m 'fix'", "lean-ctx");
1533 assert_eq!(result, Some(format!("{w1} ; {w2}")));
1534 }
1535
1536 #[test]
1537 fn compound_rewrite_or_chain() {
1538 let result = build_rewrite_compound("git pull || echo failed", "lean-ctx");
1539 let w = expect_wrapped("git pull", "lean-ctx");
1540 assert_eq!(result, Some(format!("{w} || echo failed")));
1541 }
1542
1543 #[test]
1544 fn compound_skips_already_rewritten() {
1545 let result = build_rewrite_compound("lean-ctx -c git status && git diff", "lean-ctx");
1546 let w = expect_wrapped("git diff", "lean-ctx");
1547 assert_eq!(result, Some(format!("lean-ctx -c git status && {w}")));
1548 }
1549
1550 #[test]
1551 fn single_command_not_compound() {
1552 let result = build_rewrite_compound("git status", "lean-ctx");
1553 assert_eq!(result, None);
1554 }
1555
1556 #[test]
1557 fn extract_field_works() {
1558 let input = r#"{"tool_name":"Bash","command":"git status"}"#;
1559 assert_eq!(
1560 extract_json_field(input, "tool_name"),
1561 Some("Bash".to_string())
1562 );
1563 assert_eq!(
1564 extract_json_field(input, "command"),
1565 Some("git status".to_string())
1566 );
1567 }
1568
1569 #[test]
1570 fn extract_field_with_spaces_after_colon() {
1571 let input = r#"{"tool_name": "Bash", "tool_input": {"command": "git status"}}"#;
1572 assert_eq!(
1573 extract_json_field(input, "tool_name"),
1574 Some("Bash".to_string())
1575 );
1576 assert_eq!(
1577 extract_json_field(input, "command"),
1578 Some("git status".to_string())
1579 );
1580 }
1581
1582 #[test]
1583 fn extract_field_pretty_printed() {
1584 let input = "{\n \"tool_name\": \"Bash\",\n \"tool_input\": {\n \"command\": \"npm test\"\n }\n}";
1585 assert_eq!(
1586 extract_json_field(input, "tool_name"),
1587 Some("Bash".to_string())
1588 );
1589 assert_eq!(
1590 extract_json_field(input, "command"),
1591 Some("npm test".to_string())
1592 );
1593 }
1594
1595 #[test]
1596 fn extract_field_handles_escaped_quotes() {
1597 let input = r#"{"tool_name":"Bash","command":"grep -r \"TODO\" src/"}"#;
1598 assert_eq!(
1599 extract_json_field(input, "command"),
1600 Some(r#"grep -r "TODO" src/"#.to_string())
1601 );
1602 }
1603
1604 #[test]
1605 fn extract_field_handles_escaped_backslash() {
1606 let input = r#"{"tool_name":"Bash","command":"echo \\\"hello\\\""}"#;
1607 assert_eq!(
1608 extract_json_field(input, "command"),
1609 Some(r#"echo \"hello\""#.to_string())
1610 );
1611 }
1612
1613 #[test]
1614 fn extract_field_handles_complex_curl() {
1615 let input = r#"{"tool_name":"Bash","command":"curl -H \"Authorization: Bearer token\" https://api.com"}"#;
1616 assert_eq!(
1617 extract_json_field(input, "command"),
1618 Some(r#"curl -H "Authorization: Bearer token" https://api.com"#.to_string())
1619 );
1620 }
1621
1622 #[test]
1623 fn to_bash_compatible_path_windows_drive() {
1624 let p = crate::hooks::to_bash_compatible_path(r"E:\packages\lean-ctx.exe");
1625 assert_eq!(p, "/e/packages/lean-ctx.exe");
1626 }
1627
1628 #[test]
1629 fn to_bash_compatible_path_backslashes() {
1630 let p = crate::hooks::to_bash_compatible_path(r"C:\Users\test\bin\lean-ctx.exe");
1631 assert_eq!(p, "/c/Users/test/bin/lean-ctx.exe");
1632 }
1633
1634 #[test]
1635 fn to_bash_compatible_path_unix_unchanged() {
1636 let p = crate::hooks::to_bash_compatible_path("/usr/local/bin/lean-ctx");
1637 assert_eq!(p, "/usr/local/bin/lean-ctx");
1638 }
1639
1640 #[test]
1641 fn to_bash_compatible_path_msys2_unchanged() {
1642 let p = crate::hooks::to_bash_compatible_path("/e/packages/lean-ctx.exe");
1643 assert_eq!(p, "/e/packages/lean-ctx.exe");
1644 }
1645
1646 #[test]
1647 fn wrap_command_with_bash_path() {
1648 let binary = crate::hooks::to_bash_compatible_path(r"E:\packages\lean-ctx.exe");
1649 let result = wrap_single_command("git status", &binary);
1650 assert!(
1651 !result.contains('\\'),
1652 "wrapped command must not contain backslashes, got: {result}"
1653 );
1654 assert!(
1655 result.starts_with("/e/packages/lean-ctx.exe"),
1656 "must use bash-compatible path, got: {result}"
1657 );
1658 }
1659
1660 #[test]
1661 fn wrap_single_command_em_dash() {
1662 let r = wrap_single_command("gh --comment \"closing — see #407\"", "lean-ctx");
1663 assert_eq!(
1664 r,
1665 expect_wrapped("gh --comment \"closing — see #407\"", "lean-ctx")
1666 );
1667 }
1668
1669 #[test]
1670 fn wrap_single_command_dollar_sign() {
1671 let r = wrap_single_command("echo $HOME", "lean-ctx");
1672 assert_eq!(r, expect_wrapped("echo $HOME", "lean-ctx"));
1673 }
1674
1675 #[test]
1676 fn wrap_single_command_backticks() {
1677 let r = wrap_single_command("echo `date`", "lean-ctx");
1678 assert_eq!(r, expect_wrapped("echo `date`", "lean-ctx"));
1679 }
1680
1681 #[test]
1682 fn wrap_single_command_nested_single_quotes() {
1683 let r = wrap_single_command("echo 'hello world'", "lean-ctx");
1684 assert_eq!(r, expect_wrapped("echo 'hello world'", "lean-ctx"));
1685 }
1686
1687 #[test]
1688 fn wrap_single_command_exclamation_mark() {
1689 let r = wrap_single_command("echo hello!", "lean-ctx");
1690 assert_eq!(r, expect_wrapped("echo hello!", "lean-ctx"));
1691 }
1692
1693 #[test]
1694 fn wrap_single_command_find_with_many_excludes() {
1695 let cmd = "find . -not -path ./node_modules -not -path ./.git -not -path ./dist";
1696 let r = wrap_single_command(cmd, "lean-ctx");
1697 assert_eq!(r, expect_wrapped(cmd, "lean-ctx"));
1698 }
1699
1700 #[test]
1701 fn detect_event_type_tool_response_is_mcp_call() {
1702 let v = serde_json::json!({
1703 "tool_name": "ctx_read",
1704 "tool_response": "file contents here"
1705 });
1706 let event = detect_event_type(&v, 1000).unwrap();
1707 assert_eq!(event.event_type, "mcp_call");
1708 }
1709
1710 #[test]
1711 fn detect_event_type_tool_output_is_mcp_call() {
1712 let v = serde_json::json!({
1713 "tool_name": "ctx_search",
1714 "tool_output": "search results"
1715 });
1716 let event = detect_event_type(&v, 1000).unwrap();
1717 assert_eq!(event.event_type, "mcp_call");
1718 }
1719
1720 #[test]
1721 fn detect_event_type_ctx_prefix_is_mcp_call() {
1722 let v = serde_json::json!({
1723 "tool_name": "ctx_read",
1724 "tool_input": {"path": "src/main.rs"}
1725 });
1726 let event = detect_event_type(&v, 1000).unwrap();
1727 assert_eq!(event.event_type, "mcp_call");
1728 }
1729
1730 #[test]
1731 fn detect_event_type_mcp_prefix_is_mcp_call() {
1732 let v = serde_json::json!({
1733 "tool_name": "mcp__lean-ctx__ctx_read",
1734 "tool_input": {"path": "src/main.rs"}
1735 });
1736 let event = detect_event_type(&v, 1000).unwrap();
1737 assert_eq!(event.event_type, "mcp_call");
1738 }
1739
1740 #[test]
1741 fn detect_event_type_native_read_is_native_tool() {
1742 let v = serde_json::json!({
1743 "tool_name": "Read",
1744 "tool_input": {"path": "src/main.rs"}
1745 });
1746 let event = detect_event_type(&v, 1000).unwrap();
1747 assert_eq!(event.event_type, "native_tool");
1748 }
1749
1750 #[test]
1751 fn detect_event_type_result_json_is_mcp_call() {
1752 let v = serde_json::json!({
1753 "tool_name": "ctx_read",
1754 "result_json": {"content": "..."}
1755 });
1756 let event = detect_event_type(&v, 1000).unwrap();
1757 assert_eq!(event.event_type, "mcp_call");
1758 }
1759}