Skip to main content

lean_ctx/
instructions.rs

1use crate::core::config::CompressionLevel;
2use crate::core::rules_canonical::{self as rc, Wrapper};
3use crate::tools::CrpMode;
4
5/// Universal instruction cap for all MCP clients (in tokens, not bytes).
6const INSTRUCTION_CAP_TOKENS: usize = 800;
7
8/// Token budget for the static instruction skeleton (no session/knowledge
9/// state).  Asserted in CI so instruction creep cannot silently tax every
10/// session. Measured at compression `Off` (the test pins `LEAN_CTX_COMPRESSION=off`)
11/// so the budget is deterministic across dev machines, not just clean CI (#498).
12/// Raised in reviewed steps: 520→540 / 600→640 for the sharpened ctx_* redirects
13/// (#1030), then 540→590 / 640→680 (#609 loop one-liner), then 590→615 / 680→712
14/// (proactive `RECOVER` line). Lowered 615→545 / 712→675 by the v5 rules diet
15/// (#578): the COMPACT skeleton folded loop/paradox into INTENT (measured ~505 /
16/// ~639 + headroom). Clients whose rule file already carries the canonical block
17/// get a one-line anchor instead of the skeleton (`client_loads_rules_from_file`)
18/// and land far below even this.
19#[cfg(test)]
20const STATIC_INSTRUCTION_BUDGET_TOKENS: usize = 545;
21#[cfg(test)]
22const STATIC_INSTRUCTION_BUDGET_TDD_TOKENS: usize = 675;
23/// Windows carries a one-line SHELL hint inside the skeleton.
24#[cfg(all(test, windows))]
25const STATIC_INSTRUCTION_SHELL_HINT_TOKENS: usize = 25;
26#[cfg(all(test, not(windows)))]
27const STATIC_INSTRUCTION_SHELL_HINT_TOKENS: usize = 0;
28
29#[must_use]
30pub fn build_instructions(crp_mode: CrpMode) -> String {
31    build_instructions_with_client(crp_mode, "")
32}
33
34#[must_use]
35pub fn build_instructions_with_client(crp_mode: CrpMode, client_name: &str) -> String {
36    let cfg = crate::core::config::Config::load();
37    let minimal = cfg.minimal_overhead_effective_for_client(client_name);
38    let shadow = cfg.shadow_mode;
39    // Cross-channel dedup: if the client auto-loads compression from its own rule
40    // file, skip it here to avoid duplicate billing.
41    let level = if client_loads_compression_from_file(client_name) {
42        CompressionLevel::Off
43    } else {
44        CompressionLevel::effective(&cfg)
45    };
46    // persona-spec-v1 — non-coding personas carry their domain block
47    // (intent vocabulary + defaults) into the session instructions. Empty for
48    // the `coding` default, so the skeleton stays byte-identical (#498).
49    let persona_block = crate::core::persona::Persona::resolve(&cfg).prompt_block();
50    build_full_instructions(
51        crp_mode,
52        client_name,
53        minimal,
54        level,
55        shadow,
56        &persona_block,
57    )
58}
59
60/// Deterministic STATIC Claude Code instructions for the char-budget test: the
61/// cold first-contact handshake surface (skeleton + shell hint + decoder +
62/// CLAUDE.md pointer + guidance). It pins `minimal=true` (the dynamic
63/// session/knowledge/gotcha payload is governed by `INSTRUCTION_CAP_TOKENS`, not
64/// the char budget) plus `level=Off`, `shadow=false` (the default template) and
65/// an empty persona block (the `coding` default), so the result is independent
66/// of the developer's local lean-ctx config and the assertion stays
67/// deterministic (#498) for every contributor, not just clean CI.
68#[must_use]
69pub fn claude_code_static_instructions_for_test() -> String {
70    build_full_instructions(CrpMode::Off, "", true, CompressionLevel::Off, false, "")
71}
72
73/// Deterministic variant for tests (no session/knowledge state).
74#[must_use]
75pub fn build_instructions_for_test(crp_mode: CrpMode) -> String {
76    let shadow = false;
77    // Resolve the effective compression level from config/env (matches the live
78    // build_full_instructions path) so terse/compression env vars are honoured.
79    let level = CompressionLevel::effective(&crate::core::config::Config::load());
80    let tp =
81        crate::core::tool_profiles::ToolProfile::from_config(&crate::core::config::Config::load());
82    let skeleton = rc::render(shadow, Wrapper::Bare, level, &tp);
83    let shell_hint = build_shell_hint();
84
85    let base = format!(
86        "{skeleton}\n\
87        {shell_hint}\n\
88        {decoder_block}\n\
89        {origin}",
90        decoder_block =
91            crate::core::protocol::instruction_decoder_block(matches!(crp_mode, CrpMode::Tdd)),
92        origin = crate::core::integrity::origin_line(),
93    );
94
95    match crp_mode_suffix(crp_mode) {
96        "" => format!("{base}\n\n{}", rc::INTELLIGENCE),
97        crp => format!("{base}\n\n{crp}\n\n{}", rc::INTELLIGENCE),
98    }
99}
100
101/// Deterministic instruction builder for the Instruction Compiler.
102/// Uses shadow mode (COMPACT_SHADOW profile) to avoid duplicating
103/// BULLETS/NEVER/CRITICAL that the CLAUDE.md / dedicated rule file carries.
104#[must_use]
105pub fn build_instructions_with_client_for_compiler(
106    crp_mode: CrpMode,
107    client_name: &str,
108    _unified_tool_mode: bool,
109) -> String {
110    let tp =
111        crate::core::tool_profiles::ToolProfile::from_config(&crate::core::config::Config::load());
112    let skeleton = rc::render(true, Wrapper::Bare, CompressionLevel::Off, &tp);
113    let shell_hint = build_shell_hint();
114
115    let base = format!(
116        "{skeleton}\n\
117        {shell_hint}\n\
118        {decoder_block}\n\
119        {origin}",
120        decoder_block =
121            crate::core::protocol::instruction_decoder_block(matches!(crp_mode, CrpMode::Tdd)),
122        origin = crate::core::integrity::origin_line(),
123    );
124
125    let _ = client_name;
126
127    match crp_mode_suffix(crp_mode) {
128        "" => format!("{base}\n\n{}", rc::INTELLIGENCE),
129        crp => format!("{base}\n\n{crp}\n\n{}", rc::INTELLIGENCE),
130    }
131}
132
133/// LITM calibration manifest rotation (#539).
134fn rotate_wakeup_manifest(session: &crate::core::session::SessionState, profile_name: &str) {
135    use crate::core::litm_calibration::{Position, record_outcome};
136    use crate::core::session::ManifestEntry;
137
138    let mut updated = session.clone();
139
140    for entry in &updated.wakeup_manifest {
141        if !entry.missed
142            && let Some(pos) = Position::parse(&entry.position)
143        {
144            record_outcome(&entry.profile, pos, true);
145        }
146    }
147
148    let mut manifest: Vec<ManifestEntry> = Vec::new();
149    let mut push = |key: &str, position: &str| {
150        let key = key.trim();
151        if !key.is_empty() {
152            manifest.push(ManifestEntry {
153                key: key.chars().take(80).collect(),
154                position: position.to_string(),
155                profile: profile_name.to_string(),
156                missed: false,
157            });
158        }
159    };
160
161    if let Some(ref task) = updated.task {
162        push(&task.description, "begin");
163    }
164    for d in updated.decisions.iter().rev().take(5) {
165        push(&d.summary, "begin");
166    }
167    for f in updated.findings.iter().rev().take(8) {
168        push(&f.summary, "end");
169    }
170    for n in updated.next_steps.iter().take(3) {
171        push(n, "end");
172    }
173
174    updated.wakeup_manifest = manifest;
175    let _ = updated.save();
176}
177
178/// Display path for the Claude config directory (respected by CLAUDE_CONFIG_DIR).
179#[must_use]
180pub fn claude_config_dir_display() -> String {
181    match std::env::var("CLAUDE_CONFIG_DIR") {
182        Ok(dir) if !dir.trim().is_empty() => {
183            let dir = dir.trim().to_string();
184            if dir.starts_with('~') {
185                dir
186            } else if let Some(home) = dirs::home_dir() {
187                let home_str = home.to_string_lossy();
188                if let Some(rest) = dir.strip_prefix(home_str.as_ref()) {
189                    format!("~{rest}")
190                } else {
191                    dir
192                }
193            } else {
194                dir
195            }
196        }
197        _ => "~/.claude".to_string(),
198    }
199}
200
201// ── MCP per-session instructions builder ──────────────────────
202
203fn build_full_instructions(
204    crp_mode: CrpMode,
205    client_name: &str,
206    minimal: bool,
207    level: CompressionLevel,
208    shadow: bool,
209    persona_block: &str,
210) -> String {
211    let profile = crate::core::litm::LitmProfile::from_client_name(client_name);
212    let loaded_session = if minimal {
213        None
214    } else {
215        crate::core::session::SessionState::load_latest()
216    };
217
218    let (session_block, litm_end_block) = match loaded_session {
219        Some(ref session) => {
220            rotate_wakeup_manifest(session, profile.name);
221            let share = crate::core::litm_calibration::begin_share(profile.name);
222            let mut positioned = crate::core::litm::position_optimize_with_share(session, share);
223            // #962: hard token ceiling so the re-injected ACTIVE SESSION block can
224            // never crowd out the user's task (deterministic, generous default).
225            positioned.enforce_token_budget(crate::core::litm::active_session_budget());
226            let begin = format!(
227                "\n\n--- ACTIVE SESSION (LITM P1: begin position, profile: {}) ---\n{}\n---\n",
228                profile.name, positioned.begin_block
229            );
230            let end = if positioned.end_block.is_empty() {
231                String::new()
232            } else {
233                format!(
234                    "\n--- SESSION RESUME (post-compaction) ---\n{}\n---\n",
235                    positioned.end_block
236                )
237            };
238            (begin, end)
239        }
240        None => (String::new(), String::new()),
241    };
242
243    let project_root_for_blocks = if minimal {
244        None
245    } else {
246        loaded_session
247            .as_ref()
248            .and_then(|s| s.project_root.clone())
249            .or_else(|| {
250                std::env::current_dir()
251                    .ok()
252                    .map(|p| p.to_string_lossy().to_string())
253            })
254    };
255
256    let knowledge_block = match &project_root_for_blocks {
257        Some(root) => {
258            let knowledge = crate::core::knowledge::ProjectKnowledge::load(root);
259            match knowledge {
260                Some(k) if !k.facts.is_empty() || !k.patterns.is_empty() => {
261                    let aaak = k.format_aaak();
262                    if aaak.is_empty() {
263                        String::new()
264                    } else {
265                        format!("\n--- PROJECT MEMORY (AAAK) ---\n{}\n---\n", aaak.trim())
266                    }
267                }
268                _ => String::new(),
269            }
270        }
271        None => String::new(),
272    };
273
274    let gotcha_block = match &project_root_for_blocks {
275        Some(root) => {
276            let store = crate::core::gotcha_tracker::GotchaStore::load(root);
277            let files: Vec<String> = loaded_session
278                .as_ref()
279                .map(|s| s.files_touched.iter().map(|ft| ft.path.clone()).collect())
280                .unwrap_or_default();
281            let block = store.format_injection_block(&files);
282            if block.is_empty() {
283                String::new()
284            } else {
285                format!("\n{block}\n")
286            }
287        }
288        None => String::new(),
289    };
290
291    let health_block = match &project_root_for_blocks {
292        Some(root) => {
293            let block = crate::core::code_health::persist::format_session_block(root);
294            if block.is_empty() {
295                String::new()
296            } else {
297                format!("\n{block}\n")
298            }
299        }
300        None => String::new(),
301    };
302
303    let shell_hint = build_shell_hint();
304
305    // Skeleton includes tool-mapping rules + compression prompt (if level active).
306    // Shadow mode omits BULLETS/NEVER/CRITICAL automatically.
307    //
308    // Cross-channel dedup (#578): when the client's own auto-loaded rule file
309    // already carries the canonical rules block (Cursor mdc, Codex
310    // instructions.md), repeating the skeleton here would bill the same
311    // guidance twice on every session. A one-line anchor keeps the binding;
312    // the compression payload is deduped separately via `level` above.
313    //
314    // Hook-covered hosts (GL #1153) get the hook-aware anchor: repeating
315    // "ctx_* replaces native tools" to a Cursor whose hooks already compress
316    // the native calls re-creates exactly the instruction dissonance the
317    // HookCovered rule profile removes.
318    let cfg = crate::core::config::Config::load();
319    let tool_profile = crate::core::tool_profiles::ToolProfile::from_config(&cfg);
320    let skeleton = if client_loads_rules_from_file(client_name) {
321        let anchor = if client_is_hook_covered(client_name) {
322            hook_covered_anchor(&tool_profile)
323        } else {
324            skeleton_anchor(&tool_profile)
325        };
326        let compression = rc::compression_text(level);
327        if compression.is_empty() {
328            anchor
329        } else {
330            format!("{anchor}\n{compression}")
331        }
332    } else {
333        rc::render(shadow, Wrapper::Bare, level, &tool_profile)
334    };
335
336    // Pointer to the full rule file (honours CLAUDE_CONFIG_DIR): agents load the
337    // detailed instructions on demand from there instead of inlining them.
338    let config_dir = claude_config_dir_display();
339
340    // Persona domain block (persona-spec-v1): placed right after the skeleton
341    // so the vocabulary frames everything that follows. Empty for `coding`.
342    let persona_section = if persona_block.is_empty() {
343        String::new()
344    } else {
345        format!("\n{persona_block}")
346    };
347
348    let base = format!(
349        "{skeleton}\n\
350        {persona_section}\
351        {shell_hint}\n\
352        {decoder_block}\n\
353        Full instructions at {config_dir}/CLAUDE.md\n\
354        {session_block}\n\
355        {knowledge_block}\n\
356        {gotcha_block}\n\
357        {health_block}\n\
358        {origin}\n\
359        {litm_end_block}",
360        decoder_block =
361            crate::core::protocol::instruction_decoder_block(matches!(crp_mode, CrpMode::Tdd)),
362        origin = crate::core::integrity::origin_line(),
363        litm_end_block = litm_end_block
364    );
365
366    // Guidance suffix: CRP mode + general output rule.
367    // This is the operational contract — protected from truncation.
368    let guidance_suffix = match crp_mode_suffix(crp_mode) {
369        "" => rc::INTELLIGENCE.to_string(),
370        crp => format!("{crp}\n\n{}", rc::INTELLIGENCE),
371    };
372
373    assemble_within_cap(&base, &guidance_suffix, INSTRUCTION_CAP_TOKENS)
374}
375
376fn crp_mode_suffix(crp_mode: CrpMode) -> &'static str {
377    match crp_mode {
378        CrpMode::Off => "",
379        CrpMode::Compact => {
380            "CRP MODE: compact — omit filler; abbreviate fn,cfg,impl,deps,req,res; \
381             diff lines (+/-) only; <=200 tok; trust tool outputs."
382        }
383        CrpMode::Tdd => {
384            "CRP MODE: tdd — max density; Fn refs + diff lines only \
385             (+F1:42 | -F1:10-15 | ~F1:42 old->new); <=150 tok; zero narration."
386        }
387    }
388}
389
390fn assemble_within_cap(base: &str, suffix: &str, cap_tokens: usize) -> String {
391    use crate::core::tokens::count_tokens;
392    let suffix = suffix.trim_end_matches('\n');
393    if suffix.is_empty() {
394        let full = base.to_string();
395        return if count_tokens(&full) > cap_tokens {
396            truncate_to_token_cap(&full, cap_tokens)
397        } else {
398            full
399        };
400    }
401
402    let full = format!("{base}\n\n{suffix}");
403    if count_tokens(&full) <= cap_tokens {
404        return full;
405    }
406
407    let suffix_tokens = count_tokens(suffix);
408    let Some(base_budget) = cap_tokens.checked_sub(suffix_tokens + 1) else {
409        return truncate_to_token_cap(&full, cap_tokens);
410    };
411    let trimmed_base = truncate_to_token_cap(base, base_budget);
412    format!("{trimmed_base}\n\n{suffix}")
413}
414
415fn truncate_to_token_cap(s: &str, cap_tokens: usize) -> String {
416    use crate::core::tokens::count_tokens;
417    if count_tokens(s) <= cap_tokens {
418        return s.to_string();
419    }
420    let cuts: Vec<usize> = s.match_indices('\n').map(|(i, _)| i).collect();
421    let (mut lo, mut hi) = (0usize, cuts.len());
422    let mut best: Option<usize> = None;
423    while lo < hi {
424        let mid = lo + (hi - lo) / 2;
425        let end = cuts[mid];
426        if end > 0 && count_tokens(&s[..end]) <= cap_tokens {
427            best = Some(end);
428            lo = mid + 1;
429        } else {
430            hi = mid;
431        }
432    }
433    if let Some(end) = best {
434        return s[..end].to_string();
435    }
436    let byte_approx = cap_tokens * 4;
437    let safe = s.floor_char_boundary(byte_approx.min(s.len()));
438    s[..safe].to_string()
439}
440
441/// Backward-compat alias kept for external callers.
442#[must_use]
443pub fn claude_code_instructions() -> String {
444    build_instructions(CrpMode::Off)
445}
446
447/// One-line anchor for clients whose rule file carries the canonical block (#578).
448/// Profile-aware (#756): only mentions tools the profile exposes.
449fn skeleton_anchor(tp: &crate::core::tool_profiles::ToolProfile) -> String {
450    if tp.is_tool_enabled("ctx_compose") {
451        "lean-ctx active — your auto-loaded lean-ctx rules apply: \
452         ctx_* tools replace native Read/Grep/Shell/Glob (ctx_compose first)."
453            .into()
454    } else {
455        "lean-ctx active — your auto-loaded lean-ctx rules apply: \
456         ctx_* tools replace native Read/Grep/Shell/Glob."
457            .into()
458    }
459}
460
461/// Anchor for hook-covered hosts (GL #1153). Profile-aware (#756).
462fn hook_covered_anchor(tp: &crate::core::tool_profiles::ToolProfile) -> String {
463    let mut s =
464        String::from("lean-ctx active — hooks compress native Shell/Read/Grep transparently");
465    if tp.is_tool_enabled("ctx_compose") {
466        s.push_str("; call ctx_compose to orient");
467    }
468    // #509: ctx_semantic_search folded into ctx_search(action=semantic)
469    if tp.is_tool_enabled("ctx_session") || tp.is_tool_enabled("ctx_knowledge") {
470        s.push_str(", ctx_search(action=semantic) / ctx_knowledge for meaning & memory");
471    }
472    s.push('.');
473    s
474}
475
476// Test-only backward-compat constants for assertion substrings.
477#[cfg(test)]
478const SKELETON_ANCHOR: &str = "lean-ctx active — your auto-loaded lean-ctx rules apply: \
479    ctx_* tools replace native Read/Grep/Shell/Glob (ctx_compose first).";
480
481fn client_loads_compression_from_file(client_name: &str) -> bool {
482    crate::core::home::resolve_home_dir().is_some_and(|home| {
483        crate::core::rules_channel::client_autoloads_compression(client_name, &home)
484    })
485}
486
487fn client_loads_rules_from_file(client_name: &str) -> bool {
488    crate::core::home::resolve_home_dir()
489        .is_some_and(|home| crate::core::rules_channel::client_autoloads_rules(client_name, &home))
490}
491
492fn client_is_hook_covered(client_name: &str) -> bool {
493    crate::core::home::resolve_home_dir()
494        .is_some_and(|home| crate::core::rules_channel::client_hook_covered(client_name, &home))
495}
496
497fn build_shell_hint() -> String {
498    if !cfg!(windows) {
499        return String::new();
500    }
501    let name = crate::shell::shell_name();
502    let is_posix = matches!(name.as_str(), "bash" | "sh" | "zsh" | "fish");
503    if is_posix {
504        format!("\nSHELL: {name} (POSIX) — no PowerShell cmdlets.\n")
505    } else if name.contains("powershell") || name.contains("pwsh") {
506        format!("\nSHELL: {name}. Use PowerShell cmdlets.\n")
507    } else {
508        format!("\nSHELL: {name}.\n")
509    }
510}
511
512#[cfg(test)]
513mod tests {
514    use super::*;
515    use crate::core::tokens::count_tokens;
516
517    #[test]
518    fn guidance_suffix_survives_oversized_base() {
519        let base = "SESSION LINE\n".repeat(4000);
520        let suffix = "OUTPUT STYLE: expert-terse\nFn refs only, diff lines only.";
521        let out = assemble_within_cap(&base, suffix, INSTRUCTION_CAP_TOKENS);
522        assert!(out.contains("OUTPUT STYLE: expert-terse"));
523        assert!(count_tokens(&out) <= INSTRUCTION_CAP_TOKENS);
524        assert!(out.len() < base.len());
525    }
526
527    #[test]
528    fn empty_client_never_dedups_compression() {
529        assert!(!client_loads_compression_from_file(""));
530        assert!(!client_loads_compression_from_file("totally-unknown-agent"));
531    }
532
533    #[test]
534    fn covered_client_gets_anchor_instead_of_skeleton() {
535        // #578: a client whose rule file carries the canonical block must not
536        // pay for the full skeleton again in every MCP session.
537        let _guard = crate::core::data_dir::test_env_lock();
538        let tmp = tempfile::tempdir().unwrap();
539        let home = tmp.path();
540        std::fs::create_dir_all(home.join(".cursor/rules")).unwrap();
541        let tp = crate::core::tool_profiles::ToolProfile::Power;
542        std::fs::write(
543            home.join(".cursor/rules/lean-ctx.mdc"),
544            rc::render(
545                false,
546                Wrapper::Dedicated,
547                crate::core::config::CompressionLevel::Standard,
548                &tp,
549            ),
550        )
551        .unwrap();
552        let old_home = std::env::var("HOME").ok();
553        crate::test_env::set_var("HOME", home);
554        crate::test_env::set_var("LEAN_CTX_MINIMAL", "1");
555
556        let covered = build_instructions_with_client(CrpMode::Off, "cursor");
557        let uncovered = build_instructions_with_client(CrpMode::Off, "some-other-agent");
558
559        if let Some(h) = old_home {
560            crate::test_env::set_var("HOME", h);
561        } else {
562            crate::test_env::remove_var("HOME");
563        }
564        crate::test_env::remove_var("LEAN_CTX_MINIMAL");
565
566        assert!(
567            covered.contains(SKELETON_ANCHOR),
568            "covered client must get the anchor:\n{covered}"
569        );
570        assert!(
571            !covered.contains("MANDATORY MAPPING"),
572            "covered client must not re-pay the skeleton:\n{covered}"
573        );
574        // The mdc also carries the compression block → level dedups to Off.
575        assert!(
576            !covered.contains("OUTPUT STYLE:"),
577            "covered client must not re-pay the compression prompt:\n{covered}"
578        );
579        assert!(
580            uncovered.contains("MANDATORY MAPPING"),
581            "uncovered client keeps the full skeleton:\n{uncovered}"
582        );
583        eprintln!(
584            "instructions footprint: covered={} tok, uncovered={} tok",
585            count_tokens(&covered),
586            count_tokens(&uncovered)
587        );
588        assert!(
589            count_tokens(&covered) < count_tokens(&uncovered),
590            "anchor path must be strictly cheaper"
591        );
592    }
593
594    #[test]
595    fn hook_covered_client_gets_hook_aware_anchor() {
596        // GL #1153: with lean-ctx hooks covering the native tools, the anchor
597        // must not repeat "ctx_* replaces native tools" — that is exactly the
598        // instruction dissonance the HookCovered profile removes.
599        let _guard = crate::core::data_dir::test_env_lock();
600        let tmp = tempfile::tempdir().unwrap();
601        let home = tmp.path();
602        std::fs::create_dir_all(home.join(".cursor/rules")).unwrap();
603        let tp = crate::core::tool_profiles::ToolProfile::Power;
604        std::fs::write(
605            home.join(".cursor/rules/lean-ctx.mdc"),
606            rc::render(
607                false,
608                Wrapper::HookCovered,
609                crate::core::config::CompressionLevel::Off,
610                &tp,
611            ),
612        )
613        .unwrap();
614        std::fs::write(
615            home.join(".cursor/hooks.json"),
616            r#"{"version":1,"hooks":{"preToolUse":[
617                {"matcher":"Shell","command":"/usr/local/bin/lean-ctx hook rewrite"},
618                {"matcher":"Read|Grep","command":"/usr/local/bin/lean-ctx hook redirect"}
619            ]}}"#,
620        )
621        .unwrap();
622        let old_home = std::env::var("HOME").ok();
623        crate::test_env::set_var("HOME", home);
624        crate::test_env::set_var("LEAN_CTX_MINIMAL", "1");
625
626        let covered = build_instructions_with_client(CrpMode::Off, "cursor");
627
628        if let Some(h) = old_home {
629            crate::test_env::set_var("HOME", h);
630        } else {
631            crate::test_env::remove_var("HOME");
632        }
633        crate::test_env::remove_var("LEAN_CTX_MINIMAL");
634
635        assert!(
636            covered.contains("hooks compress native Shell/Read/Grep"),
637            "hook-covered client must get the hook-aware anchor:\n{covered}"
638        );
639        assert!(
640            !covered.contains("ctx_* tools replace native")
641                && !covered.contains("MANDATORY MAPPING"),
642            "hook-covered client must not carry the replace-native wording:\n{covered}"
643        );
644    }
645
646    #[test]
647    fn non_coding_persona_block_lands_in_instructions() {
648        let _guard = crate::core::data_dir::test_env_lock();
649        crate::test_env::set_var("LEAN_CTX_MINIMAL", "1");
650
651        crate::test_env::set_var("LEAN_CTX_PERSONA", "research");
652        let research = build_instructions_with_client(CrpMode::Off, "");
653
654        crate::test_env::set_var("LEAN_CTX_PERSONA", "coding");
655        let coding = build_instructions_with_client(CrpMode::Off, "");
656
657        crate::test_env::remove_var("LEAN_CTX_PERSONA");
658        crate::test_env::remove_var("LEAN_CTX_MINIMAL");
659
660        assert!(
661            research.contains("PERSONA: research"),
662            "research persona must announce its domain block:\n{research}"
663        );
664        assert!(
665            research.contains("INTENTS: explore, summarize, compare, cite, synthesize"),
666            "research persona must carry its intent vocabulary:\n{research}"
667        );
668        assert!(
669            !coding.contains("PERSONA:"),
670            "the coding default must keep the instructions byte-stable (#498):\n{coding}"
671        );
672    }
673
674    #[test]
675    fn under_cap_keeps_everything() {
676        let base = "tool mapping block";
677        let suffix = "OUTPUT STYLE: dense";
678        let out = assemble_within_cap(base, suffix, INSTRUCTION_CAP_TOKENS);
679        assert!(out.contains(base));
680        assert!(out.contains(suffix));
681    }
682
683    #[test]
684    fn empty_suffix_caps_base_only() {
685        let base = "x\n".repeat(4000);
686        let out = assemble_within_cap(&base, "", INSTRUCTION_CAP_TOKENS);
687        assert!(count_tokens(&out) <= INSTRUCTION_CAP_TOKENS);
688    }
689
690    #[cfg(windows)]
691    #[test]
692    fn shell_hint_stays_within_its_budget() {
693        let hint = build_shell_hint();
694        let tokens = count_tokens(&hint);
695        assert!(
696            tokens <= STATIC_INSTRUCTION_SHELL_HINT_TOKENS,
697            "shell hint = {tokens} tok, budget {STATIC_INSTRUCTION_SHELL_HINT_TOKENS}: {hint}"
698        );
699    }
700
701    #[test]
702    fn minimal_overhead_instructions_stay_within_budget() {
703        const MINIMAL_INSTRUCTION_BUDGET_TOKENS: usize =
704            STATIC_INSTRUCTION_BUDGET_TDD_TOKENS + STATIC_INSTRUCTION_SHELL_HINT_TOKENS;
705        let _iso = crate::core::data_dir::isolated_data_dir();
706        crate::test_env::set_var("LEAN_CTX_MINIMAL", "1");
707        let out = build_instructions(CrpMode::Compact);
708        crate::test_env::remove_var("LEAN_CTX_MINIMAL");
709        let tokens = count_tokens(&out);
710        assert!(
711            tokens <= MINIMAL_INSTRUCTION_BUDGET_TOKENS,
712            "minimal-overhead instructions = {tokens} tok, budget {MINIMAL_INSTRUCTION_BUDGET_TOKENS}\n---\n{out}\n---"
713        );
714    }
715
716    #[test]
717    fn static_skeleton_stays_within_budget() {
718        let _iso = crate::core::data_dir::isolated_data_dir();
719        // Pin compression Off so the measured skeleton — and thus this budget —
720        // is deterministic regardless of the dev's local compression_level (#498).
721        crate::test_env::set_var("LEAN_CTX_COMPRESSION", "off");
722        for (mode, base_budget) in [
723            (CrpMode::Off, STATIC_INSTRUCTION_BUDGET_TOKENS),
724            (CrpMode::Compact, STATIC_INSTRUCTION_BUDGET_TOKENS),
725            (CrpMode::Tdd, STATIC_INSTRUCTION_BUDGET_TDD_TOKENS),
726        ] {
727            let budget = base_budget + STATIC_INSTRUCTION_SHELL_HINT_TOKENS;
728            let out = build_instructions_for_test(mode);
729            let tokens = count_tokens(&out);
730            assert!(
731                tokens <= budget,
732                "static instructions for {mode:?} = {tokens} tok, budget {budget}\n---\n{out}\n---"
733            );
734        }
735        crate::test_env::remove_var("LEAN_CTX_COMPRESSION");
736    }
737}