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