lean-ctx-engine 3.12.2

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and 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
//! Cross-channel rule deduplication policy (#684).
//!
//! lean-ctx publishes its guidance through several "channels":
//!   * per-client global rule files (`~/.cursor/rules/lean-ctx.mdc`, …),
//!   * the shared project `AGENTS.md` (Cursor, Codex and other agents all
//!     auto-load it),
//!   * the MCP server `instructions` block (sent on every `initialize`).
//!
//! Several agents read more than one channel, so the *same* guidance can be
//! billed two or three times per session. This module centralises the policy
//! that decides, per client, which channel is the single canonical carrier — so
//! the writers (`compression` inject, hooks), the repair command
//! (`lean-ctx rules dedup`) and the honest accounting (`doctor overhead`) all
//! agree on one source of truth.

use std::path::Path;

/// Markers of the heavy compression / output-style block — the per-turn payload
/// that actually drives cross-channel duplication. Defined in `rules_canonical`
/// (the single marker source of truth) and re-exported here so the coverage/dedup
/// readers and the `render()` writer can never disagree (#548).
pub use crate::core::rules_canonical::{COMPRESSION_BLOCK_END, COMPRESSION_BLOCK_START};

/// The agents that auto-load the shared project `AGENTS.md`. Kept in sync with
/// `core::rules_overhead::collect_rules_files`, which attributes `AGENTS.md` to
/// the same set.
pub const AGENTS_MD_READERS: &[&str] = &["cursor", "codex", "opencode", "codewhale"];

/// True when `content` carries a *full* lean-ctx payload — the canonical rule
/// set (the `RULES_MARKER` header) or the compression/output-style block —
/// rather than just the lightweight `<!-- lean-ctx -->` cross-reference pointer.
///
/// A pointer-only file (a thinned `AGENTS.md` / `.cursorrules` that merely says
/// "the full rules live in the canonical file") does not duplicate guidance and
/// must not be counted as a second source for its client.
pub fn carries_full_rules(content: &str) -> bool {
    carries_rules_block(content) || content.contains(COMPRESSION_BLOCK_START)
}

/// Version marker of the Claude Code `CLAUDE.md` block
/// (`<!-- lean-ctx-claude-vN -->`, `hooks/agents/claude.rs`). The block sits
/// between the pointer markers but carries the full Claude tool mapping, so
/// it is a rules channel, not a pointer.
pub const CLAUDE_BLOCK_MARKER_PREFIX: &str = "<!-- lean-ctx-claude-v";

fn has_marker_line_with_prefix(content: &str, prefix: &str) -> bool {
    content
        .lines()
        .any(|line| line.trim_start().starts_with(prefix))
}

/// True when `content` carries a lean-ctx *rules* block (tool mapping), as
/// opposed to only the compression payload or the pointer: the canonical
/// block, a legacy versioned block (`<!-- lean-ctx-rules-v9 -->`, #1289) or
/// the Claude Code `CLAUDE.md` block. These are the payloads the MCP
/// instructions skeleton repeats, so two of them in one host session are a
/// duplicate rules channel.
pub fn carries_rules_block(content: &str) -> bool {
    content.contains(crate::core::rules_canonical::START_MARK)
        || has_marker_line_with_prefix(content, crate::core::rules_canonical::RULES_MARKER_PREFIX)
        || has_marker_line_with_prefix(content, CLAUDE_BLOCK_MARKER_PREFIX)
}

/// Claude Code auto-loads `CLAUDE.md` from its state dir (`~/.claude`, or
/// `$CLAUDE_CONFIG_DIR`); covered once that file carries the lean-ctx block.
pub fn claude_md_carries_block(home: &Path) -> bool {
    std::fs::read_to_string(crate::core::editor_registry::claude_state_dir(home).join("CLAUDE.md"))
        .is_ok_and(|c| has_marker_line_with_prefix(&c, CLAUDE_BLOCK_MARKER_PREFIX))
}

/// True when `content` contains a lean-ctx block but only the lightweight
/// pointer (no canonical rules, no compression payload).
pub fn is_pointer_only(content: &str) -> bool {
    content.contains("<!-- lean-ctx") && !carries_full_rules(content)
}

fn file_has_compression(path: &Path) -> bool {
    std::fs::read_to_string(path).is_ok_and(|c| c.contains(COMPRESSION_BLOCK_START))
}

/// Cursor auto-loads `~/.cursor/rules/lean-ctx.mdc`; it is "covered" for the
/// compression payload once that canonical file carries the block.
pub fn cursor_compression_covered(home: &Path) -> bool {
    file_has_compression(&home.join(".cursor/rules/lean-ctx.mdc"))
}

/// True when the installed Cursor hooks already compress the native tools
/// (GL #1153): `~/.cursor/hooks.json` carries lean-ctx `preToolUse` entries
/// for BOTH the Shell rewrite and the Read/Grep redirect. Only then is the
/// "use ctx_* instead of native" mapping dead weight — with partial or no
/// hook coverage the full guidance stays.
pub fn cursor_hooks_cover_native_tools(home: &Path) -> bool {
    cursor_hooks_json_covers(&home.join(".cursor/hooks.json"))
}

/// Path-based core of [`cursor_hooks_cover_native_tools`], so the rules
/// injector can derive the hooks.json location from the mdc target path (the
/// two always live under the same `.cursor/` dir).
///
/// Conservative by construction: unreadable/invalid JSON, a missing file, or
/// a redirect that was manually removed all mean "not covered".
pub fn cursor_hooks_json_covers(hooks_json: &Path) -> bool {
    let Ok(content) = std::fs::read_to_string(hooks_json) else {
        return false;
    };
    let Ok(v) = crate::core::jsonc::parse_jsonc(&content) else {
        return false;
    };
    let Some(pre) = v.pointer("/hooks/preToolUse").and_then(|p| p.as_array()) else {
        return false;
    };
    let has_lean_ctx_hook = |suffix: &str| {
        pre.iter().any(|e| {
            e.get("command")
                .and_then(|c| c.as_str())
                .is_some_and(|c| c.contains("lean-ctx") && c.contains(suffix))
        })
    };
    has_lean_ctx_hook("hook rewrite") && has_lean_ctx_hook("hook redirect")
}

/// For the MCP `instructions` block: is `client_name` a host whose installed
/// lean-ctx hooks already compress the native tools? Drives the hook-aware
/// anchor wording (GL #1153) — repeating "ctx_* replaces native tools" to a
/// hook-covered Cursor re-creates exactly the instruction dissonance the
/// HookCovered profile removes.
pub fn client_hook_covered(client_name: &str, home: &Path) -> bool {
    let lower = client_name.to_lowercase();
    if lower.contains("cursor") {
        return cursor_hooks_cover_native_tools(home);
    }
    if lower.contains("codex") {
        return codex_hooks_cover_native_tools(home);
    }
    if lower.contains("windsurf") {
        return windsurf_hooks_cover_native_tools(home);
    }
    false
}

/// Codex hooks cover native tools when `~/.codex/hooks.json` has lean-ctx
/// `codex-pretooluse` in PreToolUse. The pretooluse handler provides
/// deny/redirect/rewrite for all tool types at runtime (mode-aware);
/// a separate `hook deny` entry is not installed or required.
fn codex_hooks_cover_native_tools(home: &Path) -> bool {
    let hooks_json = home.join(".codex").join("hooks.json");
    let Ok(content) = std::fs::read_to_string(&hooks_json) else {
        return false;
    };
    let Ok(v) = crate::core::jsonc::parse_jsonc(&content) else {
        return false;
    };
    let Some(pre) = v.pointer("/hooks/PreToolUse").and_then(|p| p.as_array()) else {
        return false;
    };
    let has_lean_ctx = |suffix: &str| {
        pre.iter().any(|e| {
            let in_command = e
                .get("command")
                .and_then(|c| c.as_str())
                .is_some_and(|c| c.contains("lean-ctx") && c.contains(suffix));
            let in_hooks_array = e
                .get("hooks")
                .and_then(|h| h.as_array())
                .is_some_and(|hooks| {
                    hooks.iter().any(|h| {
                        h.get("command")
                            .and_then(|c| c.as_str())
                            .is_some_and(|c| c.contains("lean-ctx") && c.contains(suffix))
                    })
                });
            in_command || in_hooks_array
        })
    };
    // codex-pretooluse handles deny/redirect/rewrite for all tool types
    // at runtime (mode-aware). No separate "hook deny" entry needed (#codex-ux).
    has_lean_ctx("hook codex-pretooluse")
}

/// Windsurf hooks cover native tools when
/// `~/.codeium/windsurf/hooks.json` has lean-ctx `rewrite` + `redirect`
/// in `pre_mcp_tool_use`.
fn windsurf_hooks_cover_native_tools(home: &Path) -> bool {
    let hooks_json = home.join(".codeium").join("windsurf").join("hooks.json");
    let Ok(content) = std::fs::read_to_string(&hooks_json) else {
        return false;
    };
    let Ok(v) = crate::core::jsonc::parse_jsonc(&content) else {
        return false;
    };
    let Some(pre) = v
        .pointer("/hooks/pre_mcp_tool_use")
        .and_then(|p| p.as_array())
    else {
        return false;
    };
    let has_lean_ctx = |suffix: &str| {
        pre.iter().any(|e| {
            e.get("command")
                .and_then(|c| c.as_str())
                .is_some_and(|c| c.contains("lean-ctx") && c.contains(suffix))
        })
    };
    has_lean_ctx("hook rewrite") && has_lean_ctx("hook redirect")
}

/// Codex's per-user config dir (`~/.codex`, or `$CODEX_HOME`).
fn codex_dir(home: &Path) -> std::path::PathBuf {
    crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"))
}

/// Codex is present on this machine when its config dir exists.
pub fn codex_present(home: &Path) -> bool {
    codex_dir(home).exists()
}

/// Codex auto-loads `~/.codex/AGENTS.md`; covered once it carries the block.
pub fn codex_compression_covered(home: &Path) -> bool {
    file_has_compression(&codex_dir(home).join("AGENTS.md"))
}

/// Decide whether the shared project `AGENTS.md` may drop its compression block
/// (keeping only the `<!-- lean-ctx -->` pointer). Safe ⇔ EVERY `AGENTS.md`
/// reader present on this machine already receives the compression payload from
/// its own canonical file.
///
/// Conservative by construction (#684, "thin only if covered"): if any reader
/// would lose the guidance, `AGENTS.md` stays the full carrier.
pub fn agents_md_can_thin(home: &Path) -> bool {
    if !cursor_compression_covered(home) {
        return false;
    }
    if codex_present(home) && !codex_compression_covered(home) {
        return false;
    }
    true
}

/// For the MCP `instructions` block: does `client_name` already auto-load the
/// compression payload from a rule file? If so, repeating the output-style
/// block in the per-session instructions is pure cross-channel duplication and
/// can be dropped (the file copy governs).
pub fn client_autoloads_compression(client_name: &str, home: &Path) -> bool {
    let lower = client_name.to_lowercase();
    if lower.is_empty() {
        return false;
    }
    if lower.contains("cursor") {
        return cursor_compression_covered(home);
    }
    if lower.contains("codex") {
        return codex_present(home) && codex_compression_covered(home);
    }
    if lower.contains("opencode") {
        let opencode_dir = home.join(".config/opencode");
        let dedicated = opencode_dir.join("rules/lean-ctx.md");
        let shared = opencode_dir.join("AGENTS.md");
        return file_has_compression(&dedicated) || file_has_compression(&shared);
    }
    false
}

fn file_has_canonical_rules(path: &Path) -> bool {
    std::fs::read_to_string(path)
        .is_ok_and(|c| crate::core::rules_canonical::RulesFile::parse(&c).has_content())
}

/// For the MCP `instructions` block: does `client_name` already auto-load the
/// *canonical rules* block (tool mapping, intent playbook, recovery line, …)
/// from its own rule file? If so, repeating the whole skeleton in the
/// per-session instructions bills the same guidance twice on every session
/// (#578) — the builder collapses it to a one-line anchor instead.
///
/// Carrier per client (kept in sync with `rules_inject::targets`):
///   * Cursor → `~/.cursor/rules/lean-ctx.mdc` (canonical rules block)
///   * Codex → `$CODEX_HOME/instructions.md` (canonical rules block)
///   * OpenCode → `~/.config/opencode/rules/lean-ctx.md` (dedicated) or
///     `~/.config/opencode/AGENTS.md` (shared)
///
///   * Claude Code → `CLAUDE.md` in its state dir (the `lean-ctx-claude-vN`
///     block, `hooks/agents/claude.rs`)
///   * Gemini CLI → `~/.gemini/GEMINI.md` (shared) or the dedicated file
///
/// Claude Code (A3, one rules channel per host): the `CLAUDE.md` block is the
/// single channel. It carries the Claude-specific guidance (Replace-mode
/// denials, the native-Read edit gate, auto memory) that cannot move into
/// the instructions — Claude Code cuts initialize `instructions` at 2048
/// chars, and the skeleton alone already fills ~1900. Repeating the mapping
/// there billed it twice per turn (instructions 468 tok → anchor path 112).
///
/// Conservative by construction: only clients whose auto-loaded carrier holds
/// the canonical block *right now* count. Any stale/removed file falls back to
/// the full skeleton.
pub fn client_autoloads_rules(client_name: &str, home: &Path) -> bool {
    let lower = client_name.to_lowercase();
    if lower.is_empty() {
        return false;
    }
    let client_id =
        crate::core::client_capabilities::ClientMcpCapabilities::detect(client_name).client_id;
    if dedicated_session_hook_carries_rules(&client_id, home) {
        return true;
    }
    match client_id.as_str() {
        "claude-code" => return claude_md_carries_block(home),
        "gemini-cli" => {
            return file_has_canonical_rules(&home.join(".gemini/GEMINI.md"))
                || file_has_canonical_rules(&crate::rules_inject::gemini_dedicated_rules_path(
                    home,
                ));
        }
        _ => {}
    }
    if lower.contains("cursor") {
        return file_has_canonical_rules(&home.join(".cursor/rules/lean-ctx.mdc"));
    }
    if lower.contains("codex") {
        return codex_present(home)
            && file_has_canonical_rules(&codex_dir(home).join("instructions.md"));
    }
    if lower.contains("opencode") {
        // OpenCode loads rules from either:
        // - ~/.config/opencode/AGENTS.md (shared mode)
        // - ~/.config/opencode/rules/lean-ctx.md (dedicated mode)
        let opencode_dir = home.join(".config/opencode");
        let dedicated = opencode_dir.join("rules/lean-ctx.md");
        let shared = opencode_dir.join("AGENTS.md");
        return file_has_canonical_rules(&dedicated) || file_has_canonical_rules(&shared);
    }
    false
}

/// Dedicated mode (#343, A3): no rules file is written; the SessionStart
/// `hook observe` injects the rules instead. When that hook is installed for
/// the host, it is the single rules channel and the MCP instructions anchor.
fn dedicated_session_hook_carries_rules(client_id: &str, home: &Path) -> bool {
    let cfg = crate::core::config::Config::load();
    if !cfg.dedicated_session_context_active() || cfg.declines_rule_steering() {
        return false;
    }
    let settings = match client_id {
        "claude-code" => crate::core::editor_registry::claude_state_dir(home).join("settings.json"),
        "codex" => codex_dir(home).join("hooks.json"),
        "codebuddy" => {
            crate::core::editor_registry::codebuddy_state_dir(home).join("settings.json")
        }
        _ => return false,
    };
    session_start_runs_observe(&settings)
}

/// True when the host's hook config runs `lean-ctx hook observe` on SessionStart
/// (`{"hooks": {"SessionStart": [{"hooks": [{"command": …}]}]}}`).
fn session_start_runs_observe(settings: &Path) -> bool {
    let Ok(content) = std::fs::read_to_string(settings) else {
        return false;
    };
    let Ok(v) = crate::core::jsonc::parse_jsonc(&content) else {
        return false;
    };
    let Some(groups) = v.pointer("/hooks/SessionStart").and_then(|g| g.as_array()) else {
        return false;
    };
    groups.iter().any(|group| {
        group
            .get("hooks")
            .and_then(|h| h.as_array())
            .is_some_and(|hooks| {
                hooks.iter().any(|hook| {
                    hook.get("command")
                        .and_then(|c| c.as_str())
                        .is_some_and(|c| c.contains("hook observe"))
                })
            })
    })
}

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

    const FULL_HEADER: &str = crate::core::rules_canonical::START_MARK;

    fn compression_block() -> String {
        format!("{COMPRESSION_BLOCK_START}\nOUTPUT STYLE\n{COMPRESSION_BLOCK_END}\n")
    }

    fn pointer_block() -> String {
        format!(
            "{}\n## lean-ctx\nFull rules: ~/.cursor/rules/lean-ctx.mdc\n{}\n",
            crate::core::rules_canonical::AGENTS_BLOCK_START,
            crate::core::rules_canonical::AGENTS_BLOCK_END,
        )
    }

    #[test]
    fn full_rules_detected_for_canonical_header_and_compression() {
        let comp = compression_block();
        let ptr = pointer_block();
        assert!(carries_full_rules(&format!("{FULL_HEADER}\nbody\n")));
        assert!(carries_full_rules(&comp));
        assert!(carries_full_rules(&format!("{ptr}{comp}")));
    }

    #[test]
    fn pointer_only_block_is_not_full() {
        let ptr = pointer_block();
        assert!(!carries_full_rules(&ptr));
        assert!(is_pointer_only(&ptr));
    }

    #[test]
    fn plain_user_content_is_neither_full_nor_pointer() {
        let user = "# My project rules\njust some notes\n";
        assert!(!carries_full_rules(user));
        assert!(!is_pointer_only(user));
    }

    #[test]
    fn cursor_coverage_follows_mdc_block() {
        let comp = compression_block();
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        assert!(!cursor_compression_covered(home));

        std::fs::create_dir_all(home.join(".cursor/rules")).unwrap();
        std::fs::write(
            home.join(".cursor/rules/lean-ctx.mdc"),
            format!("{FULL_HEADER}\n{comp}"),
        )
        .unwrap();
        assert!(cursor_compression_covered(home));
    }

    #[test]
    fn agents_md_thins_only_when_cursor_covered_and_no_uncovered_codex() {
        let comp = compression_block();
        // Serialize CODEX_HOME mutation (tests share the process environment).
        let _guard = crate::core::data_dir::test_env_lock();
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();

        // No canonical mdc yet → AGENTS.md must stay the carrier.
        crate::test_env::set_var("CODEX_HOME", home.join(".codex"));
        assert!(!agents_md_can_thin(home));

        // Cursor covered, codex absent → safe to thin (the common case).
        // CODEX_HOME points at this isolated home so a real `~/.codex` on the
        // test machine cannot leak in.
        std::fs::create_dir_all(home.join(".cursor/rules")).unwrap();
        std::fs::write(
            home.join(".cursor/rules/lean-ctx.mdc"),
            format!("{FULL_HEADER}\n{comp}"),
        )
        .unwrap();
        assert!(agents_md_can_thin(home));

        // Codex present but uncovered → must NOT thin (codex would lose it).
        std::fs::create_dir_all(home.join(".codex")).unwrap();
        assert!(codex_present(home));
        assert!(!agents_md_can_thin(home));

        // Codex now covered by its own global AGENTS.md → safe to thin again.
        std::fs::write(home.join(".codex/AGENTS.md"), &comp).unwrap();
        assert!(agents_md_can_thin(home));
        crate::test_env::remove_var("CODEX_HOME");
    }

    #[test]
    fn client_autoloads_rules_requires_canonical_block_on_disk() {
        let _guard = crate::core::data_dir::test_env_lock();
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        crate::test_env::set_var("CODEX_HOME", home.join(".codex"));

        // Nothing installed → nobody is covered.
        assert!(!client_autoloads_rules("cursor", home));
        assert!(!client_autoloads_rules("codex", home));
        assert!(!client_autoloads_rules("", home));
        assert!(!client_autoloads_rules("claude-code", home));

        // Cursor covered once the mdc carries the canonical block.
        std::fs::create_dir_all(home.join(".cursor/rules")).unwrap();
        std::fs::write(
            home.join(".cursor/rules/lean-ctx.mdc"),
            format!("{FULL_HEADER}\nbody\n"),
        )
        .unwrap();
        assert!(client_autoloads_rules("cursor", home));
        assert!(client_autoloads_rules("cursor-vscode", home));

        // A pointer-only / non-canonical file must NOT count.
        std::fs::write(home.join(".cursor/rules/lean-ctx.mdc"), "user notes\n").unwrap();
        assert!(!client_autoloads_rules("cursor", home));

        // Codex covered via $CODEX_HOME/instructions.md.
        std::fs::create_dir_all(home.join(".codex")).unwrap();
        std::fs::write(
            home.join(".codex/instructions.md"),
            format!("{FULL_HEADER}\nbody\n"),
        )
        .unwrap();
        assert!(client_autoloads_rules("codex", home));
        crate::test_env::remove_var("CODEX_HOME");
    }

    #[test]
    fn cursor_hook_coverage_requires_both_pretooluse_entries() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        // No hooks.json at all.
        assert!(!cursor_hooks_cover_native_tools(home));
        assert!(!client_hook_covered("cursor", home));

        std::fs::create_dir_all(home.join(".cursor")).unwrap();
        let hooks = home.join(".cursor/hooks.json");

        // Rewrite only (Shell covered, Read/Grep not) → NOT covered.
        std::fs::write(
            &hooks,
            r#"{"version":1,"hooks":{"preToolUse":[
                {"matcher":"Shell","command":"/usr/local/bin/lean-ctx hook rewrite"}
            ]}}"#,
        )
        .unwrap();
        assert!(!cursor_hooks_cover_native_tools(home));

        // Rewrite + redirect → covered (exactly what install_cursor_hook_config writes).
        std::fs::write(
            &hooks,
            r#"{"version":1,"hooks":{"preToolUse":[
                {"matcher":"Shell","command":"/usr/local/bin/lean-ctx hook rewrite"},
                {"matcher":"Read|Grep","command":"/usr/local/bin/lean-ctx hook redirect"}
            ]}}"#,
        )
        .unwrap();
        assert!(cursor_hooks_cover_native_tools(home));
        assert!(client_hook_covered("cursor", home));
        assert!(client_hook_covered("cursor-vscode", home));
        // Other clients never count as hook-covered via Cursor's hooks.json.
        assert!(!client_hook_covered("codex", home));
        assert!(!client_hook_covered("", home));

        // Foreign hooks (not lean-ctx) must not count.
        std::fs::write(
            &hooks,
            r#"{"version":1,"hooks":{"preToolUse":[
                {"matcher":"Shell","command":"/opt/other hook rewrite"},
                {"matcher":"Read|Grep","command":"/opt/other hook redirect"}
            ]}}"#,
        )
        .unwrap();
        assert!(!cursor_hooks_cover_native_tools(home));

        // Invalid JSON → fail closed (full guidance).
        std::fs::write(&hooks, "{ not json").unwrap();
        assert!(!cursor_hooks_cover_native_tools(home));
    }

    #[test]
    fn codex_hook_coverage_requires_pretooluse() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();

        assert!(!client_hook_covered("codex-cli", home));

        let codex_dir = home.join(".codex");
        std::fs::create_dir_all(&codex_dir).expect("create .codex dir");
        let hooks = codex_dir.join("hooks.json");

        // No hooks → not covered.
        std::fs::write(&hooks, r#"{"hooks":{"PreToolUse":[]}}"#).expect("write empty hooks");
        assert!(!codex_hooks_cover_native_tools(home));

        // codex-pretooluse alone is sufficient (it handles deny/redirect
        // at runtime, no separate deny entry needed).
        std::fs::write(
            &hooks,
            r#"{"hooks":{"PreToolUse":[
                {"hooks":[{"command":"/usr/local/bin/lean-ctx hook codex-pretooluse","type":"command","timeout":15}],"matcher":"Bash|Read|Grep|Glob"}
            ]}}"#,
        )
        .expect("write pretooluse hooks");
        assert!(codex_hooks_cover_native_tools(home));
        assert!(client_hook_covered("codex-cli", home));
        assert!(client_hook_covered("codex", home));
        // Cursor must NOT match via Codex hooks.
        assert!(!client_hook_covered("cursor", home));

        // Legacy setup with both deny + pretooluse also covered.
        std::fs::write(
            &hooks,
            r#"{"hooks":{"PreToolUse":[
                {"command":"/usr/local/bin/lean-ctx hook deny","matcher":"Read|Grep|Glob"},
                {"hooks":[{"command":"/usr/local/bin/lean-ctx hook codex-pretooluse","type":"command","timeout":15}],"matcher":"Bash"}
            ]}}"#,
        )
        .expect("write legacy hooks");
        assert!(codex_hooks_cover_native_tools(home));
    }

    #[test]
    fn windsurf_hook_coverage_requires_rewrite_and_redirect() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();

        assert!(!client_hook_covered("windsurf", home));

        let ws_dir = home.join(".codeium").join("windsurf");
        std::fs::create_dir_all(&ws_dir).expect("create .codeium/windsurf dir");
        let hooks = ws_dir.join("hooks.json");

        // rewrite only → NOT covered.
        std::fs::write(
            &hooks,
            r#"{"hooks":{"pre_mcp_tool_use":[
                {"command":"/usr/local/bin/lean-ctx hook rewrite"}
            ]}}"#,
        )
        .expect("write rewrite-only hooks");
        assert!(!windsurf_hooks_cover_native_tools(home));

        // Both rewrite + redirect → covered.
        std::fs::write(
            &hooks,
            r#"{"hooks":{"pre_mcp_tool_use":[
                {"command":"/usr/local/bin/lean-ctx hook rewrite"},
                {"command":"/usr/local/bin/lean-ctx hook redirect"}
            ]}}"#,
        )
        .expect("write full hooks");
        assert!(windsurf_hooks_cover_native_tools(home));
        assert!(client_hook_covered("windsurf", home));
        // Other clients must NOT match.
        assert!(!client_hook_covered("cursor", home));
        assert!(!client_hook_covered("codex", home));
    }

    #[test]
    fn opencode_autoloads_rules_from_shared_agents_md() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        assert!(!client_autoloads_rules("opencode", home));

        std::fs::create_dir_all(home.join(".config/opencode")).unwrap();
        std::fs::write(
            home.join(".config/opencode/AGENTS.md"),
            format!("{FULL_HEADER}\nbody\n"),
        )
        .unwrap();
        assert!(client_autoloads_rules("opencode", home));
    }

    #[test]
    fn opencode_autoloads_rules_from_dedicated_rules_file() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();

        std::fs::create_dir_all(home.join(".config/opencode/rules")).unwrap();
        std::fs::write(
            home.join(".config/opencode/rules/lean-ctx.md"),
            format!("{FULL_HEADER}\nbody\n"),
        )
        .unwrap();
        assert!(client_autoloads_rules("opencode", home));
    }

    #[test]
    fn client_autoloads_compression_is_client_aware() {
        let comp = compression_block();
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        std::fs::create_dir_all(home.join(".cursor/rules")).unwrap();
        std::fs::write(
            home.join(".cursor/rules/lean-ctx.mdc"),
            format!("{FULL_HEADER}\n{comp}"),
        )
        .unwrap();

        assert!(client_autoloads_compression("Cursor", home));
        assert!(client_autoloads_compression("cursor-vscode", home));
        // Empty / unknown clients never auto-load a file copy.
        assert!(!client_autoloads_compression("", home));
        assert!(!client_autoloads_compression("some-other-agent", home));
    }

    #[test]
    fn render_output_is_detected_as_compression_coverage() {
        // The slice's core guarantee (#548 B2): the bytes the writer (`render`)
        // emits into a carrier file are recognised by the coverage detection the
        // MCP cross-channel dedup depends on. Before the unified marker model,
        // render embedded the prompt inline (no markers) so this was always
        // false → Cursor was billed for the compression block twice (rule file +
        // every MCP session).
        use crate::core::config::CompressionLevel;
        use crate::core::rules_canonical::{Wrapper, render};
        use crate::core::tool_profiles::ToolProfile;

        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        assert!(!cursor_compression_covered(home));

        let tp = ToolProfile::Power;
        let block = render(false, Wrapper::Dedicated, CompressionLevel::Standard, &tp);
        std::fs::create_dir_all(home.join(".cursor/rules")).unwrap();
        std::fs::write(home.join(".cursor/rules/lean-ctx.mdc"), &block).unwrap();

        assert!(cursor_compression_covered(home));
        assert!(client_autoloads_compression("cursor", home));

        let off = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp);
        std::fs::write(home.join(".cursor/rules/lean-ctx.mdc"), &off).unwrap();
        assert!(!cursor_compression_covered(home));
    }
}