lean-ctx-engine-ext 3.12.13

LeanCTX | Engine extensions: the engine modules above the core (setup, reports, graph analysis, knowledge routing, sandboxing).
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
1149
1150
1151
1152
1153
1154
1155
1156
// SPDX-License-Identifier: Apache-2.0
//! Rule discovery for ctx_read (#1325).
//!
//! When lean-ctx replaces native file-read tools, the IDE's rule-injection
//! contract must be honoured: reading a file should surface rules scoped to
//! that path (CLAUDE.md, .claude/rules, .cursor/rules, AGENTS.md).
//!
//! This module discovers applicable rules for a given file path, caches them
//! per directory, and formats them for appending to `ctx_read` output.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Mutex;

// ── Types ───────────────────────────────────────────────────────────────────

#[derive(Debug, Clone)]
pub(crate) struct DiscoveredRule {
    pub source: String,
    pub content: String,
}

// ── Per-session dedup ───────────────────────────────────────────────────────

static INJECTED: Mutex<Option<HashSet<String>>> = Mutex::new(None);

fn already_injected(key: &str) -> bool {
    let mut guard = INJECTED
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    let set = guard.get_or_insert_with(HashSet::new);
    !set.insert(key.to_string())
}

fn is_injected(key: &str) -> bool {
    INJECTED
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .as_ref()
        .is_some_and(|set| set.contains(key))
}

/// A rule file as any other source reaches a reply: through the admitted
/// rooted reader, under the request project — path jail and secret-path
/// rule, project policy, gateway classification and redaction, decode
/// completeness. The reader also publishes the file into the call's source
/// capture, so the rule text in a reply has a lineage like the file that was
/// read. `None`: withheld, unreadable, empty, or not inside the project.
fn admitted_rule(project_root: &str, source: &str) -> Option<String> {
    let path = rule_path(project_root, source);
    let mut remaining = crate::core::limits::max_read_bytes();
    crate::core::rooted_read::read_file_for_tool_rooted_admitted(
        path.to_str()?,
        project_root,
        "ctx_read",
        &mut remaining,
    )
    .ok()
    .filter(|read| read.complete && !read.content.trim().is_empty())
    .map(|read| read.content)
}

/// The file a rule `source` names. Claude labels use `/` on every platform,
/// and a verbatim Windows root (`\\?\`) does not treat `/` as a separator,
/// so the label is joined one component at a time.
fn rule_path(project_root: &str, source: &str) -> std::path::PathBuf {
    source
        .split('/')
        .fold(Path::new(project_root).to_path_buf(), |path, part| {
            path.join(part)
        })
}

/// Reset injection tracking (for tests).
#[cfg(test)]
pub(crate) fn reset_injection_cache() {
    let mut guard = INJECTED
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    *guard = None;
}

// ── Public API ──────────────────────────────────────────────────────────────

/// Max tokens for the injected rules suffix. Prevents rules from dominating
/// the response and triggering turn-budget truncation of file content (#1406).
const MAX_RULES_SUFFIX_TOKENS: usize = 800;

/// Discover and format rules applicable to `file_path` that haven't been
/// injected yet in this session. Returns an empty string when no new rules
/// apply or when the client natively handles rule injection.
pub fn rules_suffix_for_read(file_path: &str, project_root: &str, client_id: &str) -> String {
    let cfg = crate::core::config::Config::load();
    if cfg.declines_rule_steering() {
        return String::new();
    }

    // Claude Code loads the root instructions at launch but nested CLAUDE.md
    // files and path-scoped `.claude/rules` only when its native Read touches
    // a file. In replace mode that Read never runs, so lean-ctx delivers
    // exactly the lazily loaded part.
    let rules = if is_claude_client(client_id) {
        claude_scoped::discover(file_path, project_root)
    } else if client_natively_injects_rules(client_id) {
        return String::new();
    } else {
        discover_rules(file_path, project_root, client_id)
    };
    if rules.is_empty() {
        return String::new();
    }

    let mut parts = Vec::new();
    let mut not_shown = Vec::new();
    let mut token_count = 0;
    for rule in &rules {
        let key = format!("{}:{}", rule.source, blake3_short(&rule.content));
        if is_injected(&key) {
            continue;
        }
        // Discovery read the file only to decide whether it applies. What is
        // appended to the reply is the file as the admitted reader delivers
        // it now. A rule file that is withheld, unreadable or outside the
        // project contributes nothing — not its text and not its name — and
        // is not marked as injected, so it is offered again once it admits.
        let Some(content) = admitted_rule(project_root, &rule.source) else {
            continue;
        };
        // The cap holds for every rule, the first included (#2229): a body
        // that does not fit is replaced by a pointer to its file, and a rule
        // whose pointer does not fit either is only named. A rule counts as
        // injected only once its body or pointer is in the reply, so a rule
        // that was merely named is offered again on a later read.
        let body = format!("[From: {}]\n{}", rule.source, content.trim());
        let pointer = format!(
            "[From: {}]\n[Rule body omitted; authoritative source: {}]",
            rule.source,
            rule_path(project_root, &rule.source).display()
        );
        let admitted_part = [body, pointer].into_iter().find_map(|part| {
            let tokens = crate::core::tokens::count_tokens(&part);
            (token_count + tokens <= MAX_RULES_SUFFIX_TOKENS).then_some((part, tokens))
        });
        match admitted_part {
            Some((part, tokens)) => {
                already_injected(&key);
                token_count += tokens;
                parts.push(part);
            }
            None => not_shown.push(rule.source.as_str()),
        }
    }
    if !not_shown.is_empty() {
        parts.push(format!(
            "[Rules in scope not shown (size limit); read them directly: {}]",
            not_shown.join(", ")
        ));
    }

    if parts.is_empty() {
        return String::new();
    }

    format!(
        "\n\n--- Rules in scope for this file ---\n{}",
        parts.join("\n\n")
    )
}

// ── Client detection ────────────────────────────────────────────────────────

/// Returns true when the client's native harness already injects rules on
/// file reads, so lean-ctx should NOT duplicate them.
///
/// #1406: Claude Code loads CLAUDE.md + AGENTS.md + .claude/rules/ at session
/// start; Cursor loads .cursor/rules/ + AGENTS.md via workspace rules. Both
/// have the rules in their system prompt already — re-injecting them via
/// ctx_read wastes tokens and can trigger turn-budget truncation.
///
/// Claude clients are routed to [`claude_scoped`] before this check: only
/// their launch-time rules are native, the lazily loaded ones are not.
fn client_natively_injects_rules(client_id: &str) -> bool {
    let lower = client_id.to_lowercase();
    lower.contains("claude") || lower.contains("cursor")
}

fn is_claude_client(client_id: &str) -> bool {
    client_id.to_lowercase().contains("claude")
}

// ── Discovery ───────────────────────────────────────────────────────────────

static DIR_CACHE: Mutex<Option<HashMap<String, Vec<DiscoveredRule>>>> = Mutex::new(None);

fn discover_rules(file_path: &str, project_root: &str, client_id: &str) -> Vec<DiscoveredRule> {
    let file = Path::new(file_path);
    let root = Path::new(project_root);
    let dir = file.parent().unwrap_or(root);

    let cache_key = format!("{client_id}:{}", dir.display());
    {
        let guard = DIR_CACHE
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(cache) = guard.as_ref()
            && let Some(cached) = cache.get(&cache_key)
        {
            return filter_by_path(cached, file_path, project_root);
        }
    }

    let mut rules = Vec::new();

    collect_hierarchy_rules(dir, root, &mut rules);
    collect_glob_rules(project_root, client_id, &mut rules);

    {
        let mut guard = DIR_CACHE
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let cache = guard.get_or_insert_with(HashMap::new);
        cache.insert(cache_key, rules.clone());
    }

    filter_by_path(&rules, file_path, project_root)
}

/// Walk from `dir` up to `root`, collecting CLAUDE.md and AGENTS.md files.
fn collect_hierarchy_rules(dir: &Path, root: &Path, rules: &mut Vec<DiscoveredRule>) {
    let mut current = Some(dir);
    while let Some(d) = current {
        for name in &["CLAUDE.md", "AGENTS.md"] {
            let candidate = d.join(name);
            if candidate.is_file()
                && let Ok(content) = std::fs::read_to_string(&candidate)
                && !content.trim().is_empty()
            {
                let relative = candidate.strip_prefix(root).map_or_else(
                    |_| candidate.display().to_string(),
                    |p| p.display().to_string(),
                );
                rules.push(DiscoveredRule {
                    source: relative,
                    content,
                });
            }
        }
        if d == root {
            break;
        }
        current = d.parent();
    }
}

/// Collect glob-scoped rules from .claude/rules and .cursor/rules.
fn collect_glob_rules(project_root: &str, client_id: &str, rules: &mut Vec<DiscoveredRule>) {
    let root = Path::new(project_root);

    let rule_dirs: Vec<PathBuf> = if client_id.contains("cursor") {
        vec![root.join(".cursor/rules")]
    } else if client_id.contains("claude") {
        vec![root.join(".claude/rules")]
    } else {
        vec![root.join(".cursor/rules"), root.join(".claude/rules")]
    };

    for rule_dir in rule_dirs {
        if !rule_dir.is_dir() {
            continue;
        }
        let Ok(entries) = std::fs::read_dir(&rule_dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
            if !matches!(ext, "md" | "mdc") {
                continue;
            }
            if let Ok(content) = std::fs::read_to_string(&path) {
                if content.trim().is_empty() {
                    continue;
                }
                let relative = path
                    .strip_prefix(root)
                    .map_or_else(|_| path.display().to_string(), |p| p.display().to_string());
                rules.push(DiscoveredRule {
                    source: relative,
                    content,
                });
            }
        }
    }
}

/// Filter rules to those applicable to the given file path.
///
/// Hierarchy rules (CLAUDE.md, AGENTS.md) always apply.
/// For `.cursor/rules` / `.claude/rules`:
///   - Rules with `alwaysApply: true` are skipped (already in system prompt)
///   - Rules without explicit `globs:` / `path:` patterns are skipped
///     (no frontmatter = system-level rule, also already in system prompt)
///   - Only rules with `globs:` / `path:` matching the file are injected
fn filter_by_path(
    rules: &[DiscoveredRule],
    file_path: &str,
    project_root: &str,
) -> Vec<DiscoveredRule> {
    let relative_file = Path::new(file_path)
        .strip_prefix(project_root)
        .map_or_else(|_| file_path.to_string(), |p| p.display().to_string());

    rules
        .iter()
        .filter(|r| {
            let src = &r.source;
            if src.ends_with("CLAUDE.md") || src.ends_with("AGENTS.md") {
                return true;
            }
            if is_always_apply(&r.content) {
                return false;
            }
            match extract_globs(&r.content) {
                Some(patterns) => patterns.iter().any(|p| glob_matches(p, &relative_file)),
                // No globs/path in frontmatter → system-level rule, skip
                None => false,
            }
        })
        .cloned()
        .collect()
}

/// Detect `alwaysApply: true` in rule frontmatter.
fn is_always_apply(content: &str) -> bool {
    if !content.starts_with("---") {
        return false;
    }
    let Some(end) = content[3..].find("---") else {
        return false;
    };
    let frontmatter = &content[3..3 + end];
    frontmatter
        .lines()
        .any(|l| l.trim().starts_with("alwaysApply:") && l.contains("true"))
}

/// Extract glob patterns from rule file frontmatter.
/// Supports Cursor `.mdc` (`globs: pattern`), the older Claude Code form
/// (`path: pattern`) and the current Claude Code `paths` field, as a scalar,
/// a comma-separated string, a flow list or a YAML block list.
fn extract_globs(content: &str) -> Option<Vec<String>> {
    let patterns = frontmatter_patterns(content, &["globs", "path", "paths"]);
    (!patterns.is_empty()).then_some(patterns)
}

/// The frontmatter between the leading `---` and the next `---` line.
fn frontmatter(content: &str) -> Option<&str> {
    let rest = content.strip_prefix("---")?;
    let end = rest.find("\n---")?;
    Some(&rest[..end])
}

/// Patterns under any of `keys` in the frontmatter, in file order.
pub(super) fn frontmatter_patterns(content: &str, keys: &[&str]) -> Vec<String> {
    let Some(frontmatter) = frontmatter(content) else {
        return Vec::new();
    };
    let mut patterns = Vec::new();
    let mut lines = frontmatter.lines().peekable();
    while let Some(line) = lines.next() {
        let trimmed = line.trim();
        let Some(rest) = keys.iter().find_map(|key| {
            trimmed
                .strip_prefix(key)
                .and_then(|rest| rest.strip_prefix(':'))
        }) else {
            continue;
        };
        let rest = rest.trim();
        if rest.is_empty() {
            // Block list: following `- item` lines (blank lines allowed).
            while let Some(next) = lines.peek() {
                let item = next.trim();
                if item.is_empty() {
                    lines.next();
                    continue;
                }
                let Some(value) = item.strip_prefix('-') else {
                    break;
                };
                push_patterns(value, &mut patterns);
                lines.next();
            }
        } else if let Some(flow) = rest.strip_prefix('[').and_then(|r| r.strip_suffix(']')) {
            push_patterns(flow, &mut patterns);
        } else {
            push_patterns(rest, &mut patterns);
        }
    }
    patterns
}

/// Splits a comma-separated value at commas outside `{...}` brace groups,
/// so `src/*.{ts,tsx}` stays one pattern, and unquotes each part.
fn push_patterns(value: &str, patterns: &mut Vec<String>) {
    let mut depth = 0usize;
    let mut start = 0;
    let mut parts = Vec::new();
    for (index, ch) in value.char_indices() {
        match ch {
            '{' => depth += 1,
            '}' => depth = depth.saturating_sub(1),
            ',' if depth == 0 => {
                parts.push(&value[start..index]);
                start = index + 1;
            }
            _ => {}
        }
    }
    parts.push(&value[start..]);
    for part in parts {
        let part = part.trim().trim_matches('"').trim_matches('\'').trim();
        if !part.is_empty() {
            patterns.push(part.to_string());
        }
    }
}

/// Simple glob matching (supports `*` and `**`).
fn glob_matches(pattern: &str, path: &str) -> bool {
    if pattern == "*" || pattern == "**/*" || pattern == "**" {
        return true;
    }

    let pattern = pattern.replace('\\', "/");
    let path = path.replace('\\', "/");

    if let Some(suffix) = pattern.strip_prefix("**/") {
        if !suffix.contains('/') {
            let filename = path.rsplit('/').next().unwrap_or(&path);
            return glob_matches(suffix, filename);
        }
        let mut remaining = &path[..];
        loop {
            if glob_matches(suffix, remaining) {
                return true;
            }
            match remaining.find('/') {
                Some(pos) => remaining = &remaining[pos + 1..],
                None => return false,
            }
        }
    }

    if pattern.starts_with("*.") {
        let ext = &pattern[1..];
        return path.ends_with(ext);
    }

    if !pattern.contains('*') {
        return path == pattern || path.ends_with(&format!("/{pattern}"));
    }

    let parts: Vec<&str> = pattern.split('*').collect();
    if parts.len() == 2 {
        let (prefix, suffix) = (parts[0], parts[1]);
        return (prefix.is_empty() || path.starts_with(prefix))
            && (suffix.is_empty() || path.ends_with(suffix));
    }

    path.contains(pattern.trim_matches('*'))
}

#[path = "rule_discovery_claude.rs"]
mod claude_scoped;

fn blake3_short(content: &str) -> String {
    let hash = blake3::hash(content.as_bytes());
    hash.to_hex()[..8].to_string()
}

// ── Tests ───────────────────────────────────────────────────────────────────

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

    const BANNERED_RULE: &str = "*** TOP SECRET ***\nAlways deploy through the launch window.\n";
    const INJECTING: &str = "[setup]\nauto_inject_rules = true\n";

    fn isolated(config: &str) -> crate::core::data_dir::IsolatedDataDir {
        let data = crate::core::data_dir::isolated_data_dir();
        let dir = crate::core::paths::config_dir_read_only().expect("isolated config dir");
        std::fs::create_dir_all(&dir).expect("config dir");
        std::fs::write(dir.join("config.toml"), config).expect("config");
        data
    }

    /// A project with one source file; returns the canonical root and file.
    fn rule_project(rules: &[(&str, &str)]) -> (tempfile::TempDir, String, String) {
        let directory = tempfile::tempdir().expect("project");
        let root = directory.path().canonicalize().expect("canonical root");
        std::fs::create_dir_all(root.join("src")).expect("source dir");
        let file = root.join("src").join("main.rs");
        std::fs::write(&file, "fn main() {}\n").expect("source");
        for (name, content) in rules {
            std::fs::write(root.join(name), content).expect("rule file");
        }
        let root = root.to_str().expect("utf-8 root").to_owned();
        let file = file.to_str().expect("utf-8 file").to_owned();
        (directory, root, file)
    }

    /// A rule file the gateway withholds contributes nothing to a `ctx_read`
    /// reply: not its text and not its name. Before, discovery read it with
    /// `read_to_string` and appended it unadmitted. Once the file admits, the
    /// reply carries what the admitted reader delivers — not the text the
    /// discovery cache still holds.
    #[test]
    fn a_withheld_rule_file_is_absent_from_the_reply() {
        let _data = isolated(&format!(
            "{INJECTING}[context_gateway]\nclassification = \"block\"\n"
        ));
        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
        let _injection = crate::test_env::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
        let (_directory, root, file) = rule_project(&[("AGENTS.md", BANNERED_RULE)]);

        reset_injection_cache();
        let suffix = rules_suffix_for_read(&file, &root, "opencode");
        assert!(
            suffix.is_empty(),
            "a withheld rule file must add nothing, got: {suffix:?}"
        );

        std::fs::write(
            Path::new(&root).join("AGENTS.md"),
            "Always write regression tests.\n",
        )
        .expect("declassified rule file");
        let suffix = rules_suffix_for_read(&file, &root, "opencode");
        assert!(
            suffix.contains("Always write regression tests."),
            "{suffix:?}"
        );
        assert!(!suffix.contains("launch window"), "{suffix:?}");
    }

    /// An admitted rule file is part of the reply AND of the call's source
    /// set: the admitted reader publishes it, so the reply's lineage is
    /// complete without marking it unknown, and it stops admitting once the
    /// rule file is reclassified. A withheld sibling adds neither text, name
    /// nor an unbound source.
    #[tokio::test]
    async fn an_admitted_rule_file_is_published_as_a_source_of_the_reply() {
        let _data = isolated(&format!(
            "{INJECTING}[context_gateway]\nmode = \"governed\"\nclassification = \"block\"\n"
        ));
        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
        let _injection = crate::test_env::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
        let (_directory, root, file) = rule_project(&[
            ("CLAUDE.md", "Prefer small modules.\n"),
            ("AGENTS.md", BANNERED_RULE),
        ]);

        reset_injection_cache();
        let (suffix, authority) = crate::core::archive::authority::capture(async {
            rules_suffix_for_read(&file, &root, "opencode")
        })
        .await;
        assert!(suffix.contains("[From: CLAUDE.md]"), "{suffix:?}");
        assert!(suffix.contains("Prefer small modules."), "{suffix:?}");
        for withheld in ["launch window", "TOP SECRET", "AGENTS.md"] {
            assert!(!suffix.contains(withheld), "{withheld}: {suffix:?}");
        }

        let authority = authority.expect("the admitted reader published the rule file");
        assert!(!authority.is_incomplete(), "the withheld rule is no source");
        let admitted = || {
            crate::core::policy::runtime::REQUEST_PROJECT.sync_scope(
                std::cell::RefCell::new(Some(std::path::PathBuf::from(&root))),
                || {
                    crate::core::policy::runtime::with_source_view(|| authority.admitted())
                        .unwrap_or(false)
                },
            )
        };
        assert!(admitted(), "unchanged rule file: the reply may be reused");
        std::fs::write(Path::new(&root).join("CLAUDE.md"), BANNERED_RULE).expect("reclassify");
        assert!(!admitted(), "reclassified rule file: no reuse");
    }

    fn suffix_tokens(suffix: &str) -> usize {
        let body = suffix
            .strip_prefix("\n\n--- Rules in scope for this file ---\n")
            .expect("suffix header");
        crate::core::tokens::count_tokens(body)
    }

    /// #2229: the cap applies to the first rule too. A rule file far larger
    /// than the budget is replaced by a pointer to its file instead of being
    /// appended whole, and the pointer counts as injected.
    #[test]
    fn an_oversized_first_rule_is_replaced_by_a_pointer() {
        let _data = isolated(INJECTING);
        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
        let _injection = crate::test_env::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
        let large = "Always keep the build green and document every decision.\n".repeat(1_000);
        let (_directory, root, file) = rule_project(&[("AGENTS.md", &large)]);

        reset_injection_cache();
        let suffix = rules_suffix_for_read(&file, &root, "opencode");
        assert!(suffix.contains("[From: AGENTS.md]"), "{suffix:?}");
        let source = Path::new(&root).join("AGENTS.md");
        assert!(
            suffix.contains(&format!(
                "[Rule body omitted; authoritative source: {}]",
                source.display()
            )),
            "{suffix:?}"
        );
        assert!(!suffix.contains("keep the build green"), "{suffix:?}");
        assert!(
            suffix_tokens(&suffix) <= MAX_RULES_SUFFIX_TOKENS,
            "{suffix:?}"
        );
        assert_eq!(
            suffix,
            {
                reset_injection_cache();
                rules_suffix_for_read(&file, &root, "opencode")
            },
            "deterministic"
        );

        let again = rules_suffix_for_read(&file, &root, "opencode");
        assert!(again.is_empty(), "the pointer was injected: {again:?}");
    }

    /// #2229: a rule whose pointer no longer fits is only named and is not
    /// marked injected, so the next read offers it again.
    #[test]
    fn a_rule_that_does_not_fit_is_named_and_offered_again() {
        let _data = isolated(INJECTING);
        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
        let _injection = crate::test_env::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
        // A CLAUDE.md body that fills the budget up to a few tokens.
        let mut claude = String::from("Prefer small modules.");
        while crate::core::tokens::count_tokens(&format!("[From: CLAUDE.md]\n{claude} word"))
            <= MAX_RULES_SUFFIX_TOKENS - 2
        {
            claude.push_str(" word");
        }
        let large = "Always keep the build green and document every decision.\n".repeat(1_000);
        let (_directory, root, file) =
            rule_project(&[("CLAUDE.md", &claude), ("AGENTS.md", &large)]);

        reset_injection_cache();
        let first = rules_suffix_for_read(&file, &root, "opencode");
        assert!(first.contains("Prefer small modules."), "{first:?}");
        assert!(!first.contains("keep the build green"), "{first:?}");
        assert!(!first.contains("authoritative source"), "{first:?}");
        assert!(
            first
                .contains("[Rules in scope not shown (size limit); read them directly: AGENTS.md]"),
            "{first:?}"
        );

        let second = rules_suffix_for_read(&file, &root, "opencode");
        assert!(!second.contains("Prefer small modules."), "{second:?}");
        assert!(second.contains("[From: AGENTS.md]"), "{second:?}");
        assert!(
            second.contains("[Rule body omitted; authoritative source:"),
            "{second:?}"
        );
        assert!(
            suffix_tokens(&second) <= MAX_RULES_SUFFIX_TOKENS,
            "{second:?}"
        );

        assert!(rules_suffix_for_read(&file, &root, "opencode").is_empty());
    }

    #[test]
    fn explicit_auto_inject_false_suppresses_ctx_read_rule_discovery() {
        let _guard = crate::core::data_dir::test_env_lock();
        let tmp = tempfile::tempdir().expect("tempdir");
        let config_dir = tmp.path().join("config");
        let project = tmp.path().join("project");
        let source_dir = project.join("src");
        let file = source_dir.join("main.rs");

        std::fs::create_dir_all(&config_dir).unwrap();
        std::fs::create_dir_all(&source_dir).unwrap();
        std::fs::write(&file, "fn main() {}\n").unwrap();
        std::fs::write(
            project.join("AGENTS.md"),
            "# Project rules\nAlways write regression tests.\n",
        )
        .unwrap();

        let _config_guard = crate::test_env::EnvVarGuard::set(
            "LEAN_CTX_CONFIG_DIR",
            config_dir.to_string_lossy().as_ref(),
        );
        let _injection_guard =
            crate::test_env::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");

        std::fs::write(
            config_dir.join("config.toml"),
            "[setup]\nauto_inject_rules = true\n",
        )
        .unwrap();

        reset_injection_cache();
        let enabled = rules_suffix_for_read(
            file.to_string_lossy().as_ref(),
            project.to_string_lossy().as_ref(),
            "opencode",
        );

        assert!(
            enabled.contains("Always write regression tests."),
            "test precondition failed: enabled rule discovery produced {enabled:?}"
        );

        std::fs::write(
            config_dir.join("config.toml"),
            "[setup]\nauto_inject_rules = false\n",
        )
        .unwrap();

        reset_injection_cache();
        let disabled = rules_suffix_for_read(
            file.to_string_lossy().as_ref(),
            project.to_string_lossy().as_ref(),
            "opencode",
        );

        assert!(
            disabled.is_empty(),
            "explicit auto_inject_rules=false must suppress ctx_read rule discovery, got: {disabled:?}"
        );
    }

    /// A project tree for the Claude tests; returns the canonical root.
    fn claude_project(files: &[(&str, &str)]) -> (tempfile::TempDir, String) {
        let directory = tempfile::tempdir().expect("project");
        let root = directory.path().canonicalize().expect("canonical root");
        for (name, content) in files {
            let path = root.join(name);
            std::fs::create_dir_all(path.parent().expect("parent")).expect("dirs");
            std::fs::write(path, content).expect("file");
        }
        let root = root.to_str().expect("utf-8 root").to_owned();
        (directory, root)
    }

    fn claude_read(root: &str, file: &str) -> String {
        rules_suffix_for_read(&format!("{root}/{file}"), root, "claude-code")
    }

    /// Claude Code loads a subdirectory's CLAUDE.md only when its native Read
    /// touches a file there. In replace mode lean-ctx delivers it, once, and
    /// never the root CLAUDE.md Claude Code already loaded at launch.
    #[test]
    fn claude_gets_the_nested_claude_md_once_and_never_the_root_one() {
        let _data = isolated(INJECTING);
        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
        let _injection = crate::test_env::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
        let (_directory, root) = claude_project(&[
            ("CLAUDE.md", "Root launch rule.\n"),
            ("AGENTS.md", "Root agents rule.\n"),
            ("src/CLAUDE.md", "Nested source rule.\n"),
            ("src/CLAUDE.local.md", "Nested local note.\n"),
            ("src/main.rs", "fn main() {}\n"),
            ("docs/guide.md", "# Guide\n"),
        ]);

        reset_injection_cache();
        let first = claude_read(&root, "src/main.rs");
        assert!(
            first.contains("[From: src/CLAUDE.md]\nNested source rule."),
            "{first:?}"
        );
        assert!(first.contains("[From: src/CLAUDE.local.md]"), "{first:?}");
        assert!(
            first.find("src/CLAUDE.md]").unwrap() < first.find("src/CLAUDE.local.md]").unwrap(),
            "CLAUDE.local.md comes last per directory: {first:?}"
        );
        for launch_time in [
            "Root launch rule.",
            "Root agents rule.",
            "[From: CLAUDE.md]",
        ] {
            assert!(!first.contains(launch_time), "{launch_time}: {first:?}");
        }
        assert!(
            claude_read(&root, "src/main.rs").is_empty(),
            "injected once"
        );
        assert!(
            claude_read(&root, "docs/guide.md").is_empty(),
            "other subtree"
        );
    }

    /// `.claude/rules` with `paths:` load when a matching file is read: the
    /// YAML list, the scalar and the comma-separated forms, brace expansion,
    /// and nothing for unscoped root rules or non-matching files.
    #[test]
    fn claude_gets_path_scoped_rules_in_every_paths_form() {
        let _data = isolated(INJECTING);
        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
        let _injection = crate::test_env::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
        let (_directory, root) = claude_project(&[
            (
                ".claude/rules/api.md",
                "---\npaths:\n  - \"src/api/**/*.{ts,tsx}\"\n  - 'lib/**/*.ts'\n---\nList rule.\n",
            ),
            (
                ".claude/rules/scalar.md",
                "---\npaths: \"*.tsx\"\n---\nScalar rule.\n",
            ),
            (
                ".claude/rules/nested/flow.md",
                "---\npaths: [\"src/api/*.ts\", \"tests/**\"]\n---\nFlow rule.\n",
            ),
            (
                ".claude/rules/other.md",
                "---\npaths:\n  - \"docs/**\"\n---\nDocs rule.\n",
            ),
            (".claude/rules/always.md", "Unscoped launch rule.\n"),
            ("src/api/deep/view.tsx", "export {}\n"),
            ("src/api/handler.ts", "export {}\n"),
            ("src/main.py", "pass\n"),
        ]);

        reset_injection_cache();
        let tsx = claude_read(&root, "src/api/deep/view.tsx");
        assert!(tsx.contains("List rule."), "{tsx:?}");
        assert!(tsx.contains("Scalar rule."), "{tsx:?}");
        for absent in ["Flow rule.", "Docs rule.", "Unscoped launch rule."] {
            assert!(!tsx.contains(absent), "{absent}: {tsx:?}");
        }

        let ts = claude_read(&root, "src/api/handler.ts");
        assert!(
            ts.contains("[From: .claude/rules/nested/flow.md]"),
            "{ts:?}"
        );
        assert!(!ts.contains("List rule."), "already injected: {ts:?}");

        assert!(claude_read(&root, "src/main.py").is_empty());
    }

    /// The suffix is a function of the files (#498): same project, same
    /// bytes, rule files in path order.
    #[test]
    fn claude_rules_suffix_is_deterministic() {
        let _data = isolated(INJECTING);
        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
        let _injection = crate::test_env::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
        let mut files: Vec<(String, String)> = (0..12)
            .map(|i| {
                (
                    format!(".claude/rules/r{i:02}.md"),
                    format!("---\npaths: \"**/*.rs\"\n---\nRule {i}.\n"),
                )
            })
            .collect();
        files.push(("crates/a/CLAUDE.md".into(), "Crate rule.\n".into()));
        files.push(("crates/a/src/lib.rs".into(), "\n".into()));
        let files: Vec<(&str, &str)> = files
            .iter()
            .map(|(a, b)| (a.as_str(), b.as_str()))
            .collect();
        let (_directory, root) = claude_project(&files);

        reset_injection_cache();
        let first = claude_read(&root, "crates/a/src/lib.rs");
        reset_injection_cache();
        claude_scoped::reset_cache();
        let second = claude_read(&root, "crates/a/src/lib.rs");
        assert!(!first.is_empty());
        assert_eq!(first, second);
        let positions: Vec<usize> = (0..12)
            .filter_map(|i| first.find(&format!("Rule {i}.")))
            .collect();
        assert!(positions.windows(2).all(|w| w[0] < w[1]), "{first:?}");
        assert!(
            first.find("Rule 11.") < first.find("Crate rule."),
            "root rules first: {first:?}"
        );
        assert!(
            suffix_tokens(&first) <= MAX_RULES_SUFFIX_TOKENS,
            "{first:?}"
        );
    }

    /// With no CLAUDE.md at the root, Claude Code reads AGENTS.md and loads a
    /// subdirectory's AGENTS.md lazily; nested `.claude/rules` are lazy too.
    #[test]
    fn claude_in_agents_md_mode_gets_the_nested_agents_md_and_nested_rules() {
        let _data = isolated(INJECTING);
        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
        let _injection = crate::test_env::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
        let (_directory, root) = claude_project(&[
            ("AGENTS.md", "Root agents rule.\n"),
            ("pkg/AGENTS.md", "Package agents rule.\n"),
            ("pkg/.claude/rules/style.md", "Package style rule.\n"),
            (
                "pkg/.claude/rules/go.md",
                "---\npaths: \"*.go\"\n---\nGo rule.\n",
            ),
            ("pkg/main.rs", "fn main() {}\n"),
        ]);

        reset_injection_cache();
        let suffix = claude_read(&root, "pkg/main.rs");
        assert!(suffix.contains("Package agents rule."), "{suffix:?}");
        assert!(suffix.contains("Package style rule."), "{suffix:?}");
        assert!(!suffix.contains("Root agents rule."), "{suffix:?}");
        assert!(!suffix.contains("Go rule."), "{suffix:?}");
    }

    /// Files under `<root>/.claude` are the root's own configuration: reading
    /// one must not re-inject the launch-time `.claude/CLAUDE.md` (or
    /// `.claude/AGENTS.md`), while root path-scoped rules still apply.
    #[test]
    fn claude_reading_inside_dot_claude_does_not_reinject_launch_files() {
        let _data = isolated(INJECTING);
        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
        let _injection = crate::test_env::EnvVarGuard::set("LEAN_CTX_RULES_INJECTION", "shared");
        let (_directory, root) = claude_project(&[
            (".claude/CLAUDE.md", "Root launch rule.\n"),
            (".claude/AGENTS.md", "Root agents rule.\n"),
            (".claude/settings.json", "{}\n"),
            (".claude/agents/reviewer.md", "Reviewer.\n"),
            (
                ".claude/rules/json.md",
                "---\npaths: \"*.json\"\n---\nJson rule.\n",
            ),
        ]);

        reset_injection_cache();
        let settings = claude_read(&root, ".claude/settings.json");
        assert!(!settings.contains("Root launch rule."), "{settings:?}");
        assert!(!settings.contains("Root agents rule."), "{settings:?}");
        assert!(settings.contains("Json rule."), "{settings:?}");
        assert!(claude_read(&root, ".claude/agents/reviewer.md").is_empty());
        assert!(claude_read(&root, ".claude/rules/json.md").is_empty());
    }

    #[test]
    fn frontmatter_patterns_read_every_paths_form() {
        let list = "---\npaths:\n  - \"src/**/*.{ts,tsx}\"\n\n  - lib/*.ts\nother: x\n---\n";
        assert_eq!(
            frontmatter_patterns(list, &["paths"]),
            vec!["src/**/*.{ts,tsx}", "lib/*.ts"]
        );
        let scalar = "---\npaths: \"src/*.{ts,tsx}, docs/**\"\n---\n";
        assert_eq!(
            frontmatter_patterns(scalar, &["paths"]),
            vec!["src/*.{ts,tsx}", "docs/**"]
        );
        let flow = "---\npaths: ['a/*.rs', \"b/**\"]\n---\n";
        assert_eq!(
            frontmatter_patterns(flow, &["paths"]),
            vec!["a/*.rs", "b/**"]
        );
        assert!(frontmatter_patterns("---\npathsx: a\n---\n", &["paths"]).is_empty());
        assert_eq!(
            extract_globs("---\npaths:\n  - \"*.rs\"\n---\n"),
            Some(vec!["*.rs".to_string()])
        );
    }

    #[test]
    fn glob_matches_extension() {
        assert!(glob_matches("*.rs", "src/main.rs"));
        assert!(glob_matches("*.rs", "main.rs"));
        assert!(!glob_matches("*.rs", "src/main.py"));
    }

    #[test]
    fn glob_matches_double_star() {
        assert!(glob_matches("**/test_*.rs", "src/tests/test_foo.rs"));
        assert!(glob_matches("**/test_*.rs", "test_foo.rs"));
        assert!(!glob_matches("**/test_*.rs", "src/foo.rs"));
    }

    #[test]
    fn glob_matches_exact() {
        assert!(glob_matches("src/main.rs", "src/main.rs"));
        assert!(!glob_matches("src/main.rs", "src/lib.rs"));
    }

    #[test]
    fn extract_globs_cursor_mdc() {
        let content = "---\nglobs: \"*.rs, *.toml\"\n---\nSome rule content";
        let patterns = extract_globs(content).unwrap();
        assert_eq!(patterns, vec!["*.rs", "*.toml"]);
    }

    #[test]
    fn extract_globs_claude_path() {
        let content = "---\npath: src/**/*.ts\n---\nRule for TS files";
        let patterns = extract_globs(content).unwrap();
        assert_eq!(patterns, vec!["src/**/*.ts"]);
    }

    #[test]
    fn extract_globs_no_frontmatter() {
        let content = "Just a plain markdown rule file";
        assert!(extract_globs(content).is_none());
    }

    #[test]
    fn format_suffix_empty_when_no_rules() {
        // The dedup set is process-wide: serialize with the other rule tests.
        let _lock = crate::core::data_dir::test_env_lock();
        reset_injection_cache();
        let suffix = rules_suffix_for_read("/nonexistent/file.rs", "/nonexistent", "cursor");
        assert!(suffix.is_empty(), "{suffix:?}");
    }

    #[test]
    fn dedup_prevents_reinjection() {
        // The dedup set is process-wide: serialize with the other rule tests.
        let _lock = crate::core::data_dir::test_env_lock();
        reset_injection_cache();
        let key = "test:abc12345";
        assert!(!already_injected(key));
        assert!(already_injected(key));
    }

    #[test]
    fn always_apply_detected() {
        let content = "---\ndescription: test\nalwaysApply: true\n---\nRule body";
        assert!(is_always_apply(content));
    }

    #[test]
    fn always_apply_false_not_detected() {
        let content = "---\ndescription: test\nalwaysApply: false\n---\nRule body";
        assert!(!is_always_apply(content));
    }

    #[test]
    fn no_frontmatter_not_always_apply() {
        let content = "Just a plain rule without frontmatter";
        assert!(!is_always_apply(content));
    }

    #[test]
    fn filter_skips_always_apply_rules() {
        let rules = vec![
            DiscoveredRule {
                source: ".cursor/rules/always.mdc".into(),
                content: "---\nalwaysApply: true\n---\nAlready in system prompt".into(),
            },
            DiscoveredRule {
                source: ".cursor/rules/scoped.mdc".into(),
                content: "---\nglobs: \"*.rs\"\n---\nRust-scoped rule".into(),
            },
            DiscoveredRule {
                source: ".cursor/rules/no-frontmatter.mdc".into(),
                content: "Rule without frontmatter".into(),
            },
            DiscoveredRule {
                source: "AGENTS.md".into(),
                content: "Agent instructions".into(),
            },
        ];
        let filtered = filter_by_path(&rules, "/project/src/main.rs", "/project");
        let sources: Vec<&str> = filtered.iter().map(|r| r.source.as_str()).collect();
        assert!(
            sources.contains(&"AGENTS.md"),
            "hierarchy rules always pass"
        );
        assert!(
            sources.contains(&".cursor/rules/scoped.mdc"),
            "glob-matched rules pass"
        );
        assert!(
            !sources.contains(&".cursor/rules/always.mdc"),
            "alwaysApply skipped"
        );
        assert!(
            !sources.contains(&".cursor/rules/no-frontmatter.mdc"),
            "no-frontmatter skipped"
        );
    }

    #[test]
    fn rules_suffix_completes_within_budget() {
        // The dedup set is process-wide: serialize with the other rule tests.
        let _lock = crate::core::data_dir::test_env_lock();
        reset_injection_cache();
        let start = std::time::Instant::now();
        for _ in 0..100 {
            let _ =
                rules_suffix_for_read("/tmp/nonexistent/src/main.rs", "/tmp/nonexistent", "cursor");
        }
        let elapsed = start.elapsed();
        let per_call_us = elapsed.as_micros() / 100;
        assert!(
            per_call_us < 5_000,
            "rule discovery too slow: {per_call_us}μs per call (budget: 5ms)"
        );
    }

    #[test]
    fn real_project_overhead_acceptable() {
        // The dedup set is process-wide: serialize with the other rule tests.
        let _lock = crate::core::data_dir::test_env_lock();
        reset_injection_cache();
        let manifest = env!("CARGO_MANIFEST_DIR");
        // The repository root: this crate sits at rust/crates/lean-ctx-engine-ext.
        let project_root = std::path::Path::new(manifest)
            .ancestors()
            .nth(3)
            .unwrap()
            .to_str()
            .unwrap();
        let file = format!("{manifest}/src/core/rule_discovery.rs");

        // Cold call (no cache, does filesystem I/O)
        let start = std::time::Instant::now();
        let suffix = rules_suffix_for_read(&file, project_root, "cursor");
        let cold_us = start.elapsed().as_micros();

        // Warm calls (directory cache hit, only dedup check)
        let start = std::time::Instant::now();
        for _ in 0..100 {
            reset_injection_cache();
            let _ = rules_suffix_for_read(&file, project_root, "cursor");
        }
        let warm_us = start.elapsed().as_micros() / 100;

        eprintln!("\n=== Rule Discovery Performance ===");
        eprintln!(
            "Cold: {cold_us}μs | Warm: {warm_us}μs | Rules: {} bytes",
            suffix.len()
        );

        assert!(
            cold_us < 50_000,
            "cold call too slow: {cold_us}μs (budget: 50ms)"
        );
        assert!(
            warm_us < 5_000,
            "warm call too slow: {warm_us}μs (budget: 5ms)"
        );
    }
}