lean-ctx 3.11.2

LeanCTX Engine: the open-source runtime for the Context Gateway for AI Systems. CLI, MCP server, and supported proxy integrations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
use std::io::Read;

use super::HOOK_STDIN_TIMEOUT;

const BINARY_EXTENSIONS: &[&str] = &[
    "png", "jpg", "jpeg", "gif", "webp", "ico", "bmp", "svg", "pdf", "zip", "tar", "gz", "bz2",
    "xz", "7z", "rar", "woff", "woff2", "ttf", "otf", "eot", "mp3", "mp4", "wav", "avi", "mov",
    "mkv", "so", "dylib", "dll", "exe", "bin", "o", "a", "class", "pyc", "wasm",
];

/// Returns `true` when the lean-ctx daemon is reachable.
pub(super) fn is_mcp_healthy() -> bool {
    is_mcp_server_reachable()
}

/// Handle the `lean-ctx hook deny` subcommand.
///
/// Called by PreToolUse hooks in Replace mode. Denies native Read/Grep/Glob/Shell
/// calls unless an exception applies (binary files, MCP down, etc.).
///
/// Output format matches both Claude Code and Cursor hook protocols.
pub fn handle_deny() {
    let stdin_payload = read_stdin_with_timeout();

    // #1407: Empty/unparseable payload → fail-open. This happens when the hook
    // is invoked with no stdin (e.g. Windsurf pre_mcp_tool_use with broken pipe)
    // or the payload format is completely unrecognized. Blocking in this case
    // would deny ALL tools including lean-ctx's own ctx_* MCP tools.
    if stdin_payload.trim().is_empty() {
        print_allow();
        return;
    }

    let tool_name = extract_tool_name(&stdin_payload);

    // #1407: If tool_name could not be extracted from a non-empty payload,
    // this is likely an MCP event we don't understand. Fail-open rather than
    // blocking unknown payloads — the deny hook's scope is native tools only.
    if tool_name.is_empty() {
        print_allow();
        return;
    }

    let file_path = extract_file_path(&stdin_payload);

    // #805: deny Write/Edit payloads that contain compression markers.
    // These indicate the agent is writing compressed ctx_read output to disk.
    if is_write_tool(&tool_name) {
        if !is_compression_guard_disabled()
            && let Some(content) = extract_write_content(&stdin_payload)
            && has_compression_markers(&content)
        {
            print_deny_compression_markers(&tool_name, &stdin_payload);
            return;
        }
        // Writes pass through — lean-ctx only handles reads (AGENTS.md).
        // The compression marker check above is the only write-path gate.
        print_allow();
        return;
    }

    if should_allow(&tool_name, file_path.as_deref(), &stdin_payload) {
        print_allow();
    } else {
        print_smart_deny(&tool_name, &stdin_payload);
    }
}

fn should_allow(tool_name: &str, file_path: Option<&str>, payload: &str) -> bool {
    if super::is_disabled() {
        return true;
    }

    // GH #1329: lean-ctx MCP tools must never be blocked by the deny hook.
    // Devin (ex-Windsurf) routes MCP calls through its own PreToolUse
    // pipeline, so ctx_* tool invocations hit the deny hook. Allow them.
    if is_lean_ctx_tool(tool_name) {
        return true;
    }

    // #1631: the same pipeline delivers every OTHER MCP server's tools too, and
    // replace mode has no drop-in `ctx_*` substitute for them: `ctx_provider`
    // reads Jira only when the user configured that provider, and nothing posts
    // to Slack. Denying them removed capabilities from the user's stack and gave
    // nothing back. Provenance decides first, because the native names below are
    // ordinary words a foreign server may legitimately use.
    if is_mcp_call(tool_name, payload) {
        return true;
    }

    if !is_replaceable_native_tool(tool_name) {
        return true;
    }

    // Shadow-only surface: hooks compress native tools transparently,
    // so the deny guard must not block them.
    if is_shadow_only_surface() {
        return true;
    }

    if !is_mcp_server_reachable() {
        return true;
    }

    if file_path.is_some_and(is_binary_file) {
        return true;
    }

    if is_notifying_background_shell(tool_name, payload) {
        return true;
    }

    // GH #1228: Claude/CodeBuddy auto memory must use native Read/Edit even
    // when Replace-mode deny hooks are installed.
    if file_path.is_some_and(|p| {
        crate::core::pathjail::is_harness_auto_memory_path(std::path::Path::new(p))
    }) {
        return true;
    }

    if is_replace_mode_disabled() {
        return true;
    }

    false
}

/// Claude Code's `Bash` with `run_in_background: true` re-invokes the model when
/// the job ends; a `ctx_shell` background job cannot (MCP has no wake channel).
/// Denying it pushed agents into `sleep` + status polling — ~19 % of all model
/// requests in a 30-day transcript corpus. Its output lands in a file the agent
/// reads later, so nothing uncompressed floods the context.
///
/// The exception is never weaker than the path the deny redirects to: the
/// command must pass the same shell allowlist `ctx_shell` enforces, and only an
/// exact Claude PreToolUse payload qualifies.
fn is_notifying_background_shell(tool_name: &str, payload: &str) -> bool {
    use crate::core::shell_allowlist::{ShellSecurity, passes_enforced};
    if tool_name != "Bash" {
        return false;
    }
    let Ok(v) = serde_json::from_str::<serde_json::Value>(payload) else {
        return false;
    };
    let background = v
        .pointer("/tool_input/run_in_background")
        .and_then(serde_json::Value::as_bool)
        == Some(true);
    let Some(cmd) = v
        .pointer("/tool_input/command")
        .and_then(serde_json::Value::as_str)
    else {
        return false;
    };
    super::is_claude_pretooluse_payload(&v)
        && background
        && (ShellSecurity::resolve() == ShellSecurity::Off || passes_enforced(cmd))
}

fn is_lean_ctx_tool(tool_name: &str) -> bool {
    tool_name.starts_with("ctx_")
        || tool_name.starts_with("mcp__lean-ctx__")
        || tool_name == "shell"
}

/// Whether this payload describes a call to *some* MCP server rather than one
/// of the host's own native tools.
///
/// Two signals, both structural rather than name-based:
/// - Windsurf/Devin `pre_mcp_tool_use` nests the name under
///   `tool_info.mcp_tool_name` (#1407) and names the server beside it;
/// - Claude Code spells MCP tools `mcp__<server>__<tool>`, the convention
///   `edit_health` and `observe` already key off.
///
/// This matters beyond tidiness: a name allowlist alone would still reject a
/// foreign server that happens to expose a tool called `search`, `read` or
/// `view` — common words that collide with the native surface. Provenance does
/// not collide.
fn is_mcp_call(tool_name: &str, payload: &str) -> bool {
    if tool_name.starts_with("mcp__") {
        return true;
    }
    serde_json::from_str::<serde_json::Value>(payload).is_ok_and(|json| {
        json.get("tool_info")
            .and_then(|ti| ti.get("mcp_tool_name"))
            .is_some()
    })
}

/// Native tools replace mode can actually redirect to a `ctx_*` equivalent.
///
/// The deny guard used to be "allow `ctx_*`, deny everything else", which is
/// only correct on a host that filters by matcher before invoking the hook.
/// Devin routes *every* MCP call through the same PreToolUse pipeline (#1329),
/// so tools from OTHER MCP servers arrived here too — and were rejected with
/// "Use the equivalent ctx_* tool", naming an equivalent that does not exist:
///
/// ```text
/// Calling jira_get_issue from atlassian-mcp-server
/// Output: Tool rejected: Use the equivalent ctx_* tool — replace mode is active.
/// ```
///
/// lean-ctx's own Jira provider (`ctx_provider provider=jira`) is opt-in and
/// separately configured, so it is no drop-in substitute for the user's MCP
/// server; denying that server's call removes a capability and gives back
/// nothing. Replace mode's
/// scope is the native read/search/shell surface it can genuinely replace;
/// everything else passes through.
///
/// The read names mirror Claude's `REDIRECT_MATCHER`; the shell names come from
/// `hook_handlers::is_shell_tool`, the same list the rewrite hook uses, so the
/// two guards cannot drift apart. This is the *second* line of defence —
/// `is_mcp_call` settles provenance first, because these names are ordinary
/// words another server may well use.
fn is_replaceable_native_tool(tool_name: &str) -> bool {
    super::is_shell_tool(tool_name)
        || matches!(
            tool_name,
            "Read"
                | "read"
                | "ReadFile"
                | "read_file"
                | "View"
                | "view"
                | "Grep"
                | "grep"
                | "Search"
                | "search"
                | "Glob"
                | "glob"
                | "ListFiles"
                | "list_files"
                | "ListDirectory"
                | "list_directory"
                | "list_dir"
        )
}

fn is_mcp_server_reachable() -> bool {
    let path = crate::daemon::daemon_pid_path();
    if !path.exists() {
        return true;
    }
    if let Ok(pid_str) = std::fs::read_to_string(&path)
        && let Ok(pid) = pid_str.trim().parse::<u32>()
        && !crate::ipc::process::is_alive(pid)
    {
        return false;
    }
    true
}

/// Whether the shadow-only tool surface is explicitly configured. The deny guard
/// runs in hook context (no MCP client name available), so only an explicit
/// `tool_surface = "shadow"` disables it. `"auto"` keeps the guard active
/// because the hook cannot determine whether THIS client is hook-covered —
/// the MCP server's `list_tools` handler makes that decision per-client.
fn is_shadow_only_surface() -> bool {
    if let Ok(v) = std::env::var("LEAN_CTX_TOOL_SURFACE") {
        return v.eq_ignore_ascii_case("shadow");
    }
    let cfg = crate::core::config::Config::load();
    matches!(cfg.tool_surface.as_deref(), Some("shadow"))
}

fn is_replace_mode_disabled() -> bool {
    matches!(
        std::env::var("LEAN_CTX_REPLACE_MODE"),
        Ok(v) if v.trim() == "0" || v.trim().eq_ignore_ascii_case("off")
    )
}

fn is_binary_file(path: &str) -> bool {
    if let Some(ext) = path.rsplit('.').next() {
        return BINARY_EXTENSIONS.contains(&ext.to_lowercase().as_str());
    }
    false
}

fn extract_tool_name(payload: &str) -> String {
    if let Ok(json) = serde_json::from_str::<serde_json::Value>(payload) {
        // Claude Code / generic: top-level `tool_name`
        if let Some(name) = json.get("tool_name").and_then(serde_json::Value::as_str) {
            return name.to_string();
        }
        // Cursor: `hookSpecificInput.toolName`
        if let Some(name) = json
            .get("hookSpecificInput")
            .and_then(|h| h.get("toolName"))
            .and_then(serde_json::Value::as_str)
        {
            return name.to_string();
        }
        // #1407: Windsurf/Devin MCP hook format: `tool_info.mcp_tool_name`
        // (fires on pre_mcp_tool_use events, which carry the MCP tool name
        // in a nested object rather than the top-level tool_name field)
        if let Some(name) = json
            .get("tool_info")
            .and_then(|ti| ti.get("mcp_tool_name"))
            .and_then(serde_json::Value::as_str)
        {
            return name.to_string();
        }
        // Devin variant: `toolName` at top level (no nesting)
        if let Some(name) = json.get("toolName").and_then(serde_json::Value::as_str) {
            return name.to_string();
        }
    }
    String::new()
}

fn extract_file_path(payload: &str) -> Option<String> {
    let json: serde_json::Value = serde_json::from_str(payload).ok()?;

    let input = json
        .get("input")
        .or_else(|| json.get("hookSpecificInput").and_then(|h| h.get("input")));

    if let Some(input) = input {
        for key in ["file_path", "path", "filePath"] {
            if let Some(path) = input.get(key).and_then(serde_json::Value::as_str) {
                return Some(path.to_string());
            }
        }
    }
    None
}

fn is_write_tool(tool_name: &str) -> bool {
    matches!(
        tool_name,
        "Write"
            | "write"
            | "WriteFile"
            | "Edit"
            | "edit"
            | "MultiEdit"
            | "StrReplace"
            | "str_replace"
            | "EditNotebook"
    )
}

fn is_compression_guard_disabled() -> bool {
    std::env::var("LEAN_CTX_ALLOW_COMPRESSED_WRITE")
        .is_ok_and(|v| v.trim() == "1" || v.trim().eq_ignore_ascii_case("true"))
}

fn has_compression_markers(content: &str) -> bool {
    if content.contains("[lean-ctx:") || content.contains("--- lean-ctx:") {
        return true;
    }
    // Budget truncation markers from apply_turn_budget (#1306).
    if content.contains("\u{2026} truncated at ~") || content.contains("use ctx_read with lines=") {
        return true;
    }
    // Cognitive/signatures mode section markers (#1444).
    for marker in [
        "§ function",
        "§ block",
        "§ impl",
        "§ struct",
        "§ enum",
        "§ trait",
        "§ mod",
        "§ const",
    ] {
        if content.contains(marker) {
            return true;
        }
    }
    // Detect ctx_read build_header corruption (#1323): "filename.ext NNL"
    // followed by " deps " or " exports " on the next line.
    static HEADER_RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
        regex::Regex::new(r"(?m)^\S+\.\w+ \d+L\n (?:deps|exports) ")
            .expect("HEADER_RE is a valid regex pattern")
    });
    static MAP_RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
        regex::Regex::new(r"(?m)(?:@L\d+-\d+|^\s+API:\s*$|^\S+\.\w+ \d+L\n\s+deps:)")
            .expect("MAP_RE is a valid regex pattern")
    });
    HEADER_RE.is_match(content) || MAP_RE.is_match(content)
}

fn extract_write_content(payload: &str) -> Option<String> {
    let json: serde_json::Value = serde_json::from_str(payload).ok()?;
    let input = json
        .get("input")
        .or_else(|| json.get("hookSpecificInput").and_then(|h| h.get("input")))?;

    let mut combined = String::new();

    // Check all common content field names across tool variants.
    // For StrReplace we must check BOTH old_string and new_string:
    // if old_string contains markers, the agent read a compressed file
    // and the resulting write will embed markers in the file. (#1302)
    for key in [
        "content",
        "contents",
        "file_text",
        "text",
        "new_string",
        "new_text",
        "old_string",
        "old_text",
    ] {
        if let Some(text) = input.get(key).and_then(serde_json::Value::as_str) {
            combined.push_str(text);
            combined.push('\n');
        }
    }

    // MultiEdit: check edits array for old_text/new_text
    if let Some(edits) = input.get("edits").and_then(|v| v.as_array()) {
        for edit in edits {
            for key in ["old_text", "oldText", "new_text", "newText"] {
                if let Some(t) = edit.get(key).and_then(serde_json::Value::as_str) {
                    combined.push_str(t);
                    combined.push('\n');
                }
            }
        }
    }

    if combined.is_empty() {
        None
    } else {
        Some(combined)
    }
}

fn print_deny_compression_markers(tool_name: &str, payload: &str) {
    let source = detect_marker_source(payload);
    let msg = match source {
        MarkerSource::OldString => format!(
            "Blocked {tool_name}: old_string contains lean-ctx compression markers. \
             You read the file in compressed mode — the old_string does not match \
             the real file on disk. Re-read with ctx_read(path, mode=\"full\") or \
             use LEAN_CTX_DISABLED=1 before editing. \
             Set LEAN_CTX_ALLOW_COMPRESSED_WRITE=1 to override."
        ),
        MarkerSource::NewString => format!(
            "Blocked {tool_name}: new_string contains lean-ctx compression markers \
             (§ function, [lean-ctx: omitted ...], or truncation marker). \
             Never write compressed content back to disk. \
             Set LEAN_CTX_ALLOW_COMPRESSED_WRITE=1 to override."
        ),
        MarkerSource::Both | MarkerSource::Content => format!(
            "Blocked {tool_name}: payload contains lean-ctx compression markers. \
             The file was read in compressed mode — re-read with \
             ctx_read(path, mode=\"full\") before editing. \
             Set LEAN_CTX_ALLOW_COMPRESSED_WRITE=1 to override."
        ),
    };
    emit_deny(&msg, payload);
}

/// Emit a deny verdict in every hook dialect at once, then exit.
///
/// #1277: the legacy output (`{"decision":"deny",...}` + exit 2) left Claude
/// Code blind — it expects `hookSpecificOutput.permissionDecision` on exit 0,
/// or a stderr message on exit 2, and rendered the old shape as
/// "PreToolUse hook error: No stderr output". The call still blocked, but the
/// model got no guidance to switch to ctx_*.
///
/// Strategy:
/// - stdout: Claude Code PreToolUse payloads get only `hookSpecificOutput`
///   (Claude rejects the legacy top-level `decision: "deny"`); every other host
///   gets one object carrying the Cursor legacy keys, the Copilot top-level
///   `permissionDecision`, and `hookSpecificOutput`.
/// - stderr: the plain reason (Claude Code surfaces stderr on exit 2).
/// - exit code: [`deny_exit_code`] — 0 only together with the Claude-only JSON.
fn emit_deny(msg: &str, payload: &str) -> ! {
    let parsed = serde_json::from_str(payload).unwrap_or(serde_json::Value::Null);
    println!("{}", super::build_deny_output(msg, &parsed));
    eprintln!("{msg}");
    std::process::exit(deny_exit_code(&parsed));
}

/// One predicate decides body AND exit code. Exit 0 is safe only with the
/// Claude-only JSON: Claude treats an invalid body at exit 0 as non-blocking
/// (fail-open). Anything else — other hosts, or a Claude-like payload missing
/// its event marker — exits 2, which every host treats as a block with the
/// stderr reason (fail-closed).
fn deny_exit_code(payload: &serde_json::Value) -> i32 {
    if super::is_claude_pretooluse_payload(payload) {
        0
    } else {
        2
    }
}

#[derive(Debug)]
enum MarkerSource {
    OldString,
    NewString,
    Both,
    Content,
}

fn detect_marker_source(payload: &str) -> MarkerSource {
    let json: serde_json::Value = match serde_json::from_str(payload) {
        Ok(v) => v,
        Err(_) => return MarkerSource::Content,
    };
    let input = json
        .get("input")
        .or_else(|| json.get("hookSpecificInput").and_then(|h| h.get("input")));
    let Some(input) = input else {
        return MarkerSource::Content;
    };
    let old_has = input
        .get("old_string")
        .or_else(|| input.get("old_text"))
        .and_then(serde_json::Value::as_str)
        .is_some_and(has_compression_markers);
    let new_has = input
        .get("new_string")
        .or_else(|| input.get("new_text"))
        .or_else(|| input.get("content"))
        .or_else(|| input.get("contents"))
        .and_then(serde_json::Value::as_str)
        .is_some_and(has_compression_markers);
    match (old_has, new_has) {
        (true, true) => MarkerSource::Both,
        (true, false) => MarkerSource::OldString,
        (false, true) => MarkerSource::NewString,
        (false, false) => MarkerSource::Content,
    }
}
fn print_smart_deny(tool_name: &str, payload: &str) {
    let msg = smart_deny_message(tool_name, payload);
    emit_deny(&msg, payload);
}

/// Build a smart deny message that includes the exact ctx_* call with mapped arguments.
/// This reduces cognitive load for the LLM and prevents instruction drift.
fn smart_deny_message(tool_name: &str, payload: &str) -> String {
    let args = extract_tool_args(payload);
    match tool_name {
        "Read" | "read" | "ReadFile" | "read_file" => build_ctx_read_hint(&args),
        "Grep" | "grep" | "Search" => build_ctx_search_hint(&args),
        "Glob" | "glob" | "list_dir" => build_ctx_glob_hint(&args),
        "Shell" | "Bash" | "bash" | "run_terminal_command" => build_ctx_shell_hint(&args),
        _ => "Use the equivalent ctx_* tool — lean-ctx replace mode is active.".to_string(),
    }
}

fn extract_tool_args(payload: &str) -> serde_json::Map<String, serde_json::Value> {
    let Ok(json) = serde_json::from_str::<serde_json::Value>(payload) else {
        return serde_json::Map::new();
    };
    json.get("input")
        .or_else(|| json.get("hookSpecificInput").and_then(|h| h.get("input")))
        .and_then(|v| v.as_object())
        .cloned()
        .unwrap_or_default()
}

fn build_ctx_read_hint(args: &serde_json::Map<String, serde_json::Value>) -> String {
    let mut parts = Vec::new();
    if let Some(path) = args
        .get("path")
        .or_else(|| args.get("file_path"))
        .and_then(serde_json::Value::as_str)
    {
        parts.push(format!("path=\"{path}\""));
    }
    if let Some(start) = args
        .get("offset")
        .or_else(|| args.get("start_line"))
        .and_then(serde_json::Value::as_i64)
    {
        parts.push(format!("start_line={start}"));
    }
    if let Some(limit) = args
        .get("limit")
        .or_else(|| args.get("end_line"))
        .and_then(serde_json::Value::as_i64)
    {
        parts.push(format!("limit={limit}"));
    }
    let call = if parts.is_empty() {
        "ctx_read(path=\"<file>\")".to_string()
    } else {
        format!("ctx_read({})", parts.join(", "))
    };
    format!("[DENIED] Native Read blocked. Use: {call} — lean-ctx replace mode is active.")
}

fn build_ctx_search_hint(args: &serde_json::Map<String, serde_json::Value>) -> String {
    let mut parts = Vec::new();
    if let Some(pat) = args
        .get("pattern")
        .or_else(|| args.get("regex"))
        .and_then(serde_json::Value::as_str)
    {
        parts.push(format!("pattern=\"{pat}\""));
    }
    if let Some(path) = args
        .get("path")
        .or_else(|| args.get("include"))
        .and_then(serde_json::Value::as_str)
    {
        parts.push(format!("path=\"{path}\""));
    }
    if let Some(glob) = args.get("glob").and_then(serde_json::Value::as_str) {
        parts.push(format!("include=\"{glob}\""));
    }
    let call = if parts.is_empty() {
        "ctx_search(pattern=\"<pattern>\")".to_string()
    } else {
        format!("ctx_search({})", parts.join(", "))
    };
    format!(
        "[DENIED] Native Grep blocked. Use: {call} — ctx_search also supports action=symbol, action=semantic."
    )
}

fn build_ctx_glob_hint(args: &serde_json::Map<String, serde_json::Value>) -> String {
    let mut parts = Vec::new();
    if let Some(pat) = args
        .get("pattern")
        .or_else(|| args.get("glob_pattern"))
        .and_then(serde_json::Value::as_str)
    {
        parts.push(format!("pattern=\"{pat}\""));
    }
    if let Some(path) = args
        .get("path")
        .or_else(|| args.get("target_directory"))
        .and_then(serde_json::Value::as_str)
    {
        parts.push(format!("path=\"{path}\""));
    }
    let call = if parts.is_empty() {
        "ctx_glob(pattern=\"<glob>\")".to_string()
    } else {
        format!("ctx_glob({})", parts.join(", "))
    };
    format!("[DENIED] Native Glob blocked. Use: {call} — or ctx_tree for directory overview.")
}

fn build_ctx_shell_hint(args: &serde_json::Map<String, serde_json::Value>) -> String {
    let cmd = args
        .get("command")
        .or_else(|| args.get("cmd"))
        .and_then(serde_json::Value::as_str)
        .unwrap_or("<command>");
    // Cut on a char boundary: a byte slice panics when byte 80 lands inside a
    // multi-byte character (umlaut, emoji), killing the hook mid-verdict.
    let short_cmd = cmd.char_indices().nth(80).map_or(cmd, |(i, _)| &cmd[..i]);
    format!(
        "[DENIED] Native Shell blocked. Use: ctx_shell(command=\"{short_cmd}\") — lean-ctx replace mode is active."
    )
}

fn print_allow() {
    println!("{{}}");
}

fn read_stdin_with_timeout() -> String {
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let mut buf = String::new();
        let _ = std::io::stdin().read_to_string(&mut buf);
        let _ = tx.send(buf);
    });
    rx.recv_timeout(HOOK_STDIN_TIMEOUT).unwrap_or_default()
}

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

    /// A user with the Atlassian MCP server got every Jira call rejected:
    ///
    /// ```text
    /// Calling jira_get_issue from atlassian-mcp-server
    /// Tool rejected: Use the equivalent ctx_* tool — replace mode is active.
    /// ```
    ///
    /// There is no drop-in equivalent: `ctx_provider provider=jira` needs its
    /// own opt-in configuration and is not the user's server. The guard was
    /// "deny everything that is not ctx_*", which is safe only on a host that
    /// filters by matcher first; Devin routes all MCP traffic through the same
    /// PreToolUse pipeline, so foreign servers were caught in it.
    #[test]
    fn foreign_mcp_tools_are_not_replaceable() {
        for tool in [
            "jira_get_issue",
            "jira_search",
            "confluence_get_page",
            "github_create_pull_request",
            "mcp__atlassian__jira_get_issue",
            "atlassian-mcp-server:jira_get_issue",
            "browser_navigate",
            "slack_post_message",
        ] {
            assert!(
                !is_replaceable_native_tool(tool),
                "{tool} has no ctx_* equivalent; denying it removes a capability \
                 and gives nothing back"
            );
        }
    }

    /// The other half of the contract: narrowing the guard must not let the
    /// native surface through, or replace mode silently stops replacing.
    #[test]
    fn the_native_read_and_shell_surface_stays_replaceable() {
        for tool in [
            "Read",
            "read",
            "ReadFile",
            "read_file",
            "View",
            "Grep",
            "grep",
            "Search",
            "Glob",
            "glob",
            "list_dir",
            "ListDirectory",
        ] {
            assert!(
                is_replaceable_native_tool(tool),
                "{tool} is the native read surface replace mode exists for"
            );
        }
        for shell in [
            "Bash",
            "bash",
            "Shell",
            "run_terminal_command",
            "powershell",
        ] {
            assert!(
                is_replaceable_native_tool(shell),
                "{shell} must stay covered — the list is shared with the rewrite hook"
            );
        }
    }

    #[test]
    fn is_write_tool_recognizes_all_variants() {
        assert!(is_write_tool("Write"));
        assert!(is_write_tool("write"));
        assert!(is_write_tool("Edit"));
        assert!(is_write_tool("StrReplace"));
        assert!(is_write_tool("MultiEdit"));
        assert!(is_write_tool("EditNotebook"));
        assert!(!is_write_tool("Read"));
        assert!(!is_write_tool("Grep"));
        assert!(!is_write_tool("Shell"));
    }

    #[test]
    fn has_compression_markers_detects_lean_ctx_patterns() {
        assert!(has_compression_markers(
            "some text [lean-ctx: omitted 42 lines] more"
        ));
        assert!(has_compression_markers("... [lean-ctx: archived] ..."));
        assert!(!has_compression_markers("[lean-ctx compressed] tail"));
        assert!(!has_compression_markers(
            "[lean-ctx docs](https://example.com)"
        ));
        assert!(!has_compression_markers(
            "normal file content without markers"
        ));
        assert!(!has_compression_markers("lean-ctx is great"));
        assert!(!has_compression_markers(""));
    }

    #[test]
    fn has_compression_markers_detects_footer_marker() {
        assert!(has_compression_markers("content\n--- lean-ctx: end ---\n"));
    }

    #[test]
    fn has_compression_markers_detects_build_header_corruption() {
        // #1323: ctx_read build_header format "mod.rs 1225L\n deps ..."
        assert!(has_compression_markers(
            "mod.rs 1225L\n deps super::foo,bar\n"
        ));
        assert!(has_compression_markers(
            "server_handler.rs 340L\n exports handle_request\n"
        ));
        // Must NOT trigger on normal Rust content
        assert!(!has_compression_markers("let x = 1225;\n deps: vec![]\n"));
        assert!(!has_compression_markers("// mod.rs has 1225 lines\n"));
    }

    #[test]
    fn has_compression_markers_detects_cognitive_section_markers() {
        assert!(has_compression_markers("§ function foo(x: i32) → bool"));
        assert!(has_compression_markers("§ block main_loop"));
        assert!(has_compression_markers("§ impl Display for Foo"));
        assert!(has_compression_markers("§ struct Config { .. }"));
        assert!(has_compression_markers("§ enum State { .. }"));
        assert!(has_compression_markers("§ trait Handler"));
        assert!(has_compression_markers("§ mod utils"));
        assert!(has_compression_markers("§ const MAX_SIZE: usize"));
        assert!(!has_compression_markers("// § is a section sign"));
        assert!(!has_compression_markers("let section = \u{a7}"));
    }

    #[test]
    fn denies_str_replace_with_cognitive_markers() {
        let payload = r#"{"tool_name":"StrReplace","input":{"path":"mod.rs","old_string":"§ function process(ctx) → Result","new_string":"fn process(ctx: &Context) -> Result<()> {}"}}"#;
        let content = extract_write_content(payload).unwrap();
        assert!(
            has_compression_markers(&content),
            "old_string with § markers must trigger the guard"
        );
    }

    #[test]
    fn detects_map_outline_patterns() {
        assert!(has_compression_markers("class pub Foo @L12-34"));
        assert!(has_compression_markers(
            "fn pub run(id:usize) → bool @L372-383"
        ));
        assert!(has_compression_markers("  API:\n    class pub Bar"));
        assert!(has_compression_markers("events.py 1045L\n  deps: foo, bar"));
    }

    #[test]
    fn allows_normal_code() {
        assert!(!has_compression_markers(
            "fn main() { println!(\"hello\"); }"
        ));
        assert!(!has_compression_markers("let x = @L12;"));
    }

    #[test]
    fn extract_write_content_from_cursor_write() {
        let payload = r#"{"hookSpecificInput":{"toolName":"Write","input":{"path":"test.md","contents":"hello [lean-ctx: omitted 5 lines]"}}}"#;
        let content = extract_write_content(payload).unwrap();
        assert!(content.contains("[lean-ctx:"));
    }

    #[test]
    fn extract_write_content_from_claude_code_edit() {
        let payload = r#"{"tool_name":"Edit","input":{"path":"test.rs","new_text":"fn foo() { [lean-ctx: omitted 10 lines] }"}}"#;
        let content = extract_write_content(payload).unwrap();
        assert!(content.contains("[lean-ctx:"));
    }

    #[test]
    fn extract_write_content_from_multi_edit() {
        let payload = r#"{"tool_name":"MultiEdit","input":{"path":"x.rs","edits":[{"new_text":"[lean-ctx: omitted 3 lines]"}]}}"#;
        let content = extract_write_content(payload).unwrap();
        assert!(content.contains("[lean-ctx:"));
    }

    #[test]
    fn extract_write_content_clean_payload_returns_none_for_markers() {
        let payload =
            r#"{"tool_name":"Write","input":{"path":"test.md","contents":"normal content"}}"#;
        let content = extract_write_content(payload).unwrap();
        assert!(!has_compression_markers(&content));
    }

    #[test]
    fn extract_write_content_no_content_returns_none() {
        let payload = r#"{"tool_name":"Write","input":{"path":"test.md"}}"#;
        assert!(extract_write_content(payload).is_none());
    }

    #[test]
    fn extract_write_content_catches_markers_in_old_string() {
        // #1302: StrReplace with compressed old_string means the agent read a
        // compressed file. The resulting write will embed markers in the file.
        let payload = r#"{"tool_name":"StrReplace","input":{"path":"README.md","old_string":"text [lean-ctx: omitted 5 lines] more","new_string":"clean replacement"}}"#;
        let content = extract_write_content(payload).unwrap();
        assert!(
            has_compression_markers(&content),
            "old_string with markers must trigger the guard"
        );
    }

    #[test]
    fn extract_write_content_clean_str_replace_passes() {
        let payload = r#"{"tool_name":"StrReplace","input":{"path":"README.md","old_string":"old text","new_string":"new text"}}"#;
        let content = extract_write_content(payload).unwrap();
        assert!(
            !has_compression_markers(&content),
            "clean StrReplace must not trigger the guard"
        );
    }

    /// The hole a name-based allowlist leaves open: a foreign MCP server whose
    /// tool is called `search`, `read` or `view` collides with the native
    /// surface, so the name alone cannot decide. Provenance can — and both
    /// hosts that route MCP through this hook announce it.
    #[test]
    fn foreign_mcp_calls_are_allowed_even_when_the_name_collides() {
        let devin = r#"{"tool_info":{"mcp_tool_name":"search","server":"atlassian-mcp-server"}}"#;
        assert!(
            is_mcp_call("search", devin),
            "tool_info.mcp_tool_name marks the call as MCP whatever the tool is called"
        );
        assert!(
            should_allow("search", None, devin),
            "another server's `search` must not be answered with 'use ctx_search'"
        );
        assert!(
            should_allow("read", None, r#"{"tool_info":{"mcp_tool_name":"read"}}"#),
            "same for a foreign `read`"
        );

        // Claude Code's spelling for the identical situation.
        assert!(is_mcp_call("mcp__atlassian__jira_get_issue", "{}"));
        assert!(should_allow("mcp__atlassian__jira_get_issue", None, "{}"));

        // A native call carries neither marker and stays in scope.
        assert!(!is_mcp_call("Read", r#"{"tool_name":"Read"}"#));
        assert!(!is_mcp_call("Grep", "{}"));
    }

    /// lean-ctx's own tools reach this hook under both spellings — bare
    /// `ctx_read` from Devin, `mcp__lean-ctx__ctx_read` from Claude Code, the
    /// form `edit_health` and `observe` already recognise.
    #[test]
    fn lean_ctx_tools_are_recognised_under_both_spellings() {
        assert!(is_lean_ctx_tool("ctx_read"));
        assert!(is_lean_ctx_tool("mcp__lean-ctx__ctx_read"));
        assert!(!is_lean_ctx_tool("mcp__atlassian__jira_get_issue"));
    }

    #[test]
    fn should_allow_lean_ctx_tools() {
        assert!(should_allow("ctx_tree", None, "{}"));
        assert!(should_allow("ctx_read", Some("/tmp/test.rs"), "{}"));
        assert!(should_allow("ctx_search", None, "{}"));
        assert!(should_allow("ctx_shell", None, "{}"));
        assert!(should_allow("ctx_compose", None, "{}"));
        assert!(should_allow("shell", None, "{}"));
    }

    #[test]
    fn is_lean_ctx_tool_checks() {
        assert!(is_lean_ctx_tool("ctx_tree"));
        assert!(is_lean_ctx_tool("ctx_read"));
        assert!(is_lean_ctx_tool("shell"));
        assert!(!is_lean_ctx_tool("Read"));
        assert!(!is_lean_ctx_tool("Grep"));
        assert!(!is_lean_ctx_tool("Shell"));
    }

    #[test]
    fn should_allow_claude_auto_memory_paths() {
        assert!(should_allow(
            "Read",
            Some("/home/jules/.claude/projects/-slug/memory/MEMORY.md"),
            "{}"
        ));
        assert!(
            !should_allow("Read", Some("/home/jules/project/src/main.rs"), "{}"),
            "ordinary project files stay denied under replace deny hooks"
        );
    }

    #[test]
    fn extract_tool_name_windsurf_mcp_format() {
        // #1407: Windsurf/Devin sends MCP tool name in tool_info.mcp_tool_name
        let payload = r#"{"tool_info":{"mcp_tool_name":"ctx_tree","server":"lean-ctx"}}"#;
        assert_eq!(extract_tool_name(payload), "ctx_tree");
    }

    #[test]
    fn extract_tool_name_empty_payload_returns_empty() {
        // #1407: Empty or unparseable payloads must not return a fake tool name
        assert_eq!(extract_tool_name(""), "");
        assert_eq!(extract_tool_name("not json"), "");
        assert_eq!(extract_tool_name("{}"), "");
    }

    #[test]
    fn extract_tool_name_top_level_tool_name_variant() {
        let payload = r#"{"toolName":"ctx_read"}"#;
        assert_eq!(extract_tool_name(payload), "ctx_read");
    }

    #[test]
    fn has_compression_markers_detects_budget_truncation() {
        assert!(has_compression_markers(
            "content\n\u{2026} truncated at ~4080 of 14201 tokens"
        ));
        assert!(has_compression_markers(
            "fn main() {}\nuse ctx_read with lines= parameter"
        ));
    }

    #[test]
    fn detect_marker_source_identifies_old_string() {
        let payload = r#"{"tool_name":"StrReplace","input":{"path":"test.rs","old_string":"\u00a7 function foo","new_string":"fn foo() {}"}}"#;
        assert!(matches!(
            detect_marker_source(payload),
            MarkerSource::OldString
        ));
    }

    #[test]
    fn detect_marker_source_identifies_new_string() {
        let payload = r#"{"tool_name":"StrReplace","input":{"path":"test.rs","old_string":"fn foo()","new_string":"[lean-ctx: omitted 5 lines]"}}"#;
        assert!(matches!(
            detect_marker_source(payload),
            MarkerSource::NewString
        ));
    }

    #[test]
    fn detect_marker_source_clean_payload() {
        let payload = r#"{"tool_name":"StrReplace","input":{"path":"test.rs","old_string":"fn foo()","new_string":"fn bar()"}}"#;
        assert!(matches!(
            detect_marker_source(payload),
            MarkerSource::Content
        ));
    }

    /// The background exception must never be weaker than `ctx_shell`: only an
    /// exact Claude PreToolUse payload whose command passes the enforced
    /// allowlist escapes the deny.
    #[test]
    fn background_bash_escapes_deny_only_within_the_allowlist() {
        // No env mutation: overriding the process-global allowlist raced
        // unlocked readers in parallel tests (Windows CI). `cargo` is on the
        // default allowlist; `eval` is blocked in every mode.
        let call = |event: &str, cmd: &str, bg: bool| {
            serde_json::json!({
                "hook_event_name": event, "transcript_path": "/t", "tool_name": "Bash",
                "tool_input": { "command": cmd, "run_in_background": bg }
            })
            .to_string()
        };
        let allowed_bg =
            is_notifying_background_shell("Bash", &call("PreToolUse", "cargo test", true));
        let foreground =
            is_notifying_background_shell("Bash", &call("PreToolUse", "cargo test", false));
        let sink =
            is_notifying_background_shell("Bash", &call("PreToolUse", "eval cat .env", true));
        let other_host =
            is_notifying_background_shell("Bash", &call("BeforeTool", "cargo test", true));
        assert!(
            allowed_bg,
            "allowlisted background job must not be pushed into polling"
        );
        assert!(!foreground, "foreground shell stays denied");
        assert!(
            !sink,
            "a non-allowlisted command must not ride the exception"
        );
        assert!(!other_host, "only exact Claude PreToolUse payloads qualify");
    }

    /// Body and exit code come from one predicate: exit 0 only with the
    /// Claude-only JSON; a Claude-like payload without its event marker and
    /// every other host exit 2 (blocking everywhere, fail-closed).
    #[test]
    fn deny_exit_code_is_zero_only_for_exact_claude_payloads() {
        let claude = serde_json::json!({"hook_event_name": "PreToolUse", "transcript_path": "/t"});
        let no_event = serde_json::json!({"transcript_path": "/t"});
        let gemini = serde_json::json!({"hook_event_name": "BeforeTool", "transcript_path": "/t"});
        let cursor = serde_json::json!({"tool_name": "Shell", "command": "ls"});
        assert_eq!(deny_exit_code(&claude), 0);
        for other in [no_event, gemini, cursor] {
            assert_eq!(deny_exit_code(&other), 2, "{other}");
        }
    }

    #[test]
    fn shell_hint_truncates_on_char_boundary() {
        // Byte 80 falls inside "ü" (2 bytes): a byte slice panicked here.
        let cmd = format!("{}ü{}", "a".repeat(79), "b".repeat(20));
        let mut args = serde_json::Map::new();
        args.insert("command".into(), serde_json::Value::String(cmd));
        let hint = build_ctx_shell_hint(&args);
        assert!(hint.contains(&format!("{}ü\"", "a".repeat(79))), "{hint}");
    }

    #[test]
    fn is_write_tool_does_not_match_ctx_edit() {
        assert!(!is_write_tool("ctx_edit"));
        assert!(!is_write_tool("ctx_patch"));
    }
}