lean-ctx 3.12.0

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
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
//! PostToolUse re-read dedup for guard hosts (GL #1140, follow-up to GH #637).
//!
//! On Claude Code / CodeBuddy the PreToolUse Read redirect is disabled
//! (`read_redirect = auto`) so the native read-before-write guard stays intact —
//! which also forfeits the redirect's re-read dedup. This handler wins those
//! savings back **after** the native Read ran on the real path:
//!
//! - First read of a file: no output → the host keeps the byte-identical native
//!   result (edit safety: `old_string` always comes from real content, and the
//!   guard has already recorded the real path).
//! - Re-read of the same file, unchanged on disk, same session: the result the
//!   model sees is replaced with a compact `[unchanged]` stub via the documented
//!   `PostToolUse.hookSpecificOutput.updatedToolOutput` channel
//!   (code.claude.com/docs/en/hooks). The file and the guard are untouched — the
//!   tool already ran; only the model-visible copy shrinks.
//!
//! Zero-regression design:
//! - **Shape mirroring**: the incoming `tool_response` is cloned and only the
//!   recognised content-bearing field is swapped; unknown shapes pass through.
//!   (The host additionally ignores schema-mismatched replacements for built-in
//!   tools, keeping the original — a second net under ours.)
//! - **Fail-open everywhere**: any parse/IO/state error → no output → original
//!   result. Emitting nothing is the documented no-op.
//! - Replace only when the stub is **strictly smaller** than the original text.
//! - Windowed reads (`offset`/`limit`) key separately — a different window is a
//!   first read.
//! - Subagents (`agent_id` in the payload) key separately from the main
//!   conversation and from each other: they share the parent's `session_id` but
//!   start with an empty context window (#1916).
//! - No `session_id` → never stub (a cross-session record could otherwise
//!   claim content this conversation has never seen).
//! - Compaction wipes the session's records (see [`purge_session`], wired to the
//!   PreCompact-aware observe handler) so post-compaction re-reads deliver full
//!   content again, mirroring the MCP-side compaction sync (GL #555).

#[allow(clippy::wildcard_imports)]
use super::*;

/// Below this size the savings are negligible and a stub only adds risk.
const MIN_DEDUP_BYTES: usize = 512;

/// Above this size, hashing the file on every Read costs more latency than the
/// dedup is worth in a synchronous PostToolUse hook.
const MAX_HASH_BYTES: u64 = 16 * 1024 * 1024;

/// Session record dirs older than this are swept opportunistically.
const SESSION_TTL: Duration = Duration::from_hours(24);

pub fn handle_read_dedup() {
    if is_disabled() {
        return;
    }
    let Some(input) = read_stdin_with_timeout(HOOK_STDIN_TIMEOUT) else {
        return;
    };
    if let Some(out) = compute_read_dedup(&input) {
        print!("{out}");
    }
}

/// Decide the read-dedup hook's stdout. `None` = emit nothing (passthrough, the
/// documented PostToolUse no-op). Split from [`handle_read_dedup`] for tests.
fn compute_read_dedup(input: &str) -> Option<String> {
    if !crate::core::config::ReadDedup::read_dedup_enabled(&crate::core::config::Config::load()) {
        return None;
    }

    let v: serde_json::Value = serde_json::from_str(input).ok()?;

    // Only native Read and lean-ctx `ctx_read` results are dedupable; other
    // tools have shapes we must not touch (the installer's matcher already
    // scopes to these, this is the in-process seatbelt).
    match payload::resolve_tool_name(&v).as_deref() {
        Some("Read") => {}
        Some(name) if CTX_READ_TOOLS.contains(&name) => return compute_ctx_read_dedup(&v),
        _ => return None,
    }

    let tool_input = payload::resolve_tool_args(&v);
    let (_, path) = payload::resolve_path_field(tool_input.as_ref(), payload::READ_PATH_FIELDS)?;
    let session_id = v.get("session_id").and_then(|s| s.as_str())?.to_string();
    // Claude Code runs subagents under the parent's `session_id` and tells them
    // apart only by `agent_id` (#1916). A subagent starts with a fresh context
    // window, so its reads must never match records of the parent or of a
    // sibling subagent.
    let agent_id = v
        .get("agent_id")
        .and_then(|s| s.as_str())
        .unwrap_or_default();
    let tool_use_id = v
        .get("tool_use_id")
        .and_then(|s| s.as_str())
        .unwrap_or_default()
        .to_string();

    let tool_response = v.get("tool_response")?;
    let slot = locate_content(tool_response)?;
    let original = slot_text(tool_response, &slot)?;
    if original.len() < MIN_DEDUP_BYTES {
        return None;
    }

    // Key on the exact read window: a different offset/limit is new content.
    let offset = tool_input
        .as_ref()
        .and_then(|ti| ti.get("offset"))
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(0);
    let limit = tool_input
        .as_ref()
        .and_then(|ti| ti.get("limit"))
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(0);

    let disk_hash = hash_file(&path)?;
    let store = record_path(&session_id, agent_id, &path, offset, limit)?;

    let Ok(prev) = std::fs::read_to_string(&store) else {
        // First read in this session: record it, keep the native result.
        write_record(&store, &disk_hash, &tool_use_id);
        return None;
    };

    let (prev_hash, prev_tool_use) = parse_record(&prev)?;
    // Same tool_use_id = a duplicate fire of the SAME event (Cursor
    // double-fires hooks, #1032). The first fire passed the content
    // through, so its twin must too.
    if prev_hash != disk_hash || (!tool_use_id.is_empty() && prev_tool_use == tool_use_id) {
        write_record(&store, &disk_hash, &tool_use_id);
        return None;
    }

    let line_count = original.lines().count();
    let stub = render_dedup_stub(&path, line_count);
    // Strictly smaller or nothing — the whole point is saving tokens.
    if stub.len() >= original.len() {
        return None;
    }
    let updated = replace_slot(tool_response, &slot, &stub)?;

    // Track dedup savings in stats.json so CEP/dashboard can report them.
    // The hook subprocess is short-lived, so flush immediately.
    let original_tokens = crate::core::tokens::count_tokens(original);
    let stub_tokens = crate::core::tokens::count_tokens(&stub);
    crate::core::stats::record("cli_read_dedup", original_tokens, stub_tokens);
    crate::core::stats::record_reread(original_tokens.saturating_sub(stub_tokens));
    crate::core::stats::flush();

    debug_log::log_hook_decision(
        "read-dedup",
        "Read",
        Route::LeanCtx,
        &path,
        "re-read of unchanged file → dedup stub",
    );
    Some(
        serde_json::json!({
            "hookSpecificOutput": {
                "hookEventName": "PostToolUse",
                "updatedToolOutput": updated,
            }
        })
        .to_string(),
    )
}

/// lean-ctx's `ctx_read` as Claude Code / CodeBuddy name it (server `lean-ctx`,
/// or `lean_ctx` where the host normalises the dash).
pub(crate) const CTX_READ_TOOLS: [&str; 2] = ["mcp__lean-ctx__ctx_read", "mcp__lean_ctx__ctx_read"];

/// Re-read dedup for lean-ctx's own `ctx_read` on guard hosts (Claude Code).
///
/// The MCP server cannot tell who calls it there: sub-agents share the
/// parent's connection, so its `[unchanged]` stub is withheld outright
/// (#1801) and every re-read re-delivered the whole result. This hook *can*
/// tell — the payload carries `session_id` and, for a sub-agent, `agent_id` —
/// so the stub returns here, keyed per reading context.
///
/// The criterion is stricter than the native Read's file hash: a stub replaces
/// a result only when the identical rendering was already delivered to this
/// context for the identical arguments **and** every read file is unchanged on
/// disk. Only the state-triggered suffixes the server may append (#498: a
/// nudge, a checkpoint, kernel context — see [`split_dynamic_suffix`]) are
/// left out of the comparison, and a new suffix still reaches the model after
/// the stub. A re-read whose rendering differs (file changed, `auto` resolving
/// another mode) passes through. `fresh=true` / `raw=true` always pass through.
fn compute_ctx_read_dedup(v: &serde_json::Value) -> Option<String> {
    let tool_input = payload::resolve_tool_args(v)?;
    let forced = |key: &str| {
        tool_input
            .get(key)
            .is_some_and(|f| f.as_bool() == Some(true) || f.as_str() == Some("true"))
    };
    if forced("fresh") || forced("raw") {
        return None;
    }
    let label = tool_input
        .get("path")
        .and_then(|p| p.as_str())
        .unwrap_or("ctx_read")
        .to_string();
    let session_id = v.get("session_id").and_then(|s| s.as_str())?;
    let agent_id = v
        .get("agent_id")
        .and_then(|s| s.as_str())
        .unwrap_or_default();
    let tool_use_id = v
        .get("tool_use_id")
        .and_then(|s| s.as_str())
        .unwrap_or_default();

    let tool_response = v.get("tool_response")?;
    let slot = locate_content(tool_response)?;
    let original = slot_text(tool_response, &slot)?;
    if original.len() < MIN_DEDUP_BYTES || original.starts_with("ERR") {
        return None;
    }
    let (core, suffix) = split_dynamic_suffix(original);
    let cwd = v.get("cwd").and_then(|c| c.as_str()).unwrap_or_default();
    let disk = read_files_fingerprint(&tool_input, cwd)?;
    let mut fingerprint = blake3::Hasher::new();
    fingerprint.update(core.as_bytes());
    fingerprint.update(b"\0");
    fingerprint.update(disk.as_bytes());
    let delivered = fingerprint.finalize().to_hex().to_string();
    // The full argument object is the read variant: path, mode, line range,
    // task, aggressiveness … (serde_json maps serialise in key order).
    let variant = format!("ctx_read\u{0}{tool_input}");
    let store = record_path(session_id, agent_id, &variant, 0, 0)?;

    let Ok(prev) = std::fs::read_to_string(&store) else {
        write_record(&store, &delivered, tool_use_id);
        return None;
    };
    let (prev_delivered, prev_tool_use) = parse_record(&prev)?;
    if prev_delivered != delivered || (!tool_use_id.is_empty() && prev_tool_use == tool_use_id) {
        write_record(&store, &delivered, tool_use_id);
        return None;
    }

    let mut stub = render_ctx_read_dedup_stub(&label, core.lines().count());
    if !suffix.is_empty() {
        stub.push_str("\n\n");
        stub.push_str(suffix);
    }
    if stub.len() >= original.len() {
        return None;
    }
    let updated = replace_slot(tool_response, &slot, &stub)?;

    let original_tokens = crate::core::tokens::count_tokens(original);
    let stub_tokens = crate::core::tokens::count_tokens(&stub);
    crate::core::stats::record("ctx_read_dedup", original_tokens, stub_tokens);
    crate::core::stats::record_reread(original_tokens.saturating_sub(stub_tokens));
    crate::core::stats::flush();

    debug_log::log_hook_decision(
        "read-dedup",
        "ctx_read",
        Route::LeanCtx,
        &label,
        "identical ctx_read result already delivered to this context → dedup stub",
    );
    Some(
        serde_json::json!({
            "hookSpecificOutput": {
                "hookEventName": "PostToolUse",
                "updatedToolOutput": updated,
            }
        })
        .to_string(),
    )
}

/// Line heads of the state-triggered suffixes lean-ctx appends to a tool
/// result (#498): behaviour nudges, activity checkpoints, kernel context.
const DYNAMIC_SUFFIX_HEADS: [&str; 4] = [
    "[lean-ctx nudge]",
    "[CHECKPOINT",
    "--- kernel context ---",
    "## Context Kernel",
];

/// Split a result into its rendering and the trailing state-triggered suffix:
/// the suffix starts at the first line that begins with a
/// [`DYNAMIC_SUFFIX_HEADS`] entry. The read files' disk fingerprint is part of
/// the comparison too, so a file whose own text has such a line can never pass
/// for unchanged.
fn split_dynamic_suffix(text: &str) -> (&str, &str) {
    let mut offset = 0;
    for line in text.split_inclusive('\n') {
        if DYNAMIC_SUFFIX_HEADS.iter().any(|h| line.starts_with(h)) {
            return (text[..offset].trim_end(), text[offset..].trim_end());
        }
        offset += line.len();
    }
    (text.trim_end(), "")
}

/// Content hashes of every file a `ctx_read` names (`path` or `paths`),
/// resolved against the session `cwd`; `None` when one cannot be hashed (then
/// nothing is stubbed).
fn read_files_fingerprint(tool_input: &serde_json::Value, cwd: &str) -> Option<String> {
    let mut paths: Vec<&str> = Vec::new();
    if let Some(p) = tool_input.get("path").and_then(|p| p.as_str()) {
        paths.push(p);
    }
    if let Some(list) = tool_input.get("paths").and_then(|p| p.as_array()) {
        paths.extend(list.iter().filter_map(|p| p.as_str()));
    }
    if paths.is_empty() {
        return None;
    }
    let mut out = String::new();
    for p in paths {
        let path = std::path::Path::new(p);
        let resolved = if path.is_absolute() || cwd.is_empty() {
            path.to_path_buf()
        } else {
            std::path::Path::new(cwd).join(path)
        };
        out.push_str(&hash_file(resolved.to_str()?)?);
        out.push('\n');
    }
    Some(out)
}

/// Deterministic (#498) stub for a deduplicated `ctx_read`.
fn render_ctx_read_dedup_stub(path: &str, line_count: usize) -> String {
    format!(
        "{path} [unchanged {line_count}L · lean-ctx read-dedup]\nIdentical to your earlier ctx_read with these arguments in this conversation — that result is above. Pass fresh=true to re-deliver it."
    )
}

/// Where the content-bearing text lives inside `tool_response`.
///
/// Claude Code's Read returns the line-numbered text either as a plain string,
/// as `{file: {content: "..."}}`, as `{content: "..."}`, or as an MCP-style
/// content-block array. Anything else is unknown → the caller passes through.
#[derive(Debug, Clone, PartialEq, Eq)]
enum ContentSlot {
    /// `tool_response` is the string itself.
    WholeString,
    /// A nested string field, addressed by object keys (e.g. `["file","content"]`).
    Field(Vec<String>),
    /// `tool_response[idx]` is a `{type:"text", text:"..."}` block.
    TextBlock(usize),
    /// `tool_response.content[idx]` is a `{type:"text", text:"..."}` block.
    ContentTextBlock(usize),
}

fn text_block_index(arr: &[serde_json::Value]) -> Option<usize> {
    arr.iter().position(|b| {
        b.get("type").and_then(|t| t.as_str()) == Some("text")
            && b.get("text").and_then(|t| t.as_str()).is_some()
    })
}

fn locate_content(resp: &serde_json::Value) -> Option<ContentSlot> {
    match resp {
        serde_json::Value::String(_) => Some(ContentSlot::WholeString),
        serde_json::Value::Array(arr) => text_block_index(arr).map(ContentSlot::TextBlock),
        serde_json::Value::Object(obj) => {
            if obj
                .get("file")
                .and_then(|f| f.get("content"))
                .and_then(|c| c.as_str())
                .is_some()
            {
                return Some(ContentSlot::Field(vec![
                    "file".to_string(),
                    "content".to_string(),
                ]));
            }
            match obj.get("content") {
                Some(serde_json::Value::String(_)) => {
                    Some(ContentSlot::Field(vec!["content".to_string()]))
                }
                Some(serde_json::Value::Array(arr)) => {
                    text_block_index(arr).map(ContentSlot::ContentTextBlock)
                }
                _ => None,
            }
        }
        _ => None,
    }
}

fn slot_text<'a>(resp: &'a serde_json::Value, slot: &ContentSlot) -> Option<&'a str> {
    match slot {
        ContentSlot::WholeString => resp.as_str(),
        ContentSlot::Field(keys) => {
            let mut cur = resp;
            for k in keys {
                cur = cur.get(k)?;
            }
            cur.as_str()
        }
        ContentSlot::TextBlock(i) => resp.get(*i)?.get("text")?.as_str(),
        ContentSlot::ContentTextBlock(i) => resp.get("content")?.get(*i)?.get("text")?.as_str(),
    }
}

/// Clone `resp` and swap ONLY the located content field for `stub` — every other
/// field (paths, line counts, flags) is mirrored verbatim so the replacement
/// matches the tool's output shape (a schema mismatch would make the host drop
/// the replacement; mirroring makes that fallback unnecessary).
fn replace_slot(
    resp: &serde_json::Value,
    slot: &ContentSlot,
    stub: &str,
) -> Option<serde_json::Value> {
    let stub_val = serde_json::Value::String(stub.to_string());
    let mut out = resp.clone();
    match slot {
        ContentSlot::WholeString => Some(stub_val),
        ContentSlot::Field(keys) => {
            let mut cur = &mut out;
            let (last, parents) = keys.split_last()?;
            for k in parents {
                cur = cur.get_mut(k)?;
            }
            *cur.get_mut(last)? = stub_val;
            Some(out)
        }
        ContentSlot::TextBlock(i) => {
            *out.get_mut(*i)?.get_mut("text")? = stub_val;
            Some(out)
        }
        ContentSlot::ContentTextBlock(i) => {
            *out.get_mut("content")?.get_mut(*i)?.get_mut("text")? = stub_val;
            Some(out)
        }
    }
}

/// The replacement body. Deterministic function of (path, line_count) — no
/// timestamps or counters (#498), so identical re-reads stay byte-stable and
/// provider prompt caching applies. Wording mirrors ctx_read's `[unchanged]`
/// stub, adapted for a host whose Read has no `fresh=true` escape: touching the
/// file or editing it changes the hash and the next Read delivers full content.
fn render_dedup_stub(path: &str, line_count: usize) -> String {
    format!(
        "{path} [unchanged {line_count}L · lean-ctx read-dedup]\nUnchanged since your last Read in this session — the full line-numbered content is already in this conversation above. It will be re-delivered automatically once the file changes on disk."
    )
}

fn hash_file(path: &str) -> Option<String> {
    let meta = std::fs::metadata(path).ok()?;
    if !meta.is_file() || meta.len() > MAX_HASH_BYTES {
        return None;
    }
    let bytes = std::fs::read(path).ok()?;
    Some(blake3::hash(&bytes).to_hex().to_string())
}

/// `<tmp>/lean-ctx-hook/rd/<session-hash>/<read-key>.rdx`, creating the session
/// dir. Session-scoped so [`purge_session`] and the TTL sweep stay O(1) dirs;
/// the reading context (`agent_id`, empty for the main conversation) is part of
/// the read key, so a compaction purge still clears every subagent's records.
fn record_path(
    session_id: &str,
    agent_id: &str,
    path: &str,
    offset: i64,
    limit: i64,
) -> Option<std::path::PathBuf> {
    let root = read_dedup_root()?;
    sweep_stale_sessions(&root);
    let sess = blake3::hash(session_id.as_bytes()).to_hex()[..16].to_string();
    let dir = root.join(sess);
    std::fs::create_dir_all(&dir).ok()?;
    let key = blake3::hash(format!("{agent_id}\u{0}{path}\u{0}{offset}\u{0}{limit}").as_bytes())
        .to_hex()[..16]
        .to_string();
    Some(dir.join(format!("{key}.rdx")))
}

fn read_dedup_root() -> Option<std::path::PathBuf> {
    let dir = std::env::temp_dir().join("lean-ctx-hook").join("rd");
    std::fs::create_dir_all(&dir).ok()?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
    }
    Some(dir)
}

/// Record format: `<blake3-hex> <tool_use_id>` on a single line.
fn parse_record(raw: &str) -> Option<(String, String)> {
    let mut parts = raw.trim().splitn(2, ' ');
    let hash = parts.next()?.to_string();
    let tool_use = parts.next().unwrap_or_default().to_string();
    (!hash.is_empty()).then_some((hash, tool_use))
}

fn write_record(store: &std::path::Path, hash: &str, tool_use_id: &str) {
    let _ = std::fs::write(store, format!("{hash} {tool_use_id}"));
}

/// Drop every read record of `session_id` — called when the host compacts its
/// context (PreCompact): the conversation the stub would point into is gone, so
/// the next Read of each file must deliver full content again (GL #555 parity).
pub(super) fn purge_session(session_id: &str) {
    let Some(root) = read_dedup_root() else {
        return;
    };
    let sess = blake3::hash(session_id.as_bytes()).to_hex()[..16].to_string();
    let _ = std::fs::remove_dir_all(root.join(sess));
}

/// Opportunistic TTL sweep of whole session dirs (no background process; runs
/// on the record-write path and touches only our own `rd/` tree).
fn sweep_stale_sessions(root: &std::path::Path) {
    let Ok(entries) = std::fs::read_dir(root) else {
        return;
    };
    for entry in entries.flatten() {
        let stale = entry
            .metadata()
            .and_then(|m| m.modified())
            .ok()
            .and_then(|t| t.elapsed().ok())
            .is_some_and(|age| age > SESSION_TTL);
        if stale {
            let _ = std::fs::remove_dir_all(entry.path());
        }
    }
}

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

    /// RAII guard that forces `read_dedup=on` for deterministic tests regardless
    /// of host (Cursor exports its own env vars that would make Auto resolve to
    /// disabled). Restores the environment on drop.
    struct GuardHost;
    impl GuardHost {
        fn claude() -> Self {
            // Force dedup on — avoids depending on host_has_read_before_write_guard()
            // which fails inside Cursor agent shells (CURSOR_* vars present).
            crate::test_env::set_var("LEAN_CTX_READ_DEDUP", "on");
            crate::test_env::set_var("CLAUDE_PROJECT_DIR", "/repo");
            GuardHost
        }
    }
    impl Drop for GuardHost {
        fn drop(&mut self) {
            crate::test_env::remove_var("LEAN_CTX_READ_DEDUP");
            crate::test_env::remove_var("CLAUDE_PROJECT_DIR");
        }
    }

    fn guard_env() -> GuardHost {
        GuardHost::claude()
    }

    fn payload(
        session: &str,
        tool_use: &str,
        path: &std::path::Path,
        response: &serde_json::Value,
    ) -> String {
        serde_json::json!({
            "session_id": session,
            "tool_use_id": tool_use,
            "hook_event_name": "PostToolUse",
            "tool_name": "Read",
            "tool_input": { "file_path": path.to_string_lossy() },
            "tool_response": response,
        })
        .to_string()
    }

    fn unique_session(tag: &str) -> String {
        format!(
            "{tag}-{}-{:?}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos(),
            std::thread::current().id()
        )
    }

    fn big_body() -> String {
        "fn main() {}\n".repeat(100)
    }

    #[test]
    fn first_read_passes_through_reread_returns_stub() {
        let _lock = crate::core::data_dir::test_env_lock();
        let _guard = guard_env();
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("lib.rs");
        std::fs::write(&file, big_body()).unwrap();
        let session = unique_session("s1");

        let first = compute_read_dedup(&payload(
            &session,
            "toolu_01",
            &file,
            &serde_json::json!(big_body()),
        ));
        assert!(first.is_none(), "first read must keep the native result");

        let second = compute_read_dedup(&payload(
            &session,
            "toolu_02",
            &file,
            &serde_json::json!(big_body()),
        ));
        let out = second.expect("unchanged re-read must be replaced");
        let v: serde_json::Value = serde_json::from_str(&out).unwrap();
        let hso = &v["hookSpecificOutput"];
        assert_eq!(hso["hookEventName"], "PostToolUse");
        let replaced = hso["updatedToolOutput"].as_str().expect("string mirrored");
        assert!(
            replaced.contains("[unchanged") && replaced.len() < big_body().len(),
            "stub must be the compact unchanged marker: {replaced}"
        );
    }

    #[test]
    fn changed_file_passes_through_and_rearms() {
        let _lock = crate::core::data_dir::test_env_lock();
        let _guard = guard_env();
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("lib.rs");
        std::fs::write(&file, big_body()).unwrap();
        let session = unique_session("s2");

        assert!(
            compute_read_dedup(&payload(
                &session,
                "toolu_01",
                &file,
                &serde_json::json!(big_body())
            ))
            .is_none()
        );

        // File changes on disk → the re-read must deliver the new content.
        std::fs::write(&file, format!("{}\n// changed", big_body())).unwrap();
        assert!(
            compute_read_dedup(&payload(
                &session,
                "toolu_02",
                &file,
                &serde_json::json!(format!("{}\n// changed", big_body()))
            ))
            .is_none(),
            "changed file must pass through"
        );

        // …and the record re-arms on the new hash: the NEXT unchanged re-read stubs.
        assert!(
            compute_read_dedup(&payload(
                &session,
                "toolu_03",
                &file,
                &serde_json::json!(format!("{}\n// changed", big_body()))
            ))
            .is_some(),
            "unchanged re-read after re-arm must stub again"
        );
    }

    #[test]
    fn duplicate_fire_of_same_tool_use_never_stubs() {
        // Cursor double-fires hooks (#1032): the twin of a first read must not
        // be mistaken for a re-read.
        let _lock = crate::core::data_dir::test_env_lock();
        let _guard = guard_env();
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("lib.rs");
        std::fs::write(&file, big_body()).unwrap();
        let session = unique_session("s3");

        let p = payload(&session, "toolu_dup", &file, &serde_json::json!(big_body()));
        assert!(compute_read_dedup(&p).is_none());
        assert!(
            compute_read_dedup(&p).is_none(),
            "identical tool_use_id must replay the first fire's passthrough"
        );
    }

    #[test]
    fn different_window_is_a_first_read() {
        let _lock = crate::core::data_dir::test_env_lock();
        let _guard = guard_env();
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("lib.rs");
        std::fs::write(&file, big_body()).unwrap();
        let session = unique_session("s4");

        assert!(
            compute_read_dedup(&payload(
                &session,
                "toolu_01",
                &file,
                &serde_json::json!(big_body())
            ))
            .is_none()
        );

        // Same file, but a windowed read → different key → passthrough.
        let windowed = serde_json::json!({
            "session_id": session,
            "tool_use_id": "toolu_02",
            "hook_event_name": "PostToolUse",
            "tool_name": "Read",
            "tool_input": { "file_path": file.to_string_lossy(), "offset": 10, "limit": 50 },
            "tool_response": big_body(),
        })
        .to_string();
        assert!(
            compute_read_dedup(&windowed).is_none(),
            "a windowed read of a fully-read file is new content, never a stub"
        );
    }

    #[test]
    fn object_shape_is_mirrored_with_only_content_swapped() {
        let _lock = crate::core::data_dir::test_env_lock();
        let _guard = guard_env();
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("lib.rs");
        std::fs::write(&file, big_body()).unwrap();
        let session = unique_session("s5");

        let resp = serde_json::json!({
            "type": "text",
            "file": {
                "filePath": file.to_string_lossy(),
                "content": big_body(),
                "numLines": 100,
                "startLine": 1,
                "totalLines": 100
            }
        });
        assert!(compute_read_dedup(&payload(&session, "toolu_01", &file, &resp)).is_none());

        let out = compute_read_dedup(&payload(&session, "toolu_02", &file, &resp))
            .expect("object-shaped re-read must stub");
        let v: serde_json::Value = serde_json::from_str(&out).unwrap();
        let updated = &v["hookSpecificOutput"]["updatedToolOutput"];
        assert_eq!(updated["type"], "text", "sibling fields mirrored");
        assert_eq!(updated["file"]["numLines"], 100, "metadata mirrored");
        assert_eq!(
            updated["file"]["filePath"],
            file.to_string_lossy().as_ref(),
            "path mirrored"
        );
        assert!(
            updated["file"]["content"]
                .as_str()
                .unwrap()
                .contains("[unchanged"),
            "only the content field is swapped"
        );
    }

    #[test]
    fn unknown_shape_and_non_read_pass_through() {
        let _lock = crate::core::data_dir::test_env_lock();
        let _guard = guard_env();
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("lib.rs");
        std::fs::write(&file, big_body()).unwrap();
        let session = unique_session("s6");

        // Unknown response shape (number) → fail-open, no record drama.
        let odd = payload(&session, "toolu_01", &file, &serde_json::json!(42));
        assert!(compute_read_dedup(&odd).is_none());

        // Non-Read tool → never touched, even with a plausible shape.
        let write = serde_json::json!({
            "session_id": session,
            "tool_use_id": "toolu_02",
            "hook_event_name": "PostToolUse",
            "tool_name": "Write",
            "tool_input": { "file_path": file.to_string_lossy() },
            "tool_response": big_body(),
        })
        .to_string();
        assert!(compute_read_dedup(&write).is_none());

        // Missing session_id → never stub (cross-session safety).
        let no_session = serde_json::json!({
            "tool_use_id": "toolu_03",
            "hook_event_name": "PostToolUse",
            "tool_name": "Read",
            "tool_input": { "file_path": file.to_string_lossy() },
            "tool_response": big_body(),
        })
        .to_string();
        assert!(compute_read_dedup(&no_session).is_none());
        assert!(compute_read_dedup(&no_session).is_none());
    }

    #[test]
    fn tiny_files_are_never_stubbed() {
        let _lock = crate::core::data_dir::test_env_lock();
        let _guard = guard_env();
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("tiny.rs");
        std::fs::write(&file, "fn a() {}\n").unwrap();
        let session = unique_session("s7");

        let p1 = payload(&session, "t1", &file, &serde_json::json!("fn a() {}\n"));
        let p2 = payload(&session, "t2", &file, &serde_json::json!("fn a() {}\n"));
        assert!(compute_read_dedup(&p1).is_none());
        assert!(
            compute_read_dedup(&p2).is_none(),
            "below MIN_DEDUP_BYTES nothing is replaced"
        );
    }

    #[test]
    fn disabled_off_guard_host_stays_passive() {
        let _lock = crate::core::data_dir::test_env_lock();
        // No guard-host marker → auto keeps the hook passive.
        crate::test_env::remove_var("CLAUDE_PROJECT_DIR");
        crate::test_env::remove_var("CLAUDECODE");
        crate::test_env::remove_var("CODEBUDDY");
        crate::test_env::remove_var("LEAN_CTX_READ_DEDUP");
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("lib.rs");
        std::fs::write(&file, big_body()).unwrap();
        let session = unique_session("s8");

        for id in ["t1", "t2"] {
            assert!(
                compute_read_dedup(&payload(
                    &session,
                    id,
                    &file,
                    &serde_json::json!(big_body())
                ))
                .is_none(),
                "off guard hosts the PreToolUse redirect owns dedup"
            );
        }
    }

    #[test]
    fn purge_session_resets_reread_state() {
        let _lock = crate::core::data_dir::test_env_lock();
        let _guard = guard_env();
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("lib.rs");
        std::fs::write(&file, big_body()).unwrap();
        let session = unique_session("s9");

        assert!(
            compute_read_dedup(&payload(
                &session,
                "t1",
                &file,
                &serde_json::json!(big_body())
            ))
            .is_none()
        );
        // Compaction: the conversation the stub would point into is gone.
        purge_session(&session);
        assert!(
            compute_read_dedup(&payload(
                &session,
                "t2",
                &file,
                &serde_json::json!(big_body())
            ))
            .is_none(),
            "post-compaction re-read must deliver full content (state purged)"
        );
    }

    #[test]
    fn content_block_array_shape_is_supported() {
        let _lock = crate::core::data_dir::test_env_lock();
        let _guard = guard_env();
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("lib.rs");
        std::fs::write(&file, big_body()).unwrap();
        let session = unique_session("s10");

        let resp = serde_json::json!([{ "type": "text", "text": big_body() }]);
        assert!(compute_read_dedup(&payload(&session, "t1", &file, &resp)).is_none());
        let out = compute_read_dedup(&payload(&session, "t2", &file, &resp))
            .expect("content-block re-read must stub");
        let v: serde_json::Value = serde_json::from_str(&out).unwrap();
        let updated = &v["hookSpecificOutput"]["updatedToolOutput"];
        assert!(
            updated[0]["text"].as_str().unwrap().contains("[unchanged"),
            "text block swapped in place"
        );
        assert_eq!(updated[0]["type"], "text", "block type mirrored");
    }

    #[test]
    fn subagent_first_read_is_never_stubbed() {
        // #1916: Claude Code runs subagents under the parent's session_id and
        // marks them only with agent_id. A subagent's first Read of a file the
        // parent already read must deliver full content; repeated reads inside
        // that subagent still dedup, and a compaction purge clears them too.
        let _lock = crate::core::data_dir::test_env_lock();
        let _guard = guard_env();
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("lib.rs");
        std::fs::write(&file, big_body()).unwrap();
        let session = unique_session("s11");
        let with_agent = |tool_use: &str, agent: &str| {
            let mut v: serde_json::Value = serde_json::from_str(&payload(
                &session,
                tool_use,
                &file,
                &serde_json::json!(big_body()),
            ))
            .unwrap();
            v["agent_id"] = serde_json::json!(agent);
            v["agent_type"] = serde_json::json!("general-purpose");
            v.to_string()
        };

        let parent = payload(&session, "toolu_p1", &file, &serde_json::json!(big_body()));
        assert!(compute_read_dedup(&parent).is_none(), "parent first read");
        assert!(
            compute_read_dedup(&with_agent("toolu_s1", "ac658786042dba697")).is_none(),
            "subagent's first read must keep the native result"
        );
        assert!(
            compute_read_dedup(&with_agent("toolu_s2", "b0000000000000001")).is_none(),
            "a sibling subagent's first read must keep the native result"
        );
        assert!(
            compute_read_dedup(&with_agent("toolu_s3", "ac658786042dba697")).is_some(),
            "a re-read inside the same subagent still dedups"
        );
        assert!(
            compute_read_dedup(&payload(
                &session,
                "toolu_p2",
                &file,
                &serde_json::json!(big_body())
            ))
            .is_some(),
            "the parent's own re-read still dedups"
        );

        purge_session(&session);
        assert!(
            compute_read_dedup(&with_agent("toolu_s4", "ac658786042dba697")).is_none(),
            "compaction purge must clear subagent records as well"
        );
    }

    #[test]
    fn stub_is_deterministic() {
        // #498: byte-stable output for identical inputs.
        assert_eq!(
            render_dedup_stub("/a/b.rs", 42),
            render_dedup_stub("/a/b.rs", 42)
        );
    }

    /// Claude Code's MCP result shape: a content-block array.
    fn ctx_read_payload(
        session: &str,
        agent: Option<&str>,
        tool_use: &str,
        input: &serde_json::Value,
        text: &str,
    ) -> String {
        let mut p = serde_json::json!({
            "session_id": session,
            "tool_use_id": tool_use,
            "hook_event_name": "PostToolUse",
            "tool_name": "mcp__lean-ctx__ctx_read",
            "tool_input": input,
            "tool_response": [{ "type": "text", "text": text }],
        });
        if let Some(agent) = agent {
            p["agent_id"] = serde_json::json!(agent);
        }
        p.to_string()
    }

    fn stubbed_text(out: &str) -> String {
        let v: serde_json::Value = serde_json::from_str(out).unwrap();
        v["hookSpecificOutput"]["updatedToolOutput"][0]["text"]
            .as_str()
            .expect("content block mirrored")
            .to_string()
    }

    /// #1801 left Claude Code without any ctx_read re-read savings: the MCP
    /// server cannot tell a sub-agent from its parent. The hook can.
    #[test]
    fn ctx_read_reread_is_stubbed_per_reading_context() {
        let _lock = crate::core::data_dir::test_env_lock();
        let _guard = guard_env();
        let session = unique_session("cr1");
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("main.rs");
        std::fs::write(&file, big_body()).unwrap();
        let path = file.to_string_lossy().to_string();
        let input = serde_json::json!({ "path": path, "mode": "full" });
        let body = big_body();
        let run = |agent: Option<&str>, tool_use: &str| {
            compute_read_dedup(&ctx_read_payload(&session, agent, tool_use, &input, &body))
        };

        assert!(run(None, "t1").is_none(), "first read delivers the result");
        let stub = stubbed_text(&run(None, "t2").expect("identical re-read is stubbed"));
        assert!(
            stub.starts_with(&format!("{path} [unchanged 100L")),
            "{stub}"
        );
        assert!(stub.contains("fresh=true"), "the escape is named: {stub}");
        assert!(
            run(Some("sub-1"), "t3").is_none(),
            "a sub-agent never saw the parent's result: full delivery"
        );
        assert!(
            run(Some("sub-1"), "t4").is_some(),
            "…but its own re-read stubs"
        );
    }

    #[test]
    fn ctx_read_dedup_requires_identical_bytes_and_identical_arguments() {
        let _lock = crate::core::data_dir::test_env_lock();
        let _guard = guard_env();
        let session = unique_session("cr2");
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("a.rs");
        std::fs::write(&file, big_body()).unwrap();
        let path = file.to_string_lossy().to_string();
        let body = big_body();
        let call = |input: &serde_json::Value, text: &str, tool_use: &str| {
            compute_read_dedup(&ctx_read_payload(&session, None, tool_use, input, text))
        };
        let full = serde_json::json!({ "path": path, "mode": "full" });

        assert!(call(&full, &body, "t1").is_none());
        let changed = format!("{body}// edited\n");
        assert!(
            call(&full, &changed, "t2").is_none(),
            "different rendering (file changed, auto picked another mode) passes through"
        );
        assert!(
            call(&full, &changed, "t3").is_some(),
            "re-armed on new bytes"
        );
        assert!(
            call(
                &serde_json::json!({ "path": path, "mode": "map" }),
                &changed,
                "t4"
            )
            .is_none(),
            "another mode is another read"
        );
        assert!(
            call(
                &serde_json::json!({ "path": path, "mode": "full", "fresh": true }),
                &changed,
                "t5"
            )
            .is_none(),
            "fresh=true is the explicit escape and is never stubbed"
        );
        assert!(
            call(&full, &changed, "t2").is_none(),
            "a duplicate fire of the delivering tool_use passes through"
        );
        assert!(
            call(&full, "ERROR: file not found", "t6").is_none(),
            "errors are never recorded or stubbed"
        );
    }

    /// Live capture (Claude Code, 2026-10-12): the second identical read
    /// carried a once-per-session `[lean-ctx nudge]` suffix, so a bytes-only
    /// comparison never stubbed. The rendering is compared, the suffix still
    /// reaches the model, and a changed file on disk never stubs.
    #[test]
    fn ctx_read_dedup_ignores_state_suffixes_but_never_a_changed_file() {
        let _lock = crate::core::data_dir::test_env_lock();
        let _guard = guard_env();
        let session = unique_session("cr4");
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("lib.rs");
        std::fs::write(&file, big_body()).unwrap();
        let input = serde_json::json!({ "path": file.to_string_lossy(), "mode": "full" });
        let call = |text: &str, tool_use: &str| {
            compute_read_dedup(&ctx_read_payload(&session, None, tool_use, &input, text))
        };
        let nudge = "[lean-ctx nudge] large explicit full/raw read — use map. (once per session)";

        assert!(call(&big_body(), "t1").is_none());
        let out = call(&format!("{}\n\n{nudge}", big_body()), "t2")
            .expect("same rendering plus a nudge is a re-read");
        let stub = stubbed_text(&out);
        assert!(stub.contains("[unchanged"), "{stub}");
        assert!(
            stub.ends_with(nudge),
            "the new suffix still reaches the model: {stub}"
        );

        std::fs::write(&file, format!("{}// edited\n", big_body())).unwrap();
        assert!(
            call(&big_body(), "t3").is_none(),
            "a file changed on disk is delivered, whatever the rendering"
        );
        assert_eq!(
            split_dynamic_suffix("a\nb\n\n[CHECKPOINT: x]\n"),
            ("a\nb", "[CHECKPOINT: x]")
        );
        assert_eq!(
            split_dynamic_suffix("  \"[lean-ctx nudge]\" in code\n"),
            ("  \"[lean-ctx nudge]\" in code", "")
        );
    }

    #[test]
    fn ctx_read_dedup_ignores_other_lean_ctx_tools() {
        let _lock = crate::core::data_dir::test_env_lock();
        let _guard = guard_env();
        let session = unique_session("cr3");
        let body = big_body();
        let mut p: serde_json::Value = serde_json::from_str(&ctx_read_payload(
            &session,
            None,
            "t1",
            &serde_json::json!({ "command": "git log" }),
            &body,
        ))
        .unwrap();
        p["tool_name"] = serde_json::json!("mcp__lean-ctx__ctx_shell");
        let p = p.to_string();
        assert!(compute_read_dedup(&p).is_none());
        assert!(compute_read_dedup(&p.replace("\"t1\"", "\"t2\"")).is_none());
    }
}