Skip to main content

lean_ctx/core/
rules_canonical.rs

1//! Canonical rules source — single source of truth for all lean-ctx guidance.
2//!
3//! All content is declared as `pub const` at the top. Three profiles (LONGFORM,
4//! FULL, COMPACT) define which sections compose each output format. Four
5//! wrappers (Longform, Dedicated, Shared, Bare) select the profile and wrapping
6//! style. One `render()` function assembles everything, including the
7//! compression-level output-style prompt (Lite / Standard / Max).
8//!
9//! Profile economics (#578): every *injected* file bills its tokens on every
10//! single session, so FULL (dedicated rule files) and COMPACT (shared files +
11//! MCP instructions) stay tight. LONGFORM is carried only by the project
12//! `LEAN-CTX.md`, which agents open on demand — it keeps the verbose teaching
13//! sections (loop taxonomy, navigation paradox, recovery vocabulary, CEP).
14//!
15//! ***Every*** template, injected rule file, AGENTS.md block, and MCP
16//! instructions field MUST derive its content from this module.
17
18use crate::core::config::CompressionLevel;
19
20/// Stable HTML-comment anchor that marks the start of any lean-ctx rule
21/// section.  Never changes — used for find/replace in shared files and for
22/// ownership detection in dedicated files.  The version number follows on the
23/// next line (see `render`).
24pub const START_MARK: &str = "<!-- lean-ctx-rules -->";
25
26/// Prefix shared by every lean-ctx rules marker including legacy versioned
27/// formats (`<!-- lean-ctx-rules-v9 -->`). Use for substring detection when
28/// the exact constant would miss older installs.
29pub const RULES_MARKER_PREFIX: &str = "<!-- lean-ctx-rules";
30
31/// Start marker for lightweight AGENTS.md/CODEBUDDY.md/CLAUDE.md pointer
32/// blocks. These are deliberately separate from `START_MARK` / `<!-- lean-ctx-rules -->`
33/// because the pointer-only vs full-rules distinction drives duplicate detection
34/// in `doctor overhead` — a pointer-only file (`is_pointer_only`) must not be
35/// counted as a second source for its client.
36pub const AGENTS_BLOCK_START: &str = "<!-- lean-ctx -->";
37
38/// End marker for AGENTS.md/CODEBUDDY.md/CLAUDE.md pointer blocks.
39pub const AGENTS_BLOCK_END: &str = "<!-- /lean-ctx -->";
40
41/// Owner banner placed as the first line of the project-level `LEAN-CTX.md`
42/// artifact (`<repo>/LEAN-CTX.md`, `rust/LEAN-CTX.md`). Marks the whole file as
43/// lean-ctx-owned so uninstall can remove it wholesale; the writer
44/// (`hooks::ensure_project_agents_integration`), the regenerator
45/// (`gen_rules` example) and the drift gate all share this one literal.
46pub const PROJECT_LEAN_CTX_OWNED_MARKER: &str = "<!-- lean-ctx-owned: PROJECT-LEAN-CTX.md v1 -->";
47
48/// Closing marker that ends a lean-ctx rule section.
49pub const END_MARK: &str = "<!-- /lean-ctx-rules -->";
50
51/// Markers of the heavy compression / output-style block — the per-turn payload
52/// that drives cross-channel duplication (#684/#548).
53///
54/// `render()` wraps the compression prompt in these markers for **persistent
55/// carriers** (the `Dedicated` and `Shared` wrappers, i.e. every injected rule
56/// file). This is the single carrier/marker model: coverage and dedup
57/// (`core::rules_channel`, `cli::rules_dedup`) detect and thin the payload by
58/// these markers, so the writer and the readers can never disagree again. The
59/// ephemeral `Bare` MCP-instructions channel deliberately omits the markers —
60/// its inclusion is *governed* by carrier coverage (`client_autoloads_compression`),
61/// so a per-session marker would be pure noise.
62pub const COMPRESSION_BLOCK_START: &str = "<!-- lean-ctx-compression -->";
63
64/// Closing marker of the compression / output-style block (see
65/// [`COMPRESSION_BLOCK_START`]).
66pub const COMPRESSION_BLOCK_END: &str = "<!-- /lean-ctx-compression -->";
67
68/// Opening marker of the solution-intelligence block.
69pub const SOLUTION_BLOCK_START: &str = "<!-- lean-ctx-solution -->";
70
71/// Closing marker of the solution-intelligence block.
72pub const SOLUTION_BLOCK_END: &str = "<!-- /lean-ctx-solution -->";
73
74/// The solution-efficiency guidance shared by rule-file generators that do not
75/// use [`render`] directly.
76pub fn enabled_solution_rules_block() -> String {
77    if !crate::core::config::Config::load().solution.enabled {
78        return String::new();
79    }
80
81    format!(
82        "{SOLUTION_BLOCK_START}\n\
83SOLUTION EFFICIENCY: stop at first level that applies:\n\
84skip (YAGNI) → reuse codebase → stdlib → native platform → installed dep → one-line → minimum code.\n\
85Never skip: validation, security, error handling.\n\
86{SOLUTION_BLOCK_END}"
87    )
88}
89
90/// Current rules version (monotonically increasing integer).  Embedded as
91/// `<!-- version: {RULES_VERSION} -->` right after `START_MARK` so the
92/// injection layer can parse it and decide whether a file is up-to-date.
93///
94/// History: v3 (#609) adds the `AGENT_LOOP` taxonomy + `NAV_PARADOX` guidance to
95/// the FULL profile and a compact one-liner to COMPACT. v4 adds recovery guidance
96/// so agents learn the (MCP-optional) decompression paths proactively instead of
97/// re-reading compressed output line-by-line. v5 (#578) is the self-footprint
98/// diet: the injected FULL profile drops to ~470 tokens (the intent playbook
99/// absorbs the loop taxonomy and navigation paradox; the verbose
100/// `AGENT_LOOP`/`NAV_PARADOX`/`RECOVER`/`CEP` sections move to the LONGFORM
101/// profile that only the on-demand project `LEAN-CTX.md` carries).
102/// v6: HookCovered profile strengthened — ctx_compose-first priority, imperative
103/// session memory requirement, ctx_callgraph/ctx_search(semantic) promoted from
104/// optional to mandatory. Fixes agents falling back to native Read+Grep for
105/// exploration on hook-covered hosts (Cursor).
106/// Bumping it forces every committed `LEAN-CTX.md` artifact to be regenerated
107/// (see `tests/rules_drift.rs`) and every injected user file to resync.
108/// v9 (#1287): the "re-reads ~13 tokens" claim is scoped to unchanged
109/// full/auto re-reads — signatures/map re-reads currently return the full
110/// (cached) payload.
111pub const RULES_VERSION: usize = 9;
112
113/// Banner placed at the top of dedicated rule files (non-shadow only).
114pub const CRITICAL: &str = "CRITICAL: ALWAYS use lean-ctx ctx_* tools instead of native equivalents. \
115     This is NOT optional.";
116
117/// Weak-model adherence nudge (#1067 / GH #593). Smaller models (e.g. GLM 5.2 in
118/// Windsurf) often read the tool-mapping rules yet still answer from memory or
119/// reach for a built-in tool instead of emitting an actual MCP call — so
120/// `lean-ctx watch` stays empty and the layer looks "off". This one imperative
121/// line makes the *act of invoking* a ctx_* tool the explicit first step. It
122/// lives in the dedicated rule files of *every* agent (`FULL_NON_SHADOW`), which
123/// is what #1067 asks for; the Windsurf project template (`windsurfrules.txt`)
124/// carries its own copy. It is omitted where it would be dead weight: shadow
125/// mode enforces routing at the call layer, and the `Bare`/instructions channel
126/// is capped separately.
127pub const MUST_INVOKE: &str = "ACTUALLY EMIT the ctx_* tool call (ctx_compose first) — \
128    describing a tool is not calling it.";
129
130/// Compact bullet-list mapping (for both dedicated and shared contexts).
131pub const BULLETS: &str = "\
132MANDATORY MAPPING:\n\
133• Read/cat -> ctx_read(path, mode)\n\
134• Grep -> ctx_search(pattern, path)\n\
135• Shell/bash -> ctx_shell(command)\n\
136• Glob/find -> ctx_glob(pattern)\n\
137• ls/find -> ctx_tree(path, depth)";
138
139/// One-line admonition reinforcing the tool preference.  Always right after
140/// `BULLETS` in both profiles.
141pub const NEVER: &str = "NEVER use native Read/Grep/Shell/Glob when a ctx_* equivalent \
142    exists. SELF-CORRECT: the moment you reach for one, stop and call the ctx_* tool instead.";
143
144/// Intent-to-tool playbook — maps common agent questions to the right tool.
145/// Since v5 it also absorbs the agent-loop phases (#609) and the navigation
146/// paradox one-liner, replacing the separate verbose sections in the injected
147/// profile (they stay verbatim in LONGFORM).
148pub const INTENT: &str = "\
149Tool selection by intent:\n\
150• Orient / understand code (call FIRST) -> ctx_compose\n\
151• Read a file -> ctx_read(path, mode=signatures|map|full); edit after reading -> ctx_patch\n\
152• Exact symbol -> ctx_search(action=symbol); pattern -> ctx_search; by meaning -> ctx_search(action=semantic)\n\
153• Files by glob -> ctx_glob; structure -> ctx_tree; callers/impact -> ctx_callgraph\n\
154• Verify after edits -> ctx_shell(test/build); memory -> ctx_session / ctx_knowledge\n\
155Semantic questions -> search tools, not whole-file reads: reading more ≠ understanding more.";
156
157/// Anti-patterns that waste tokens and round-trips.
158pub const ANTI: &str = "\
159Anti-patterns — do NOT:\n\
160• Chain ctx_search -> ctx_read -> ctx_search(action=symbol) — one ctx_compose replaces all three\n\
161• Use ctx_read(mode=full) for orientation — use mode=signatures\n\
162• Use ctx_callgraph/ctx_graph for const/static/variable refs — they track call\n\
163  edges and file deps only; use ctx_search instead";
164
165/// Encourages parallel tool calls to reduce round-trips.
166pub const PARALLEL: &str = "\
167PARALLEL: fire independent tool calls in the SAME turn — ctx_compose bundles \
168multiple lookups into one call.";
169
170/// Agent-loop tool taxonomy (#609). Names each phase of the gather → act →
171/// verify loop an agent actually runs in and the one lean-ctx tool that serves
172/// it. Since v5 (#578) LONGFORM-only — the injected profiles carry the phases
173/// folded into `INTENT`.
174pub const AGENT_LOOP: &str = "\
175AGENT LOOP (phase -> tool):\n\
176• Orient — understand before acting -> ctx_compose\n\
177• Find — exact symbol by name -> ctx_search(action=symbol)\n\
178• Read — a file, structurally -> ctx_read(mode=signatures|map)\n\
179• Locate — a pattern across files -> ctx_search\n\
180• Trace — callers / callees / blast radius -> ctx_callgraph\n\
181• Verify — after an edit -> ctx_shell(test/build) + native lints";
182
183/// Navigation-paradox guidance (#609): reading more is not understanding more.
184/// Steers semantic questions to BM25 + meaning search and reserves the call/dep
185/// graph for genuinely hidden architectural edges. Since v5 LONGFORM-only —
186/// `INTENT` carries the one-line thesis in the injected profiles.
187pub const NAV_PARADOX: &str = "\
188NAVIGATION PARADOX: reading more ≠ understanding more.\n\
189• Semantic question (\"where/how is X handled?\") -> ctx_search (BM25) + ctx_search(action=semantic) (meaning), not whole-file reads\n\
190• Hidden architectural deps (who calls this, what breaks) -> ctx_callgraph / ctx_graph — for these only\n\
191• Navigate structure (signatures, symbols) before reading entire files";
192
193/// One-line automation reminder.
194pub const AUTO: &str = "Long shell jobs: ctx_shell(run_in_background=true), then poll job_id. \
195    ctx_session=memory; full guide: LEAN-CTX.md";
196
197/// Recovery vocabulary (verbose, LONGFORM profile). lean-ctx compression is fully
198/// reversible (CCR), but agents otherwise only discover the escape hatch reactively
199/// from output hints — so they re-read compressed files line-by-line instead of
200/// expanding (the "too compressed" complaint). The MCP-free path ("read the shown
201/// file path with any tool") covers orgs that forbid MCP. Since v5 every injected
202/// profile (FULL + COMPACT/Bare) carries the terser [`RECOVER_COMPACT`] instead;
203/// the reactive footers in `ctx_read`/`archive`/`ctx_shell` still teach the
204/// `ctx_expand` path in context.
205pub const RECOVER: &str = "RECOVER: compressed output is reversible — never re-read line-by-line. \
206    Need full/exact? Read the shown file path with any tool (no MCP), or \
207    ctx_read(mode=full|raw=true); [Archived]/tee/firewall → ctx_expand(id=...).";
208
209/// Terse injected variant of [`RECOVER`] (FULL + COMPACT/Bare). The cold
210/// first-contact handshake renders the COMPACT profile, so this one-liner keeps
211/// the static char/token budget (`tests/intensive_benchmarks.rs`,
212/// `instructions.rs`); since v5 the FULL dedicated files carry it too (#578).
213/// Keeps the two primary MCP-optional paths and the "never line-by-line" rule.
214/// Must keep the `(no MCP)` clause (asserted in tests).
215pub const RECOVER_COMPACT: &str = "RECOVER: compression is reversible — read the shown path \
216    (no MCP) or ctx_read(raw=true), never re-read line-by-line.";
217
218/// Root restriction hint (#1465). Paths outside project roots and configured
219/// `allow_paths`/`extra_roots` are refused by ctx_* tools. Without this hint
220/// the model discovers the restriction only from a surprise error.
221pub const ROOT_RESTRICTION: &str = "ROOTS: ctx_* refuses paths outside project root + allow_paths. \
222    Use native Read for out-of-root; `lean-ctx doctor` shows effective roots.";
223
224/// Context Engineering Protocol version reference.
225pub const CEP: &str = "CEP v1: 1.ACT FIRST 2.DELTA ONLY (Fn refs) 3.STRUCTURED (+/-/~) \
226     4.ONE LINE PER ACTION 5.QUALITY ANCHOR";
227
228/// LITM end-of-instructions preference line.
229pub const LITM_END: &str = "TOOL PREFERENCE (END): ctx_compose>chain ctx_read>Read ctx_shell>Shell \
230     ctx_search>Grep ctx_glob>Glob ctx_tree>ls | Edit/Write/Delete=native";
231
232/// Minimal rules body for shadow mode (#963). Under shadow-mode interception
233/// native Read/Grep/Shell/Glob calls are transparently routed to ctx_*, so the
234/// tool-mapping and "use ctx_* instead of native" guidance is dead weight — the
235/// enforcement happens at the call layer, not in the prompt. Only the lean-ctx
236/// tools that have *no* native trigger to intercept still need advertising.
237pub const SHADOW_MINIMAL: &str = "\
238lean-ctx shadow mode: native read/search/shell calls auto-route to ctx_* — no tool-mapping needed.\n\
239File editing → native Edit/StrReplace (lean-ctx only handles reads); if denied, use ctx_patch.\n\
240Exclusive tools (no native trigger): ctx_compose (understand code, call first), ctx_search(action=symbol) (exact symbol), ctx_search(action=semantic) (by meaning), ctx_callgraph (callers), ctx_knowledge / ctx_session (memory).";
241
242/// Hook-covered header (GL #1153): the honest replacement for the
243/// `CRITICAL`/`BULLETS`/`NEVER` mapping on hosts whose *installed hooks*
244/// already compress the native tools (Cursor: `preToolUse` rewrite covers
245/// Shell, redirect covers Read/Grep). There a "NEVER use native tools" rule
246/// fights the host's own tool guidance and is unenforceable — the model calls
247/// native tools anyway and the hooks compress them transparently. Saying so
248/// removes the instruction dissonance instead of losing the battle silently.
249pub const HOOK_COVERED_HEADER: &str = "\
250CRITICAL: ALWAYS prefer lean-ctx ctx_* tools over native equivalents — ctx_* tools \
251provide superior caching, compression, and session memory. Hooks compress native \
252Shell/Read/Grep as fallback, but direct ctx_* calls are the primary path.\n\
253ACTUALLY EMIT the ctx_* tool call (ctx_compose first) — describing a tool is not calling it.\n\
254WHY ctx_read > native Read: ctx_read picks the optimal mode (map/signatures/terse) \
255per file, caches unchanged full/auto re-reads (~13 tokens), and compresses 26-92%. Native \
256Read through hook redirect is limited to verbatim pass-through (~5% savings).";
257
258/// The tools worth an explicit MCP call on a hook-covered host: capabilities
259/// with *no* native equivalent the hooks could intercept. Kept in sync with
260/// [`SHADOW_MINIMAL`]'s exclusive-tools line (same rationale, different cause).
261pub const HOOK_COVERED_TOOLS: &str = "\
262MANDATORY MAPPING (always use ctx_* instead of native):\n\
263• Read/cat -> ctx_read(path, mode) — cached, 10 modes, unchanged full/auto re-reads ~13 tokens\n\
264• Grep/search -> ctx_search(pattern, path) — also action=symbol|semantic for definitions/meaning\n\
265• Shell/bash -> ctx_shell(command) — 95+ compression patterns\n\
266• ctx_compose — orient in code FIRST (bundles search + read + symbols) — call before editing/debugging\n\
267• ctx_callgraph — callers, callees, blast radius — use instead of manual file reading\n\
268• ctx_session / ctx_knowledge — persistent memory — record decisions & progress after milestones\n\
269• ctx_expand — recover full text from [Archived]/compressed output";
270
271// ── Output-style compression prompts ───────────────────────────
272
273/// Lite compression — concise, bullet-point output.
274pub const LITE_PROMPT: &str = "\
275OUTPUT STYLE: concise
276- Bullet points over paragraphs
277- Skip filler words and hedging (\"I think\", \"probably\", \"it seems\")
278- 1-sentence explanations max, then code/action
279- No repeating what the user said";
280
281/// Standard compression — dense, atomic fact lines, abbreviations.
282pub const STANDARD_PROMPT: &str = "\
283OUTPUT STYLE: dense
284- Each statement = one atomic fact line
285- Use abbreviations: fn, cfg, impl, deps, req, res, ctx, err, ret
286- Diff lines only (+/-/~), never repeat unchanged code
287- Symbols: → (causes), + (adds), − (removes), ~ (modifies), ∴ (therefore)
288- No narration, no filler, no hedging
289- BUDGET: ≤200 tokens per response unless code block required";
290
291/// Max compression — expert-terse, telegraph format, symbolic vocabulary.
292pub const MAX_PROMPT: &str = "\
293OUTPUT STYLE: expert-terse
294- Telegraph format: subject-verb-object, drop articles/prepositions
295- Symbolic vocabulary: → cause, ∵ because, ∴ therefore, ⊕ add, ⊖ remove, Δ change, ≈ similar, ≠ different, ∈ in/member, ∅ empty/none, ✓ ok, ✗ fail
296- Code blocks: untouched (never compress code syntax)
297- Each line: max 80 chars
298- Zero narration, zero filler
299- BUDGET: ≤100 tokens per non-code response";
300
301/// Raw compression — densest possible output. Bullet points only, zero prose,
302/// diff-style facts, no intro/outro. Tighter than Max (#795).
303pub const RAW_PROMPT: &str = "\
304OUTPUT STYLE: raw-dense
305- Bullet points ONLY, zero prose, no intro, no outro, no greetings
306- Diff-style facts: +added, -removed, ~changed, !breaking
307- One fact per line, max 60 chars
308- Symbolic: → ∵ ∴ ⊕ ⊖ Δ ≈ ≠ ∈ ∅ ✓ ✗ (same as expert-terse)
309- Code blocks: untouched
310- BUDGET: ≤50 tokens per non-code response
311- NEVER explain what you did — show only the result";
312
313/// Return the compression prompt text for a given level (empty string for Off).
314pub fn compression_text(level: CompressionLevel) -> &'static str {
315    match level {
316        CompressionLevel::Off => "",
317        CompressionLevel::Lite => LITE_PROMPT,
318        CompressionLevel::Standard => STANDARD_PROMPT,
319        CompressionLevel::Max => MAX_PROMPT,
320        CompressionLevel::Raw => RAW_PROMPT,
321    }
322}
323
324// The verbose teaching profile — only the on-demand project `LEAN-CTX.md`
325// Static profile arrays removed (#756): replaced by the profile-aware
326// section-builder functions below (longform_non_shadow_sections, etc.).
327
328// ── Profile-aware section assembly (#756) ──────────────────────
329//
330// Each function returns Vec<String> with the same section ordering as the
331// static arrays above, but replaces tool-referencing constants with their
332// dynamic equivalents from `rules_sections`.
333
334fn s(c: &str) -> String {
335    c.to_string()
336}
337
338fn longform_non_shadow_sections(p: &super::tool_profiles::ToolProfile) -> Vec<String> {
339    use super::rules_sections as rs;
340    let mut v = vec![
341        s(CRITICAL),
342        s(MUST_INVOKE),
343        s(BULLETS),
344        s(NEVER),
345        rs::intent_section(p),
346        s(AGENT_LOOP), // verbose teaching — LONGFORM only
347        rs::anti_section(p),
348        s(NAV_PARADOX), // verbose teaching — LONGFORM only
349        s(PARALLEL),
350        s(AUTO),
351        s(RECOVER),
352        s(ROOT_RESTRICTION),
353        s(CEP),
354        rs::litm_end_section(p),
355    ];
356    if let Some(fb) = rs::ctx_call_fallback(p) {
357        v.push(fb);
358    }
359    v
360}
361
362fn full_non_shadow_sections(p: &super::tool_profiles::ToolProfile) -> Vec<String> {
363    use super::rules_sections as rs;
364    let mut v = vec![
365        s(CRITICAL),
366        s(MUST_INVOKE),
367        s(BULLETS),
368        s(NEVER),
369        rs::intent_section(p),
370        rs::anti_section(p),
371        s(PARALLEL),
372        s(AUTO),
373        s(RECOVER_COMPACT),
374        s(ROOT_RESTRICTION),
375        rs::litm_end_section(p),
376    ];
377    if let Some(fb) = rs::ctx_call_fallback(p) {
378        v.push(fb);
379    }
380    v
381}
382
383fn full_shadow_sections(p: &super::tool_profiles::ToolProfile) -> Vec<String> {
384    use super::rules_sections as rs;
385    vec![rs::shadow_minimal_section(p)]
386}
387
388fn hook_covered_non_shadow_sections(p: &super::tool_profiles::ToolProfile) -> Vec<String> {
389    use super::rules_sections as rs;
390    let mut v = vec![
391        s(HOOK_COVERED_HEADER),
392        rs::hook_covered_tools_section(p),
393        s(PARALLEL),
394        s(RECOVER_COMPACT),
395        s(ROOT_RESTRICTION),
396    ];
397    if let Some(fb) = rs::ctx_call_fallback(p) {
398        v.push(fb);
399    }
400    v
401}
402
403fn compact_non_shadow_sections(p: &super::tool_profiles::ToolProfile) -> Vec<String> {
404    use super::rules_sections as rs;
405    let mut v = vec![
406        s(CRITICAL),
407        s(BULLETS),
408        s(NEVER),
409        rs::intent_section(p),
410        rs::anti_section(p),
411        s(PARALLEL),
412        s(RECOVER_COMPACT),
413        s(ROOT_RESTRICTION),
414    ];
415    if let Some(fb) = rs::ctx_call_fallback(p) {
416        v.push(fb);
417    }
418    v
419}
420
421fn compact_shadow_sections(p: &super::tool_profiles::ToolProfile) -> Vec<String> {
422    use super::rules_sections as rs;
423    vec![rs::shadow_minimal_section(p)]
424}
425
426/// Selects the profile (LONGFORM / FULL / COMPACT) and the wrapping style
427/// (markers, headers, footers) for `render()`.
428#[derive(Debug, Clone, Copy, PartialEq, Eq)]
429pub enum Wrapper {
430    /// **On-demand long form** (project `LEAN-CTX.md`). LONGFORM profile with
431    /// the same marker wrapping as `Dedicated`. Not auto-loaded by any client
432    /// — agents open it on demand via the AGENTS.md pointer, so it can afford
433    /// the verbose teaching sections.
434    Longform,
435
436    /// **Dedicated rule file.**  FULL profile.  Wrapped with `START_MARK`,
437    /// `<!-- version: N -->`, and `END_MARK`.  Non-shadow includes the
438    /// `CRITICAL` banner before the body.  The whole file is lean-ctx–owned;
439    /// the injection layer detects staleness by parsing the version comment.
440    Dedicated,
441
442    /// **Shared file section** (appended to AGENTS.md, GEMINI.md, etc.).
443    /// COMPACT profile.  Same marker wrapping for find/replace within a
444    /// larger shared file.  Non-shadow includes `## Tool Mapping` header.
445    Shared,
446
447    /// **MCP session instructions.**  COMPACT profile.  No markers or
448    /// headers — bare content used inline in per-session MCP instructions.
449    Bare,
450
451    /// **Hook-covered dedicated rule file** (GL #1153). For hosts whose
452    /// installed lean-ctx hooks already compress the native tools (Cursor:
453    /// PreToolUse rewrite/redirect). Same marker/version wrapping as
454    /// `Dedicated`, but the body swaps the unenforceable tool-mapping for the
455    /// honest hook-coverage note plus the exclusive-capability advert.
456    /// Shadow mode collapses it to the same minimal profile as `Dedicated`.
457    HookCovered,
458}
459
460/// Render lean-ctx rules for a given wrapper, shadow mode, compression level,
461/// and tool profile (#756).
462///
463/// * `shadow` — when true, tool-mapping sections (BULLETS, NEVER,
464///   CRITICAL banner, "## Tool Mapping" header) are omitted.
465/// * `wrapper` — selects the profile (FULL / COMPACT) and wrapping style.
466/// * `level` — selects the output-style compression prompt (Lite / Standard /
467///   Max) which is appended to the body. `Off` omits it.
468/// * `tool_profile` — filters tool references in dynamic sections so agents
469///   only see tools they can actually call.
470pub fn render(
471    shadow: bool,
472    wrapper: Wrapper,
473    level: CompressionLevel,
474    tool_profile: &super::tool_profiles::ToolProfile,
475) -> String {
476    use super::rules_sections as rs;
477
478    let sections: Vec<String> = match (wrapper, shadow) {
479        (Wrapper::Longform, false) => longform_non_shadow_sections(tool_profile),
480        (Wrapper::Longform | Wrapper::Dedicated | Wrapper::HookCovered, true) => {
481            full_shadow_sections(tool_profile)
482        }
483        (Wrapper::Dedicated, false) => full_non_shadow_sections(tool_profile),
484        (Wrapper::HookCovered, false) => hook_covered_non_shadow_sections(tool_profile),
485        (_, false) => compact_non_shadow_sections(tool_profile),
486        (_, true) => compact_shadow_sections(tool_profile),
487    };
488
489    // Suppress empty sections (a section builder may return "" when the
490    // profile hides all tools it would mention).
491    let mut body: String = sections
492        .into_iter()
493        .filter(|s| !s.is_empty())
494        .collect::<Vec<_>>()
495        .join("\n\n");
496    let _ = rs::intent_section; // anchor — ensures the module is linked
497
498    // Append the compression / output-style prompt for active levels. Persistent
499    // carriers (Dedicated, Shared) wrap it in the canonical COMPRESSION_BLOCK
500    // markers so coverage/dedup (rules_channel, rules_dedup) can detect and thin
501    // it; the ephemeral Bare MCP channel keeps it unmarked (#684/#548).
502    let compression = compression_text(level);
503    if !compression.is_empty() {
504        body.push('\n');
505        if matches!(wrapper, Wrapper::Bare) {
506            body.push_str(compression);
507        } else {
508            body.push_str(COMPRESSION_BLOCK_START);
509            body.push('\n');
510            body.push_str(compression);
511            body.push('\n');
512            body.push_str(COMPRESSION_BLOCK_END);
513        }
514    }
515
516    // Solution Intelligence block: inject efficiency ladder when enabled
517    {
518        let cfg = crate::core::config::Config::load();
519        if cfg.solution.enabled {
520            let ladder = cfg.solution.ladder_text();
521            if !ladder.is_empty() {
522                body.push('\n');
523                if matches!(wrapper, Wrapper::Bare) {
524                    body.push_str(ladder);
525                } else {
526                    body.push_str(SOLUTION_BLOCK_START);
527                    body.push('\n');
528                    body.push_str("SOLUTION EFFICIENCY: stop at first level that applies:\n");
529                    body.push_str("skip (YAGNI) → reuse codebase → stdlib → native platform → installed dep → one-line → minimum code.\n");
530                    body.push_str("Never skip: validation, security, error handling.\n");
531                    body.push_str(SOLUTION_BLOCK_END);
532                }
533            }
534        }
535    }
536
537    if matches!(wrapper, Wrapper::Bare) {
538        return body;
539    }
540
541    let version_line = format!("<!-- version: {RULES_VERSION} -->");
542
543    format!("{START_MARK}\n{version_line}\n\n{body}\n{END_MARK}")
544}
545
546/// Unmarked render of the hook-covered profile for ephemeral channels
547/// (the mcp.json `instructions` snapshot on hook-covered hosts, GL #1153).
548/// The `Bare` counterpart of `Wrapper::HookCovered`: same body, no markers —
549/// per-session channels are governed by carrier coverage, so markers would be
550/// noise (see [`COMPRESSION_BLOCK_START`]). Shadow collapses to the regular
551/// bare shadow profile (interception supersedes hook coverage).
552pub fn render_hook_covered_bare(
553    shadow: bool,
554    level: CompressionLevel,
555    tool_profile: &super::tool_profiles::ToolProfile,
556) -> String {
557    if shadow {
558        return render(true, Wrapper::Bare, level, tool_profile);
559    }
560    let sections = hook_covered_non_shadow_sections(tool_profile);
561    let mut body: String = sections
562        .into_iter()
563        .filter(|s| !s.is_empty())
564        .collect::<Vec<_>>()
565        .join("\n\n");
566    let compression = compression_text(level);
567    if !compression.is_empty() {
568        body.push('\n');
569        body.push_str(compression);
570    }
571    body
572}
573// Rules-file parsing and validation live in the sibling module.
574pub use super::rules_validation::RulesFile;
575
576#[cfg(test)]
577mod tests {
578    use super::*;
579
580    fn tp() -> super::super::tool_profiles::ToolProfile {
581        super::super::tool_profiles::ToolProfile::Power
582    }
583
584    // --- Constants ---
585
586    #[test]
587    fn bullets_uses_ctx_shell() {
588        assert!(BULLETS.contains("ctx_shell"));
589        assert!(!BULLETS.contains("lean-ctx -c"));
590        assert!(!BULLETS.contains("ctx_edit"));
591    }
592
593    #[test]
594    fn sections_not_empty() {
595        assert!(!BULLETS.is_empty());
596        assert!(!NEVER.is_empty());
597        assert!(!INTENT.is_empty());
598        assert!(!ANTI.is_empty());
599        assert!(!PARALLEL.is_empty());
600        assert!(!AUTO.is_empty());
601        assert!(!CEP.is_empty());
602        assert!(!LITM_END.is_empty());
603        assert!(!CRITICAL.is_empty());
604    }
605
606    #[test]
607    fn intent_contains_ctx_compose() {
608        assert!(INTENT.contains("ctx_compose"));
609    }
610
611    #[test]
612    fn anti_contains_do_not() {
613        assert!(ANTI.contains("do NOT"));
614    }
615
616    #[test]
617    fn parallel_contains_parallel() {
618        assert!(PARALLEL.contains("PARALLEL"));
619    }
620
621    // --- Agent loop + navigation paradox (#609) ---
622
623    #[test]
624    fn agent_loop_names_every_phase() {
625        for phase in ["Orient", "Find", "Read", "Locate", "Trace", "Verify"] {
626            assert!(AGENT_LOOP.contains(phase), "AGENT_LOOP must name {phase}");
627        }
628        assert!(AGENT_LOOP.contains("ctx_compose") && AGENT_LOOP.contains("ctx_callgraph"));
629    }
630
631    #[test]
632    fn nav_paradox_steers_semantic_vs_graph() {
633        assert!(
634            NAV_PARADOX.contains("ctx_search(action=semantic)"),
635            "semantic route must use folded action (#509)"
636        );
637        assert!(NAV_PARADOX.contains("ctx_callgraph"), "graph route");
638        assert!(
639            NAV_PARADOX.contains("≠"),
640            "must carry the reading≠understanding thesis"
641        );
642    }
643
644    #[test]
645    fn longform_carries_loop_and_paradox_injected_full_does_not() {
646        // v5 (#578): the verbose teaching sections live only in the on-demand
647        // LEAN-CTX.md (Longform); the injected dedicated files fold the loop
648        // phases + paradox thesis into INTENT.
649        let long = render(false, Wrapper::Longform, CompressionLevel::Off, &tp());
650        assert!(
651            long.contains("AGENT LOOP"),
652            "LONGFORM must carry AGENT_LOOP"
653        );
654        assert!(
655            long.contains("NAVIGATION PARADOX"),
656            "LONGFORM must carry NAV_PARADOX"
657        );
658        assert!(long.contains(CEP), "LONGFORM must carry CEP");
659
660        let full = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
661        assert!(
662            !full.contains("AGENT LOOP (phase -> tool):"),
663            "injected FULL must not inline the multi-line AGENT_LOOP block"
664        );
665        assert!(
666            !full.contains("NAVIGATION PARADOX: reading"),
667            "injected FULL must not inline the multi-line NAV_PARADOX block"
668        );
669        assert!(
670            full.contains('≠'),
671            "INTENT must keep the reading≠understanding thesis in FULL"
672        );
673        // #509: ctx_symbol folded into ctx_search(action=symbol)
674        for phase_tool in [
675            "ctx_compose",
676            "ctx_search(action=symbol)",
677            "ctx_search",
678            "ctx_callgraph",
679        ] {
680            assert!(
681                full.contains(phase_tool),
682                "FULL keeps the loop tools via INTENT: {phase_tool}"
683            );
684        }
685    }
686
687    #[test]
688    fn injected_profiles_stay_lean() {
689        // The whole point of v5 (#578): injected files bill every session.
690        // chars/4 ≈ tokens — the dedicated body must stay around ~470 tok and
691        // the Longform must be a strict superset.
692        let full = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
693        eprintln!(
694            "rules footprint: dedicated={} chars (~{} tok), longform={} chars, bare={} chars",
695            full.len(),
696            full.len() / 4,
697            render(false, Wrapper::Longform, CompressionLevel::Off, &tp()).len(),
698            render(false, Wrapper::Bare, CompressionLevel::Off, &tp()).len(),
699        );
700        assert!(
701            full.len() <= 2400,
702            "injected dedicated rules must stay ≤2400 chars (~600 tok), got {} chars (~{} tok)",
703            full.len(),
704            full.len() / 4
705        );
706        let long = render(false, Wrapper::Longform, CompressionLevel::Off, &tp());
707        assert!(
708            long.len() > full.len(),
709            "Longform ({}) must carry more than the injected profile ({})",
710            long.len(),
711            full.len()
712        );
713        let compact = render(false, Wrapper::Bare, CompressionLevel::Off, &tp());
714        assert!(
715            compact.len() < full.len(),
716            "COMPACT/Bare ({}) must stay below the dedicated profile ({})",
717            compact.len(),
718            full.len()
719        );
720    }
721
722    #[test]
723    fn compact_profile_has_no_multiline_teaching_sections() {
724        // COMPACT (shared + Bare) keeps the per-session channel lean: no
725        // multi-line AGENT_LOOP/NAV_PARADOX blocks; INTENT carries the thesis.
726        let out = render(false, Wrapper::Shared, CompressionLevel::Off, &tp());
727        assert!(
728            !out.contains("AGENT LOOP (phase -> tool):"),
729            "COMPACT must not inline the multi-line AGENT_LOOP block"
730        );
731        assert!(
732            !out.contains("NAVIGATION PARADOX: reading"),
733            "COMPACT must not inline the multi-line NAV_PARADOX block"
734        );
735        assert!(
736            out.contains('≠'),
737            "COMPACT keeps the reading≠understanding thesis via INTENT"
738        );
739    }
740
741    #[test]
742    fn shadow_omits_loop_and_paradox() {
743        // #963: shadow collapses to the irreducible minimum — the routing
744        // taxonomy is redundant once native calls are intercepted.
745        for wrapper in [Wrapper::Longform, Wrapper::Dedicated, Wrapper::Shared] {
746            let out = render(true, wrapper, CompressionLevel::Off, &tp());
747            assert!(!out.contains("AGENT LOOP"), "{wrapper:?} shadow drops loop");
748            assert!(
749                !out.contains("NAVIGATION PARADOX"),
750                "{wrapper:?} shadow drops paradox"
751            );
752        }
753    }
754
755    #[test]
756    fn recover_reaches_every_non_shadow_carrier() {
757        // The recovery vocabulary must reach every non-shadow carrier so agents
758        // never re-read compressed output line-by-line, and every carrier must
759        // keep the MCP-free path ("read the shown path") for orgs that ban MCP.
760        // v5 (#578): only Longform carries the verbose RECOVER; every injected
761        // profile (Dedicated FULL + Shared/Bare COMPACT) carries the terse
762        // RECOVER_COMPACT one-liner.
763        let long = render(false, Wrapper::Longform, CompressionLevel::Off, &tp());
764        assert!(
765            long.contains(RECOVER),
766            "Longform must carry the verbose RECOVER verbatim"
767        );
768        for wrapper in [Wrapper::Dedicated, Wrapper::Shared, Wrapper::Bare] {
769            let out = render(false, wrapper, CompressionLevel::Off, &tp());
770            assert!(
771                out.contains(RECOVER_COMPACT),
772                "{wrapper:?} must carry RECOVER_COMPACT verbatim"
773            );
774            assert!(
775                !out.contains(RECOVER),
776                "{wrapper:?} must not inline the verbose RECOVER block"
777            );
778        }
779        for wrapper in [
780            Wrapper::Longform,
781            Wrapper::Dedicated,
782            Wrapper::Shared,
783            Wrapper::Bare,
784        ] {
785            assert!(
786                render(false, wrapper, CompressionLevel::Off, &tp()).contains("(no MCP)"),
787                "{wrapper:?} recovery line must keep the MCP-free path"
788            );
789        }
790        for wrapper in [Wrapper::Dedicated, Wrapper::Shared] {
791            let out = render(true, wrapper, CompressionLevel::Off, &tp());
792            assert!(
793                !out.contains(RECOVER) && !out.contains(RECOVER_COMPACT),
794                "{wrapper:?} shadow drops all RECOVER guidance"
795            );
796        }
797    }
798
799    // --- render() — Dedicated ---
800
801    #[test]
802    fn dedicated_has_markers_and_version() {
803        let out = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
804        assert!(out.contains(START_MARK));
805        assert!(out.contains(&format!("<!-- version: {RULES_VERSION} -->")));
806        assert!(out.contains(END_MARK));
807        assert!(out.contains(BULLETS));
808        assert!(out.contains(NEVER));
809        assert!(out.contains("CRITICAL"));
810    }
811
812    #[test]
813    fn dedicated_shadow_is_minimal() {
814        // #963: shadow drops the whole tool-mapping AND routing playbook —
815        // interception makes them redundant. Only the exclusive-tool advert remains.
816        let out = render(true, Wrapper::Dedicated, CompressionLevel::Off, &tp());
817        assert!(out.contains(START_MARK));
818        assert!(!out.contains("MANDATORY MAPPING"), "no BULLETS in shadow");
819        assert!(!out.contains(NEVER), "no NEVER in shadow");
820        assert!(!out.contains("CRITICAL"), "no CRITICAL banner in shadow");
821        assert!(
822            !out.contains("Tool selection by intent"),
823            "routing INTENT block is redundant under interception"
824        );
825        assert!(
826            !out.contains("Anti-patterns") && !out.contains("PARALLEL tool calls"),
827            "ANTI/PARALLEL routing guidance is dropped in shadow"
828        );
829        assert!(
830            out.contains("shadow mode") && out.contains("ctx_compose"),
831            "shadow keeps the exclusive-tool advert"
832        );
833    }
834
835    #[test]
836    fn shadow_is_smaller_than_non_shadow() {
837        // The whole point of #963: the shadow body must be a strict reduction.
838        let shadow = render(true, Wrapper::Dedicated, CompressionLevel::Off, &tp());
839        let full = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
840        assert!(
841            shadow.len() < full.len(),
842            "shadow ({}) must be smaller than non-shadow ({})",
843            shadow.len(),
844            full.len()
845        );
846    }
847
848    #[test]
849    fn dedicated_litm_structure() {
850        let out = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
851        let lines: Vec<&str> = out.lines().collect();
852        let first_5 = lines[..5.min(lines.len())].join("\n");
853        assert!(
854            first_5.contains("CRITICAL") || first_5.contains("MUST"),
855            "LITM: MUST/CRITICAL instruction near start"
856        );
857        // LITM_END or NEVER should appear in the final content lines (before END_MARK).
858        let tail = lines[lines.len().saturating_sub(8)..].join("\n");
859        assert!(
860            tail.contains("PREFERENCE") || tail.contains("NEVER"),
861            "LITM: reinforcement near end, tail={tail:?}"
862        );
863    }
864
865    #[test]
866    fn dedicated_carries_weak_model_invoke_nudge() {
867        // #1067/GH #593: the "actually CALL ctx_*" nudge must ride every dedicated
868        // rule file (Windsurf, Cursor, Claude, …) in non-shadow mode, and must be
869        // absent where it is dead weight: shadow mode (call-layer routing) and the
870        // Bare/instructions channel (separately capped).
871        let dedicated = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
872        assert!(
873            dedicated.contains(MUST_INVOKE),
874            "dedicated non-shadow rules must carry the MUST_INVOKE nudge"
875        );
876        assert!(
877            !render(true, Wrapper::Dedicated, CompressionLevel::Off, &tp()).contains(MUST_INVOKE),
878            "shadow mode must not carry the nudge (routing is enforced at the call layer)"
879        );
880        assert!(
881            !render(false, Wrapper::Bare, CompressionLevel::Off, &tp()).contains(MUST_INVOKE),
882            "Bare/instructions channel is capped separately and carries no copy"
883        );
884    }
885
886    // --- render() — Shared ---
887
888    #[test]
889    fn shared_has_markers_and_header() {
890        let out = render(false, Wrapper::Shared, CompressionLevel::Off, &tp());
891        assert!(out.contains(START_MARK));
892        assert!(out.contains(END_MARK));
893        assert!(out.contains("MANDATORY MAPPING"));
894        assert!(out.contains(BULLETS));
895    }
896
897    #[test]
898    fn shared_shadow_omits_mapping() {
899        let out = render(true, Wrapper::Shared, CompressionLevel::Off, &tp());
900        assert!(out.contains(START_MARK));
901        assert!(
902            !out.contains("MANDATORY MAPPING"),
903            "shadow must not have header"
904        );
905        assert!(
906            !out.contains("MANDATORY MAPPING"),
907            "shadow must not contain BULLETS"
908        );
909    }
910
911    // --- render() — Bare ---
912
913    #[test]
914    fn bare_has_no_markers() {
915        let out = render(false, Wrapper::Bare, CompressionLevel::Off, &tp());
916        assert!(!out.contains(START_MARK), "Bare must not have START_MARK");
917        assert!(!out.contains(END_MARK), "Bare must not have END_MARK");
918        assert!(!out.contains("<!-- version:"), "Bare must not have version");
919        assert!(out.contains(BULLETS));
920        assert!(out.contains(NEVER));
921    }
922
923    #[test]
924    fn bare_shadow_only_read_modes() {
925        let out = render(true, Wrapper::Bare, CompressionLevel::Off, &tp());
926        assert!(!out.contains(NEVER), "shadow Bare must not have NEVER");
927        assert!(
928            !out.contains("MANDATORY MAPPING"),
929            "shadow Bare must not have BULLETS"
930        );
931    }
932
933    // --- Compression level tests ---
934
935    #[test]
936    fn render_includes_lite_prompt() {
937        let out = render(false, Wrapper::Bare, CompressionLevel::Lite, &tp());
938        assert!(out.contains("OUTPUT STYLE: concise"));
939        assert!(out.contains("Bullet points"));
940    }
941
942    #[test]
943    fn render_includes_standard_prompt() {
944        let out = render(false, Wrapper::Bare, CompressionLevel::Standard, &tp());
945        assert!(out.contains("OUTPUT STYLE: dense"));
946        assert!(out.contains("atomic fact"));
947    }
948
949    #[test]
950    fn render_includes_max_prompt() {
951        let out = render(false, Wrapper::Bare, CompressionLevel::Max, &tp());
952        assert!(out.contains("OUTPUT STYLE: expert-terse"));
953        assert!(out.contains("Telegraph"));
954    }
955
956    #[test]
957    fn render_off_excludes_compression() {
958        let out = render(false, Wrapper::Bare, CompressionLevel::Off, &tp());
959        assert!(!out.contains("OUTPUT STYLE:"));
960    }
961
962    #[test]
963    fn compression_text_matches_level() {
964        assert!(compression_text(CompressionLevel::Off).is_empty());
965        assert!(compression_text(CompressionLevel::Lite).contains("Bullet"));
966        assert!(compression_text(CompressionLevel::Standard).contains("fn, cfg"));
967        assert!(compression_text(CompressionLevel::Max).contains("Telegraph"));
968    }
969
970    // --- Compression marker model (#548 B2) ---
971
972    #[test]
973    fn carrier_wrappers_wrap_compression_in_markers() {
974        // Persistent carriers must delimit the compression payload so coverage
975        // and dedup can detect/thin it (#684/#548).
976        for wrapper in [Wrapper::Longform, Wrapper::Dedicated, Wrapper::Shared] {
977            let out = render(false, wrapper, CompressionLevel::Standard, &tp());
978            assert!(
979                out.contains(COMPRESSION_BLOCK_START) && out.contains(COMPRESSION_BLOCK_END),
980                "{wrapper:?} must wrap compression in COMPRESSION_BLOCK markers"
981            );
982            // The marked region must actually contain the prompt body.
983            let start = out.find(COMPRESSION_BLOCK_START).unwrap();
984            let end = out.find(COMPRESSION_BLOCK_END).unwrap();
985            assert!(start < end, "{wrapper:?}: start marker precedes end marker");
986            assert!(out[start..end].contains("OUTPUT STYLE: dense"));
987        }
988    }
989
990    #[test]
991    fn bare_wrapper_emits_compression_without_markers() {
992        // The ephemeral MCP channel keeps the payload unmarked — its inclusion is
993        // governed by carrier coverage, so per-session markers would be noise.
994        let out = render(false, Wrapper::Bare, CompressionLevel::Standard, &tp());
995        assert!(out.contains("OUTPUT STYLE: dense"));
996        assert!(!out.contains(COMPRESSION_BLOCK_START));
997        assert!(!out.contains(COMPRESSION_BLOCK_END));
998    }
999
1000    #[test]
1001    fn compression_off_emits_no_markers_in_any_wrapper() {
1002        for wrapper in [
1003            Wrapper::Longform,
1004            Wrapper::Dedicated,
1005            Wrapper::Shared,
1006            Wrapper::Bare,
1007        ] {
1008            let out = render(false, wrapper, CompressionLevel::Off, &tp());
1009            assert!(
1010                !out.contains(COMPRESSION_BLOCK_START) && !out.contains(COMPRESSION_BLOCK_END),
1011                "{wrapper:?}: Off must emit no compression markers"
1012            );
1013        }
1014    }
1015
1016    #[test]
1017    fn rendered_carrier_block_is_seen_as_carrying_compression() {
1018        // The detection helper that coverage/dedup rely on must agree with the
1019        // writer's output (the bug this slice fixes: it previously never did).
1020        let dedicated = render(false, Wrapper::Dedicated, CompressionLevel::Lite, &tp());
1021        assert!(crate::core::rules_channel::carries_full_rules(&dedicated));
1022        assert!(dedicated.contains(COMPRESSION_BLOCK_START));
1023    }
1024
1025    // --- Wrapper round-trip ---
1026
1027    #[test]
1028    fn all_wrappers_produce_output() {
1029        for shadow in [false, true] {
1030            for wrapper in [
1031                Wrapper::Longform,
1032                Wrapper::Dedicated,
1033                Wrapper::Shared,
1034                Wrapper::Bare,
1035            ] {
1036                let out = render(shadow, wrapper, CompressionLevel::Off, &tp());
1037                assert!(!out.is_empty(), "{wrapper:?} shadow={shadow} is empty");
1038            }
1039        }
1040    }
1041
1042    // --- RulesFile ---
1043
1044    #[test]
1045    fn rules_file_parses_version() {
1046        let content = format!(
1047            "stuff before\n{START_MARK}\n<!-- version: {RULES_VERSION} -->\n\nbody\n{END_MARK}\nstuff after"
1048        );
1049        let f = RulesFile::parse(&content);
1050        assert!(f.has_content());
1051        assert_eq!(f.version(), RULES_VERSION);
1052        assert!(f.is_current());
1053        assert!(f.prefix().contains("stuff before"));
1054        assert!(f.suffix().contains("stuff after"));
1055    }
1056
1057    #[test]
1058    fn rules_file_no_version_defaults_to_zero() {
1059        let content = format!("{START_MARK}\nbody\n{END_MARK}");
1060        let f = RulesFile::parse(&content);
1061        assert!(f.has_content());
1062        assert_eq!(f.version(), 0);
1063        assert!(!f.is_current());
1064    }
1065
1066    #[test]
1067    fn rules_file_no_start_marker_no_content() {
1068        let f = RulesFile::parse("just user stuff");
1069        assert!(!f.has_content());
1070        assert_eq!(f.version(), 0);
1071    }
1072
1073    #[test]
1074    fn block_matches_render_true_for_fresh_render() {
1075        let fresh = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
1076        let content = format!("user before\n{fresh}\nuser after");
1077        let f = RulesFile::parse(&content);
1078        assert!(f.is_current(), "fresh render carries the current version");
1079        assert!(
1080            f.block_matches_render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp()),
1081            "an unchanged block must compare equal to a fresh render"
1082        );
1083    }
1084
1085    #[test]
1086    fn block_matches_render_false_on_compression_change() {
1087        // Body rendered at Off, then asked whether it matches a Max render:
1088        // the version is identical but the compression payload differs (#548).
1089        let content = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
1090        let f = RulesFile::parse(&content);
1091        assert!(f.is_current());
1092        assert!(
1093            !f.block_matches_render(false, Wrapper::Dedicated, CompressionLevel::Max, &tp()),
1094            "a compression-level change must be detected as drift"
1095        );
1096    }
1097
1098    #[test]
1099    fn block_matches_render_false_on_shadow_change() {
1100        let content = render(false, Wrapper::Dedicated, CompressionLevel::Lite, &tp());
1101        let f = RulesFile::parse(&content);
1102        assert!(
1103            !f.block_matches_render(true, Wrapper::Dedicated, CompressionLevel::Lite, &tp()),
1104            "a shadow-mode toggle must be detected as drift"
1105        );
1106    }
1107
1108    #[test]
1109    fn block_matches_render_false_without_block() {
1110        let f = RulesFile::parse("plain user content, no markers");
1111        assert!(!f.block_matches_render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp()));
1112    }
1113
1114    #[test]
1115    fn rules_file_merged_replaces_section() {
1116        let content =
1117            format!("before\n{START_MARK}\n<!-- version: 1 -->\n\nold\n{END_MARK}\nafter");
1118        let f = RulesFile::parse(&content);
1119        let merged = f.merged(false, Wrapper::Shared, CompressionLevel::Off, &tp());
1120        assert!(merged.contains("before"), "prefix preserved");
1121        assert!(merged.contains("after"), "suffix preserved");
1122        assert!(!merged.contains("old"), "old content replaced");
1123        assert!(merged.contains(&format!("<!-- version: {RULES_VERSION} -->")));
1124    }
1125
1126    #[test]
1127    fn rules_file_merged_appends_when_no_section() {
1128        let content = "user content";
1129        let f = RulesFile::parse(content);
1130        assert!(!f.has_content());
1131        let merged = f.merged(false, Wrapper::Bare, CompressionLevel::Off, &tp());
1132        assert!(merged.contains("user content"));
1133        assert!(merged.contains(BULLETS));
1134    }
1135
1136    #[test]
1137    fn rules_file_without_section_strips_content() {
1138        let content =
1139            format!("header\n{START_MARK}\n<!-- version: 1 -->\n\nbody\n{END_MARK}\nfooter");
1140        let f = RulesFile::parse(&content);
1141        let stripped = f.without_section();
1142        assert!(stripped.contains("header"));
1143        assert!(stripped.contains("footer"));
1144        assert!(!stripped.contains("body"));
1145        assert!(!stripped.contains(START_MARK));
1146    }
1147
1148    #[test]
1149    fn rules_file_without_section_noop_when_no_content() {
1150        let content = "just user text";
1151        let f = RulesFile::parse(content);
1152        assert_eq!(f.without_section(), content);
1153    }
1154
1155    #[test]
1156    fn bullets_lead_with_four_core_redirects() {
1157        // Most-used routes (Read/Grep/Shell/Glob) lead; ls->ctx_tree trails.
1158        let read = BULLETS.find("ctx_read").expect("ctx_read mapping present");
1159        let search = BULLETS
1160            .find("ctx_search")
1161            .expect("ctx_search mapping present");
1162        let shell = BULLETS
1163            .find("ctx_shell")
1164            .expect("ctx_shell mapping present");
1165        let glob = BULLETS.find("ctx_glob").expect("ctx_glob mapping present");
1166        let tree = BULLETS.find("ctx_tree").expect("ctx_tree mapping present");
1167        assert!(
1168            read < search && search < shell && shell < glob && glob < tree,
1169            "core redirects (read<search<shell<glob) must precede ctx_tree"
1170        );
1171    }
1172
1173    #[test]
1174    fn never_carries_self_correction() {
1175        // Self-correction reinforces the redirect harder than a bare prohibition.
1176        assert!(
1177            NEVER.contains("SELF-CORRECT"),
1178            "NEVER must teach self-correction"
1179        );
1180        assert!(
1181            NEVER.contains("call"),
1182            "NEVER must spell out the corrective action"
1183        );
1184    }
1185
1186    #[test]
1187    fn critical_names_ctx_family() {
1188        assert!(
1189            CRITICAL.contains("ctx_*"),
1190            "CRITICAL must name the ctx_* family"
1191        );
1192    }
1193
1194    // --- HookCovered profile (GL #1153) ---
1195
1196    #[test]
1197    fn hook_covered_carries_strict_mapping() {
1198        // v8: HookCovered is strict — always prefer ctx_* over native tools.
1199        // The MANDATORY MAPPING replaces the old "no native equivalent" list.
1200        let out = render(false, Wrapper::HookCovered, CompressionLevel::Off, &tp());
1201        assert!(
1202            !out.contains(NEVER),
1203            "HookCovered uses its own strict header, not the NEVER constant"
1204        );
1205        assert!(
1206            out.contains(HOOK_COVERED_HEADER),
1207            "must carry the strict preference header"
1208        );
1209        assert!(
1210            out.contains("MANDATORY MAPPING")
1211                && out.contains("ctx_read")
1212                && out.contains("ctx_search"),
1213            "must carry the full mandatory mapping"
1214        );
1215        assert!(
1216            out.contains("ctx_compose") && out.contains("action=symbol|semantic"),
1217            "must advertise the search capabilities"
1218        );
1219    }
1220
1221    #[test]
1222    fn hook_covered_keeps_markers_version_and_recovery() {
1223        // Coverage detection (rules_channel::carries_full_rules /
1224        // client_autoloads_rules) and the injector's drift check both key on
1225        // the canonical markers — HookCovered must stay a first-class carrier.
1226        let out = render(false, Wrapper::HookCovered, CompressionLevel::Off, &tp());
1227        assert!(out.contains(START_MARK) && out.contains(END_MARK));
1228        assert!(out.contains(&format!("<!-- version: {RULES_VERSION} -->")));
1229        assert!(out.contains(RECOVER_COMPACT), "recovery line must survive");
1230        assert!(out.contains("(no MCP)"), "MCP-free recovery path stays");
1231    }
1232
1233    #[test]
1234    fn hook_covered_is_leaner_than_full() {
1235        let covered = render(false, Wrapper::HookCovered, CompressionLevel::Off, &tp());
1236        let full = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
1237        assert!(
1238            covered.len() < full.len(),
1239            "HookCovered ({}) must be a strict reduction of FULL ({})",
1240            covered.len(),
1241            full.len()
1242        );
1243    }
1244
1245    #[test]
1246    fn hook_covered_shadow_collapses_to_minimal() {
1247        // Interception supersedes hook coverage — same minimal profile as
1248        // Dedicated shadow.
1249        let covered_shadow = render(true, Wrapper::HookCovered, CompressionLevel::Off, &tp());
1250        let dedicated_shadow = render(true, Wrapper::Dedicated, CompressionLevel::Off, &tp());
1251        assert_eq!(covered_shadow, dedicated_shadow);
1252    }
1253
1254    #[test]
1255    fn hook_covered_wraps_compression_in_markers() {
1256        let out = render(
1257            false,
1258            Wrapper::HookCovered,
1259            CompressionLevel::Standard,
1260            &tp(),
1261        );
1262        assert!(out.contains(COMPRESSION_BLOCK_START) && out.contains(COMPRESSION_BLOCK_END));
1263        assert!(out.contains("OUTPUT STYLE: dense"));
1264    }
1265
1266    // --- Profile-aware rules (#756) ---
1267
1268    #[test]
1269    fn rules_only_mention_enabled_tools() {
1270        use super::super::rules_sections;
1271        use super::super::tool_profiles::ToolProfile;
1272        let exclusive_tools = ["ctx_compose", "ctx_callgraph", "ctx_patch"];
1273        for profile in [ToolProfile::Minimal, ToolProfile::Standard] {
1274            let mut sections = vec![
1275                rules_sections::intent_section(&profile),
1276                rules_sections::hook_covered_tools_section(&profile),
1277                rules_sections::shadow_minimal_section(&profile),
1278                rules_sections::anti_section(&profile),
1279                rules_sections::litm_end_section(&profile),
1280            ];
1281            if let Some(fb) = rules_sections::ctx_call_fallback(&profile) {
1282                sections.push(fb);
1283            }
1284            for tool in &exclusive_tools {
1285                if !profile.is_tool_enabled(tool) {
1286                    for section in &sections {
1287                        assert!(
1288                            !section.contains(tool),
1289                            "profile {:?} dynamic section must not mention disabled tool {tool}",
1290                            profile.as_str()
1291                        );
1292                    }
1293                }
1294            }
1295        }
1296    }
1297
1298    #[test]
1299    fn minimal_rules_shorter_than_standard() {
1300        use super::super::tool_profiles::ToolProfile;
1301        let min = render(
1302            false,
1303            Wrapper::Dedicated,
1304            CompressionLevel::Off,
1305            &ToolProfile::Minimal,
1306        );
1307        let std = render(
1308            false,
1309            Wrapper::Dedicated,
1310            CompressionLevel::Off,
1311            &ToolProfile::Standard,
1312        );
1313        assert!(
1314            min.len() < std.len(),
1315            "minimal ({}) must be shorter than standard ({})",
1316            min.len(),
1317            std.len()
1318        );
1319    }
1320
1321    #[test]
1322    fn power_profile_output_identical_to_default() {
1323        use super::super::tool_profiles::ToolProfile;
1324        let power = render(
1325            false,
1326            Wrapper::Dedicated,
1327            CompressionLevel::Off,
1328            &ToolProfile::Power,
1329        );
1330        assert!(
1331            power.contains("ctx_compose"),
1332            "Power must include all tools"
1333        );
1334        assert!(
1335            power.contains("ctx_callgraph"),
1336            "Power must include all tools"
1337        );
1338        assert!(
1339            power.contains("ctx_session"),
1340            "Power must include all tools"
1341        );
1342    }
1343
1344    #[test]
1345    fn render_is_deterministic_across_profiles() {
1346        use super::super::tool_profiles::ToolProfile;
1347        for profile in [
1348            ToolProfile::Minimal,
1349            ToolProfile::Standard,
1350            ToolProfile::Power,
1351        ] {
1352            let a = render(false, Wrapper::Dedicated, CompressionLevel::Off, &profile);
1353            let b = render(false, Wrapper::Dedicated, CompressionLevel::Off, &profile);
1354            assert_eq!(
1355                a,
1356                b,
1357                "render must be deterministic for {:?}",
1358                profile.as_str()
1359            );
1360        }
1361    }
1362
1363    #[test]
1364    fn minimal_has_ctx_call_fallback() {
1365        use super::super::tool_profiles::ToolProfile;
1366        let rules = render(
1367            false,
1368            Wrapper::Dedicated,
1369            CompressionLevel::Off,
1370            &ToolProfile::Minimal,
1371        );
1372        assert!(
1373            rules.contains("ctx_call"),
1374            "minimal profile must include ctx_call gateway hint"
1375        );
1376    }
1377
1378    #[test]
1379    fn power_has_no_ctx_call_fallback() {
1380        use super::super::tool_profiles::ToolProfile;
1381        let rules = render(
1382            false,
1383            Wrapper::Dedicated,
1384            CompressionLevel::Off,
1385            &ToolProfile::Power,
1386        );
1387        assert!(
1388            !rules.contains("ctx_call(tool="),
1389            "power profile must not include ctx_call gateway hint"
1390        );
1391    }
1392}