Skip to main content

lean_ctx/
instructions.rs

1use crate::tools::CrpMode;
2
3pub fn build_instructions(crp_mode: CrpMode) -> String {
4    build_instructions_with_client(crp_mode, "")
5}
6
7pub fn build_instructions_with_client(crp_mode: CrpMode, client_name: &str) -> String {
8    let profile = crate::core::litm::LitmProfile::from_client_name(client_name);
9    let session_block = match crate::core::session::SessionState::load_latest() {
10        Some(ref session) => {
11            let positioned = crate::core::litm::position_optimize(session);
12            format!(
13                "\n\n--- ACTIVE SESSION (LITM P1: begin position, profile: {}) ---\n{}\n---\n",
14                profile.name, positioned.begin_block
15            )
16        }
17        None => String::new(),
18    };
19
20    let project_root_for_blocks = crate::core::session::SessionState::load_latest()
21        .and_then(|s| s.project_root)
22        .or_else(|| {
23            std::env::current_dir()
24                .ok()
25                .map(|p| p.to_string_lossy().to_string())
26        });
27
28    let knowledge_block = match &project_root_for_blocks {
29        Some(root) => {
30            let knowledge = crate::core::knowledge::ProjectKnowledge::load(root);
31            match knowledge {
32                Some(k) if !k.facts.is_empty() || !k.patterns.is_empty() => {
33                    let aaak = k.format_aaak();
34                    if aaak.is_empty() {
35                        String::new()
36                    } else {
37                        format!("\n--- PROJECT MEMORY (AAAK) ---\n{}\n---\n", aaak.trim())
38                    }
39                }
40                _ => String::new(),
41            }
42        }
43        None => String::new(),
44    };
45
46    let gotcha_block = match &project_root_for_blocks {
47        Some(root) => {
48            let store = crate::core::gotcha_tracker::GotchaStore::load(root);
49            let files: Vec<String> = crate::core::session::SessionState::load_latest()
50                .map(|s| s.files_touched.iter().map(|ft| ft.path.clone()).collect())
51                .unwrap_or_default();
52            let block = store.format_injection_block(&files);
53            if block.is_empty() {
54                String::new()
55            } else {
56                format!("\n{block}\n")
57            }
58        }
59        None => String::new(),
60    };
61
62    let mut base = format!("\
63PREFER lean-ctx tools over native equivalents for token savings:\n\
64\n\
65lean-ctx MCP — tool mapping:\n\
66• Read/cat/head/tail -> ctx_read(path, mode)\n\
67• Shell/bash -> ctx_shell(command)\n\
68• Grep/rg -> ctx_search(pattern, path)\n\
69• ls/find -> ctx_tree(path, depth)\n\
70• Edit/StrReplace -> use native if available, otherwise use ctx_edit(path, old_string, new_string)\n\
71• Write, Delete, Glob -> use normally\n\
72\n\
73FILE EDITING: Use your IDE's native Edit/StrReplace when available. \
74If Edit requires native Read and Read is unavailable, use ctx_edit instead — it reads, replaces, and writes in one call. \
75NEVER loop trying to make Edit work. If Edit fails, switch to ctx_edit immediately.\n\
76\n\
77ctx_read modes: full (cached, for edits), map (deps+API), signatures, diff, task (IB-filtered), \
78reference, aggressive, entropy, lines:N-M. Auto-selects when unspecified. Re-reads ~13 tokens. File refs F1,F2.. persist.\n\
79If ctx_read returns 'cached': use fresh=true, start_line=N, or mode='lines:N-M' to re-read.\n\
80\n\
81AUTONOMY: lean-ctx auto-runs ctx_overview, ctx_preload, ctx_dedup, ctx_compress behind the scenes.\n\
82Multi-agent: ctx_share auto-pushes context at checkpoints. Use ctx_agent(action=handoff) to transfer tasks, ctx_agent(action=sync) for status.\n\
83Semantic: ctx_semantic_search finds similar code by meaning — use when exact search (ctx_search) misses.\n\
84Focus on: ctx_read, ctx_shell, ctx_search, ctx_tree. Use ctx_session for memory, ctx_knowledge for project facts.\n\
85Knowledge: ctx_knowledge actions: remember, recall, timeline, rooms, search (cross-session), wakeup. Facts have temporal validity + contradiction detection.\n\
86Agent diary: ctx_agent(action=diary, category=discovery|decision|blocker|progress|insight) to log agent work. ctx_agent(action=recall_diary) to review.\n\
87ctx_shell raw=true: skip compression for small/critical outputs. Full output tee files at ~/.lean-ctx/tee/.\n\
88\n\
89Auto-checkpoint every 15 calls. Cache clears after 5 min idle.\n\
90\n\
91CEP v1: 1.ACT FIRST 2.DELTA ONLY (Fn refs) 3.STRUCTURED (+/-/~) 4.ONE LINE PER ACTION 5.QUALITY ANCHOR\n\
92\n\
93{decoder_block}\n\
94\n\
95{session_block}\
96{knowledge_block}\
97{gotcha_block}\
98\n\
99--- TOOL PREFERENCE (LITM-END) ---\n\
100Prefer: ctx_read over Read | ctx_shell over Shell | ctx_search over Grep | ctx_tree over ls\n\
101Edit files: native Edit/StrReplace if available, ctx_edit if Edit requires unavailable Read.\n\
102Write, Delete, Glob -> use normally. NEVER loop on Edit failures — use ctx_edit.",
103        decoder_block = crate::core::protocol::instruction_decoder_block()
104    );
105
106    if should_use_unified(client_name) {
107        base.push_str(
108            "\n\n\
109UNIFIED TOOL MODE (active):\n\
110Additional tools are accessed via ctx() meta-tool: ctx(tool=\"<name>\", ...params).\n\
111See the ctx() tool description for available sub-tools.\n",
112        );
113    }
114
115    let intelligence_block = build_intelligence_block();
116
117    let base = base;
118    match crp_mode {
119        CrpMode::Off => format!("{base}\n\n{intelligence_block}"),
120        CrpMode::Compact => {
121            format!(
122                "{base}\n\n\
123CRP MODE: compact\n\
124Compact Response Protocol:\n\
125• Omit filler words, articles, redundant phrases\n\
126• Abbreviate: fn, cfg, impl, deps, req, res, ctx, err, ret, arg, val, ty, mod\n\
127• Compact lists over prose, code blocks over explanations\n\
128• Code changes: diff lines (+/-) only, not full files\n\
129• TARGET: <=200 tokens per response unless code edits require more\n\
130• Tool outputs are pre-analyzed and compressed. Trust them directly.\n\n\
131{intelligence_block}"
132            )
133        }
134        CrpMode::Tdd => {
135            format!(
136                "{base}\n\n\
137CRP MODE: tdd (Token Dense Dialect)\n\
138Maximize information density. Every token must carry meaning.\n\
139\n\
140RESPONSE RULES:\n\
141• Drop articles, filler words, pleasantries\n\
142• Reference files by Fn refs only, never full paths\n\
143• Code changes: diff lines only (+/-), not full files\n\
144• No explanations unless asked\n\
145• Tables for structured data\n\
146• Abbreviations: fn, cfg, impl, deps, req, res, ctx, err, ret, arg, val, ty, mod\n\
147\n\
148CHANGE NOTATION:\n\
149+F1:42 param(timeout:Duration)     — added\n\
150-F1:10-15                           — removed\n\
151~F1:42 validate_token -> verify_jwt — changed\n\
152\n\
153STATUS: ctx_read(F1) -> 808L cached ok | cargo test -> 82 passed 0 failed\n\
154\n\
155TOKEN BUDGET: <=150 tokens per response. Exceed only for multi-file edits.\n\
156Tool outputs are pre-analyzed and compressed. Trust them directly.\n\
157ZERO NARRATION: Act, then report result in 1 line.\n\n\
158{intelligence_block}"
159            )
160        }
161    }
162}
163
164fn build_intelligence_block() -> String {
165    "\
166OUTPUT EFFICIENCY:\n\
167• NEVER echo back code that was provided in tool outputs — it wastes tokens.\n\
168• NEVER add narration comments (// Import, // Define, // Return) — code is self-documenting.\n\
169• For code changes: show only the new/changed code, not unchanged context.\n\
170• Tool outputs include [TASK:type] and SCOPE hints for context.\n\
171• Respect the user's intent: architecture tasks need thorough analysis, simple generates need code."
172        .to_string()
173}
174
175fn should_use_unified(client_name: &str) -> bool {
176    if std::env::var("LEAN_CTX_FULL_TOOLS").is_ok() {
177        return false;
178    }
179    if std::env::var("LEAN_CTX_UNIFIED").is_ok() {
180        return true;
181    }
182    let _ = client_name;
183    false
184}