Skip to main content

lean_ctx/
instructions.rs

1use crate::tools::CrpMode;
2
3/// Claude Code truncates MCP server instructions at 2048 characters.
4/// Full instructions are installed as `~/.claude/rules/lean-ctx.md` instead.
5const CLAUDE_CODE_INSTRUCTION_CAP: usize = 2048;
6
7pub fn build_instructions(crp_mode: CrpMode) -> String {
8    build_instructions_with_client(crp_mode, "")
9}
10
11pub fn build_instructions_with_client(crp_mode: CrpMode, client_name: &str) -> String {
12    if is_claude_code_client(client_name) {
13        return build_claude_code_instructions();
14    }
15    build_full_instructions(crp_mode, client_name)
16}
17
18fn is_claude_code_client(client_name: &str) -> bool {
19    let lower = client_name.to_lowercase();
20    lower.contains("claude") && !lower.contains("cursor")
21}
22
23fn build_claude_code_instructions() -> String {
24    let instr = "\
25ALWAYS use lean-ctx MCP tools instead of native equivalents.
26
27Tool mapping (MANDATORY):
28• Read/cat/head/tail -> ctx_read(path, mode)
29• Shell/bash -> ctx_shell(command)
30• Grep/rg -> ctx_search(pattern, path)
31• ls/find -> ctx_tree(path, depth)
32• Edit/StrReplace -> native (lean-ctx=READ only). If Edit needs Read and Read is unavailable, use ctx_edit.
33• Write, Delete, Glob -> normal. NEVER loop on Edit failures — use ctx_edit.
34
35ctx_read modes: full|map|signatures|diff|task|reference|aggressive|entropy|lines:N-M
36Auto-selects mode. Re-reads ~13 tok. File refs F1,F2.. persist.
37Cached? fresh=true or lines:N-M.
38
39Auto: ctx_overview, ctx_preload, ctx_dedup, ctx_compress behind the scenes.
40Multi-agent: ctx_agent(action=handoff|sync|diary).
41ctx_semantic_search for meaning search. ctx_session for memory.
42ctx_knowledge: remember|recall|timeline|rooms|search|wakeup.
43ctx_shell raw=true for uncompressed.
44
45CEP: 1.ACT FIRST 2.DELTA ONLY 3.STRUCTURED(+/-/~) 4.ONE LINE 5.QUALITY
46
47Prefer: ctx_read>Read | ctx_shell>Shell | ctx_search>Grep | ctx_tree>ls
48Edit: native Edit/StrReplace preferred, ctx_edit if Edit unavailable.
49Never echo tool output. Never narrate. Show only changed code.
50Full instructions at ~/.claude/CLAUDE.md (imports rules/lean-ctx.md)";
51
52    debug_assert!(
53        instr.len() <= CLAUDE_CODE_INSTRUCTION_CAP,
54        "Claude Code instructions exceed {CLAUDE_CODE_INSTRUCTION_CAP} chars: {} chars",
55        instr.len()
56    );
57    instr.to_string()
58}
59
60fn build_full_instructions(crp_mode: CrpMode, client_name: &str) -> String {
61    let profile = crate::core::litm::LitmProfile::from_client_name(client_name);
62    let session_block = match crate::core::session::SessionState::load_latest() {
63        Some(ref session) => {
64            let positioned = crate::core::litm::position_optimize(session);
65            format!(
66                "\n\n--- ACTIVE SESSION (LITM P1: begin position, profile: {}) ---\n{}\n---\n",
67                profile.name, positioned.begin_block
68            )
69        }
70        None => String::new(),
71    };
72
73    let project_root_for_blocks = crate::core::session::SessionState::load_latest()
74        .and_then(|s| s.project_root)
75        .or_else(|| {
76            std::env::current_dir()
77                .ok()
78                .map(|p| p.to_string_lossy().to_string())
79        });
80
81    let knowledge_block = match &project_root_for_blocks {
82        Some(root) => {
83            let knowledge = crate::core::knowledge::ProjectKnowledge::load(root);
84            match knowledge {
85                Some(k) if !k.facts.is_empty() || !k.patterns.is_empty() => {
86                    let aaak = k.format_aaak();
87                    if aaak.is_empty() {
88                        String::new()
89                    } else {
90                        format!("\n--- PROJECT MEMORY (AAAK) ---\n{}\n---\n", aaak.trim())
91                    }
92                }
93                _ => String::new(),
94            }
95        }
96        None => String::new(),
97    };
98
99    let gotcha_block = match &project_root_for_blocks {
100        Some(root) => {
101            let store = crate::core::gotcha_tracker::GotchaStore::load(root);
102            let files: Vec<String> = crate::core::session::SessionState::load_latest()
103                .map(|s| s.files_touched.iter().map(|ft| ft.path.clone()).collect())
104                .unwrap_or_default();
105            let block = store.format_injection_block(&files);
106            if block.is_empty() {
107                String::new()
108            } else {
109                format!("\n{block}\n")
110            }
111        }
112        None => String::new(),
113    };
114
115    let mut base = format!("\
116CRITICAL: ALWAYS use lean-ctx MCP tools instead of native equivalents for token savings.\n\
117\n\
118lean-ctx MCP — MANDATORY tool mapping:\n\
119• Read/cat/head/tail -> ctx_read(path, mode)  [NEVER use native Read]\n\
120• Shell/bash -> ctx_shell(command)  [NEVER use native Shell]\n\
121• Grep/rg -> ctx_search(pattern, path)  [NEVER use native Grep]\n\
122• ls/find -> ctx_tree(path, depth)\n\
123• Edit/StrReplace -> use native (lean-ctx only replaces READ, not WRITE)\n\
124• Write, Delete, Glob -> use normally\n\
125\n\
126COMPATIBILITY: lean-ctx replaces READ operations only. Edit/Write/StrReplace stay native.\n\
127FILE EDITING: Native Edit/StrReplace preferred. If Edit fails, use ctx_edit immediately.\n\
128\n\
129ctx_read modes: full|map|signatures|diff|task|reference|aggressive|entropy|lines:N-M. Auto-selects. Re-reads ~13 tok. Fn refs F1,F2.. persist.\n\
130Cached? Use fresh=true, start_line=N, or lines:N-M.\n\
131\n\
132Auto: ctx_overview, ctx_preload, ctx_dedup, ctx_compress run behind the scenes. Checkpoint every 15 calls.\n\
133Multi-agent: ctx_agent(action=handoff|sync). Diary: ctx_agent(action=diary, category=discovery|decision|blocker|progress|insight).\n\
134ctx_semantic_search for meaning-based search. ctx_session for memory. ctx_knowledge: remember|recall|timeline|rooms|search|wakeup.\n\
135ctx_shell raw=true for uncompressed output.\n\
136\n\
137CEP v1: 1.ACT FIRST 2.DELTA ONLY (Fn refs) 3.STRUCTURED (+/-/~) 4.ONE LINE PER ACTION 5.QUALITY ANCHOR\n\
138\n\
139{decoder_block}\n\
140\n\
141{session_block}\
142{knowledge_block}\
143{gotcha_block}\
144\n\
145--- ORIGIN ---\n\
146{origin}\n\
147\n\
148--- TOOL PREFERENCE (LITM-END) ---\n\
149Prefer: ctx_read over Read | ctx_shell over Shell | ctx_search over Grep | ctx_tree over ls\n\
150Edit files: native Edit/StrReplace if available, ctx_edit if Edit requires unavailable Read.\n\
151Write, Delete, Glob -> use normally. NEVER loop on Edit failures — use ctx_edit.",
152        decoder_block = crate::core::protocol::instruction_decoder_block(),
153        origin = crate::core::integrity::origin_line()
154    );
155
156    if should_use_unified(client_name) {
157        base.push_str(
158            "\n\n\
159UNIFIED TOOL MODE (active):\n\
160Additional tools are accessed via ctx() meta-tool: ctx(tool=\"<name>\", ...params).\n\
161See the ctx() tool description for available sub-tools.\n",
162        );
163    }
164
165    let intelligence_block = build_intelligence_block();
166
167    let base = base;
168    match crp_mode {
169        CrpMode::Off => format!("{base}\n\n{intelligence_block}"),
170        CrpMode::Compact => {
171            format!(
172                "{base}\n\n\
173CRP MODE: compact\n\
174Omit filler. Abbreviate: fn,cfg,impl,deps,req,res,ctx,err,ret,arg,val,ty,mod.\n\
175Diff lines (+/-) only. TARGET: <=200 tok. Trust tool outputs.\n\n\
176{intelligence_block}"
177            )
178        }
179        CrpMode::Tdd => {
180            format!(
181                "{base}\n\n\
182CRP MODE: tdd\n\
183Max density. Every token carries meaning. Fn refs only, diff lines (+/-) only.\n\
184Abbreviate: fn,cfg,impl,deps,req,res,ctx,err,ret,arg,val,ty,mod.\n\
185+F1:42 param(timeout:Duration) | -F1:10-15 | ~F1:42 old->new\n\
186BUDGET: <=150 tok. ZERO NARRATION. Trust tool outputs.\n\n\
187{intelligence_block}"
188            )
189        }
190    }
191}
192
193pub fn claude_code_instructions() -> String {
194    build_claude_code_instructions()
195}
196
197pub fn full_instructions_for_rules_file(crp_mode: CrpMode) -> String {
198    build_full_instructions(crp_mode, "")
199}
200
201fn build_intelligence_block() -> String {
202    "\
203OUTPUT EFFICIENCY:\n\
204• Never echo tool output code. Never add narration comments. Show only changed code.\n\
205• [TASK:type] and SCOPE hints included. Architecture=thorough, generate=code."
206        .to_string()
207}
208
209fn should_use_unified(client_name: &str) -> bool {
210    if std::env::var("LEAN_CTX_FULL_TOOLS").is_ok() {
211        return false;
212    }
213    if std::env::var("LEAN_CTX_UNIFIED").is_ok() {
214        return true;
215    }
216    let _ = client_name;
217    false
218}