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