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    use super::rules_sections as rs;
499
500    let sections: Vec<String> = match (wrapper, shadow) {
501        (Wrapper::Longform, false) => longform_non_shadow_sections(tool_profile),
502        (Wrapper::Longform | Wrapper::Dedicated | Wrapper::HookCovered, true) => {
503            full_shadow_sections(tool_profile)
504        }
505        (Wrapper::Dedicated, false) => full_non_shadow_sections(tool_profile),
506        (Wrapper::HookCovered, false) => hook_covered_non_shadow_sections(tool_profile),
507        (_, false) => compact_non_shadow_sections(tool_profile),
508        (_, true) => compact_shadow_sections(tool_profile),
509    };
510
511    // Suppress empty sections (a section builder may return "" when the
512    // profile hides all tools it would mention).
513    let mut body: String = sections
514        .into_iter()
515        .filter(|s| !s.is_empty())
516        .collect::<Vec<_>>()
517        .join("\n\n");
518    let _ = rs::intent_section; // anchor — ensures the module is linked
519
520    // Append the compression / output-style prompt for active levels. Persistent
521    // carriers (Dedicated, Shared) wrap it in the canonical COMPRESSION_BLOCK
522    // markers so coverage/dedup (rules_channel, rules_dedup) can detect and thin
523    // it; the ephemeral Bare MCP channel keeps it unmarked (#684/#548).
524    let compression = compression_text(level);
525    if !compression.is_empty() {
526        body.push('\n');
527        if matches!(wrapper, Wrapper::Bare) {
528            body.push_str(compression);
529        } else {
530            body.push_str(COMPRESSION_BLOCK_START);
531            body.push('\n');
532            body.push_str(compression);
533            body.push('\n');
534            body.push_str(COMPRESSION_BLOCK_END);
535        }
536    }
537
538    // Solution Intelligence block: inject efficiency ladder when enabled
539    {
540        let cfg = crate::core::config::Config::load();
541        if cfg.solution.enabled {
542            let ladder = cfg.solution.ladder_text();
543            if !ladder.is_empty() {
544                body.push('\n');
545                if matches!(wrapper, Wrapper::Bare) {
546                    body.push_str(ladder);
547                } else {
548                    body.push_str(SOLUTION_BLOCK_START);
549                    body.push('\n');
550                    body.push_str("SOLUTION EFFICIENCY: stop at first level that applies:\n");
551                    body.push_str("skip (YAGNI) → reuse codebase → stdlib → native platform → installed dep → one-line → minimum code.\n");
552                    body.push_str("Never skip: validation, security, error handling.\n");
553                    body.push_str(SOLUTION_BLOCK_END);
554                }
555            }
556        }
557    }
558
559    if matches!(wrapper, Wrapper::Bare) {
560        return body;
561    }
562
563    let version_line = format!("<!-- version: {RULES_VERSION} -->");
564
565    format!("{START_MARK}\n{version_line}\n\n{body}\n{END_MARK}")
566}
567
568/// Unmarked render of the hook-covered profile for ephemeral channels
569/// (the mcp.json `instructions` snapshot on hook-covered hosts, GL #1153).
570/// The `Bare` counterpart of `Wrapper::HookCovered`: same body, no markers —
571/// per-session channels are governed by carrier coverage, so markers would be
572/// noise (see [`COMPRESSION_BLOCK_START`]). Shadow collapses to the regular
573/// bare shadow profile (interception supersedes hook coverage).
574pub fn render_hook_covered_bare(
575    shadow: bool,
576    level: CompressionLevel,
577    tool_profile: &super::tool_profiles::ToolProfile,
578) -> String {
579    if shadow {
580        return render(true, Wrapper::Bare, level, tool_profile);
581    }
582    let sections = hook_covered_non_shadow_sections(tool_profile);
583    let mut body: String = sections
584        .into_iter()
585        .filter(|s| !s.is_empty())
586        .collect::<Vec<_>>()
587        .join("\n\n");
588    let compression = compression_text(level);
589    if !compression.is_empty() {
590        body.push('\n');
591        body.push_str(compression);
592    }
593    body
594}
595// Rules-file parsing and validation live in the sibling module.
596pub use super::rules_validation::RulesFile;
597
598#[cfg(test)]
599mod tests {
600    use super::*;
601
602    fn tp() -> super::super::tool_profiles::ToolProfile {
603        super::super::tool_profiles::ToolProfile::Power
604    }
605
606    // --- Constants ---
607
608    #[test]
609    fn bullets_uses_ctx_shell() {
610        assert!(BULLETS.contains("ctx_shell"));
611        assert!(!BULLETS.contains("lean-ctx -c"));
612        assert!(!BULLETS.contains("ctx_edit"));
613    }
614
615    #[test]
616    fn sections_not_empty() {
617        assert!(!BULLETS.is_empty());
618        assert!(!NEVER.is_empty());
619        assert!(!INTENT.is_empty());
620        assert!(!ANTI.is_empty());
621        assert!(!PARALLEL.is_empty());
622        assert!(!AUTO.is_empty());
623        assert!(!CEP.is_empty());
624        assert!(!LITM_END.is_empty());
625        assert!(!CRITICAL.is_empty());
626    }
627
628    #[test]
629    fn intent_contains_ctx_compose() {
630        assert!(INTENT.contains("ctx_compose"));
631    }
632
633    #[test]
634    fn anti_contains_do_not() {
635        assert!(ANTI.contains("do NOT"));
636    }
637
638    #[test]
639    fn parallel_contains_parallel() {
640        assert!(PARALLEL.contains("PARALLEL"));
641    }
642
643    // --- Agent loop + navigation paradox (#609) ---
644
645    #[test]
646    fn agent_loop_names_every_phase() {
647        for phase in ["Orient", "Find", "Read", "Locate", "Trace", "Verify"] {
648            assert!(AGENT_LOOP.contains(phase), "AGENT_LOOP must name {phase}");
649        }
650        assert!(AGENT_LOOP.contains("ctx_compose") && AGENT_LOOP.contains("ctx_callgraph"));
651    }
652
653    #[test]
654    fn nav_paradox_steers_semantic_vs_graph() {
655        assert!(
656            NAV_PARADOX.contains("ctx_search(action=semantic)"),
657            "semantic route must use folded action (#509)"
658        );
659        assert!(NAV_PARADOX.contains("ctx_callgraph"), "graph route");
660        assert!(
661            NAV_PARADOX.contains("≠"),
662            "must carry the reading≠understanding thesis"
663        );
664    }
665
666    #[test]
667    fn longform_carries_loop_and_paradox_injected_full_does_not() {
668        // v5 (#578): the verbose teaching sections live only in the on-demand
669        // LEAN-CTX.md (Longform); the injected dedicated files fold the loop
670        // phases + paradox thesis into INTENT.
671        let long = render(false, Wrapper::Longform, CompressionLevel::Off, &tp());
672        assert!(
673            long.contains("AGENT LOOP"),
674            "LONGFORM must carry AGENT_LOOP"
675        );
676        assert!(
677            long.contains("NAVIGATION PARADOX"),
678            "LONGFORM must carry NAV_PARADOX"
679        );
680        assert!(long.contains(CEP), "LONGFORM must carry CEP");
681
682        let full = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
683        assert!(
684            !full.contains("AGENT LOOP (phase -> tool):"),
685            "injected FULL must not inline the multi-line AGENT_LOOP block"
686        );
687        assert!(
688            !full.contains("NAVIGATION PARADOX: reading"),
689            "injected FULL must not inline the multi-line NAV_PARADOX block"
690        );
691        assert!(
692            full.contains('≠'),
693            "INTENT must keep the reading≠understanding thesis in FULL"
694        );
695        // #509: ctx_symbol folded into ctx_search(action=symbol)
696        for phase_tool in [
697            "ctx_compose",
698            "ctx_search(action=symbol)",
699            "ctx_search",
700            "ctx_callgraph",
701        ] {
702            assert!(
703                full.contains(phase_tool),
704                "FULL keeps the loop tools via INTENT: {phase_tool}"
705            );
706        }
707    }
708
709    #[test]
710    fn injected_profiles_stay_lean() {
711        // The whole point of v5 (#578): injected files bill every session.
712        // chars/4 ≈ tokens — the dedicated body must stay around ~470 tok and
713        // the Longform must be a strict superset.
714        let full = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
715        eprintln!(
716            "rules footprint: dedicated={} chars (~{} tok), longform={} chars, bare={} chars",
717            full.len(),
718            full.len() / 4,
719            render(false, Wrapper::Longform, CompressionLevel::Off, &tp()).len(),
720            render(false, Wrapper::Bare, CompressionLevel::Off, &tp()).len(),
721        );
722        assert!(
723            full.len() <= 2400,
724            "injected dedicated rules must stay ≤2400 chars (~600 tok), got {} chars (~{} tok)",
725            full.len(),
726            full.len() / 4
727        );
728        let long = render(false, Wrapper::Longform, CompressionLevel::Off, &tp());
729        assert!(
730            long.len() > full.len(),
731            "Longform ({}) must carry more than the injected profile ({})",
732            long.len(),
733            full.len()
734        );
735        let compact = render(false, Wrapper::Bare, CompressionLevel::Off, &tp());
736        assert!(
737            compact.len() < full.len(),
738            "COMPACT/Bare ({}) must stay below the dedicated profile ({})",
739            compact.len(),
740            full.len()
741        );
742    }
743
744    #[test]
745    fn compact_profile_has_no_multiline_teaching_sections() {
746        // COMPACT (shared + Bare) keeps the per-session channel lean: no
747        // multi-line AGENT_LOOP/NAV_PARADOX blocks; INTENT carries the thesis.
748        let out = render(false, Wrapper::Shared, CompressionLevel::Off, &tp());
749        assert!(
750            !out.contains("AGENT LOOP (phase -> tool):"),
751            "COMPACT must not inline the multi-line AGENT_LOOP block"
752        );
753        assert!(
754            !out.contains("NAVIGATION PARADOX: reading"),
755            "COMPACT must not inline the multi-line NAV_PARADOX block"
756        );
757        assert!(
758            out.contains('≠'),
759            "COMPACT keeps the reading≠understanding thesis via INTENT"
760        );
761    }
762
763    #[test]
764    fn shadow_omits_loop_and_paradox() {
765        // #963: shadow collapses to the irreducible minimum — the routing
766        // taxonomy is redundant once native calls are intercepted.
767        for wrapper in [Wrapper::Longform, Wrapper::Dedicated, Wrapper::Shared] {
768            let out = render(true, wrapper, CompressionLevel::Off, &tp());
769            assert!(!out.contains("AGENT LOOP"), "{wrapper:?} shadow drops loop");
770            assert!(
771                !out.contains("NAVIGATION PARADOX"),
772                "{wrapper:?} shadow drops paradox"
773            );
774        }
775    }
776
777    #[test]
778    fn recover_reaches_every_non_shadow_carrier() {
779        // The recovery vocabulary must reach every non-shadow carrier so agents
780        // never re-read compressed output line-by-line, and every carrier must
781        // keep the MCP-free path ("read the shown path") for orgs that ban MCP.
782        // v5 (#578): only Longform carries the verbose RECOVER; every injected
783        // profile (Dedicated FULL + Shared/Bare COMPACT) carries the terse
784        // RECOVER_COMPACT one-liner.
785        let long = render(false, Wrapper::Longform, CompressionLevel::Off, &tp());
786        assert!(
787            long.contains(RECOVER),
788            "Longform must carry the verbose RECOVER verbatim"
789        );
790        for wrapper in [Wrapper::Dedicated, Wrapper::Shared, Wrapper::Bare] {
791            let out = render(false, wrapper, CompressionLevel::Off, &tp());
792            assert!(
793                out.contains(RECOVER_COMPACT),
794                "{wrapper:?} must carry RECOVER_COMPACT verbatim"
795            );
796            assert!(
797                !out.contains(RECOVER),
798                "{wrapper:?} must not inline the verbose RECOVER block"
799            );
800        }
801        for wrapper in [
802            Wrapper::Longform,
803            Wrapper::Dedicated,
804            Wrapper::Shared,
805            Wrapper::Bare,
806        ] {
807            assert!(
808                render(false, wrapper, CompressionLevel::Off, &tp()).contains("(no MCP)"),
809                "{wrapper:?} recovery line must keep the MCP-free path"
810            );
811        }
812        for wrapper in [Wrapper::Dedicated, Wrapper::Shared] {
813            let out = render(true, wrapper, CompressionLevel::Off, &tp());
814            assert!(
815                !out.contains(RECOVER) && !out.contains(RECOVER_COMPACT),
816                "{wrapper:?} shadow drops all RECOVER guidance"
817            );
818        }
819    }
820
821    // --- render() — Dedicated ---
822
823    #[test]
824    fn dedicated_has_markers_and_version() {
825        let out = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
826        assert!(out.contains(START_MARK));
827        assert!(out.contains(&format!("<!-- version: {RULES_VERSION} -->")));
828        assert!(out.contains(END_MARK));
829        assert!(out.contains(BULLETS));
830        assert!(out.contains(NEVER));
831        assert!(out.contains("CRITICAL"));
832    }
833
834    #[test]
835    fn dedicated_shadow_is_minimal() {
836        // #963: shadow drops the whole tool-mapping AND routing playbook —
837        // interception makes them redundant. Only the exclusive-tool advert remains.
838        let out = render(true, Wrapper::Dedicated, CompressionLevel::Off, &tp());
839        assert!(out.contains(START_MARK));
840        assert!(!out.contains("MANDATORY MAPPING"), "no BULLETS in shadow");
841        assert!(!out.contains(NEVER), "no NEVER in shadow");
842        assert!(!out.contains("CRITICAL"), "no CRITICAL banner in shadow");
843        assert!(
844            !out.contains("Tool selection by intent"),
845            "routing INTENT block is redundant under interception"
846        );
847        assert!(
848            !out.contains("Anti-patterns") && !out.contains("PARALLEL tool calls"),
849            "ANTI/PARALLEL routing guidance is dropped in shadow"
850        );
851        assert!(
852            out.contains("shadow mode") && out.contains("ctx_compose"),
853            "shadow keeps the exclusive-tool advert"
854        );
855    }
856
857    #[test]
858    fn shadow_is_smaller_than_non_shadow() {
859        // The whole point of #963: the shadow body must be a strict reduction.
860        let shadow = render(true, Wrapper::Dedicated, CompressionLevel::Off, &tp());
861        let full = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
862        assert!(
863            shadow.len() < full.len(),
864            "shadow ({}) must be smaller than non-shadow ({})",
865            shadow.len(),
866            full.len()
867        );
868    }
869
870    #[test]
871    fn dedicated_litm_structure() {
872        let out = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
873        let lines: Vec<&str> = out.lines().collect();
874        let first_5 = lines[..5.min(lines.len())].join("\n");
875        assert!(
876            first_5.contains("CRITICAL") || first_5.contains("MUST"),
877            "LITM: MUST/CRITICAL instruction near start"
878        );
879        // LITM_END or NEVER should appear in the final content lines (before END_MARK).
880        let tail = lines[lines.len().saturating_sub(8)..].join("\n");
881        assert!(
882            tail.contains("PREFERENCE") || tail.contains("NEVER"),
883            "LITM: reinforcement near end, tail={tail:?}"
884        );
885    }
886
887    #[test]
888    fn dedicated_carries_weak_model_invoke_nudge() {
889        // #1067/GH #593: the "actually CALL ctx_*" nudge must ride every dedicated
890        // rule file (Windsurf, Cursor, Claude, …) in non-shadow mode, and must be
891        // absent where it is dead weight: shadow mode (call-layer routing) and the
892        // Bare/instructions channel (separately capped).
893        let dedicated = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
894        assert!(
895            dedicated.contains(MUST_INVOKE),
896            "dedicated non-shadow rules must carry the MUST_INVOKE nudge"
897        );
898        assert!(
899            !render(true, Wrapper::Dedicated, CompressionLevel::Off, &tp()).contains(MUST_INVOKE),
900            "shadow mode must not carry the nudge (routing is enforced at the call layer)"
901        );
902        assert!(
903            !render(false, Wrapper::Bare, CompressionLevel::Off, &tp()).contains(MUST_INVOKE),
904            "Bare/instructions channel is capped separately and carries no copy"
905        );
906    }
907
908    // --- render() — Shared ---
909
910    #[test]
911    fn shared_has_markers_and_header() {
912        let out = render(false, Wrapper::Shared, CompressionLevel::Off, &tp());
913        assert!(out.contains(START_MARK));
914        assert!(out.contains(END_MARK));
915        assert!(out.contains("MANDATORY MAPPING"));
916        assert!(out.contains(BULLETS));
917    }
918
919    #[test]
920    fn shared_shadow_omits_mapping() {
921        let out = render(true, Wrapper::Shared, CompressionLevel::Off, &tp());
922        assert!(out.contains(START_MARK));
923        assert!(
924            !out.contains("MANDATORY MAPPING"),
925            "shadow must not have header"
926        );
927        assert!(
928            !out.contains("MANDATORY MAPPING"),
929            "shadow must not contain BULLETS"
930        );
931    }
932
933    // --- render() — Bare ---
934
935    #[test]
936    fn bare_has_no_markers() {
937        let out = render(false, Wrapper::Bare, CompressionLevel::Off, &tp());
938        assert!(!out.contains(START_MARK), "Bare must not have START_MARK");
939        assert!(!out.contains(END_MARK), "Bare must not have END_MARK");
940        assert!(!out.contains("<!-- version:"), "Bare must not have version");
941        assert!(out.contains(BULLETS));
942        assert!(out.contains(NEVER));
943    }
944
945    #[test]
946    fn bare_shadow_only_read_modes() {
947        let out = render(true, Wrapper::Bare, CompressionLevel::Off, &tp());
948        assert!(!out.contains(NEVER), "shadow Bare must not have NEVER");
949        assert!(
950            !out.contains("MANDATORY MAPPING"),
951            "shadow Bare must not have BULLETS"
952        );
953    }
954
955    // --- Compression level tests ---
956
957    #[test]
958    fn render_includes_lite_prompt() {
959        let out = render(false, Wrapper::Bare, CompressionLevel::Lite, &tp());
960        assert!(out.contains("OUTPUT STYLE: concise"));
961        assert!(out.contains("Bullet points"));
962    }
963
964    #[test]
965    fn render_includes_standard_prompt() {
966        let out = render(false, Wrapper::Bare, CompressionLevel::Standard, &tp());
967        assert!(out.contains("OUTPUT STYLE: dense"));
968        assert!(out.contains("atomic fact"));
969    }
970
971    #[test]
972    fn render_includes_max_prompt() {
973        let out = render(false, Wrapper::Bare, CompressionLevel::Max, &tp());
974        assert!(out.contains("OUTPUT STYLE: expert-terse"));
975        assert!(out.contains("Telegraph"));
976    }
977
978    #[test]
979    fn render_off_excludes_compression() {
980        let out = render(false, Wrapper::Bare, CompressionLevel::Off, &tp());
981        assert!(!out.contains("OUTPUT STYLE:"));
982    }
983
984    #[test]
985    fn compression_text_matches_level() {
986        assert!(compression_text(CompressionLevel::Off).is_empty());
987        assert!(compression_text(CompressionLevel::Lite).contains("Bullet"));
988        assert!(compression_text(CompressionLevel::Standard).contains("fn, cfg"));
989        assert!(compression_text(CompressionLevel::Max).contains("Telegraph"));
990    }
991
992    // --- Compression marker model (#548 B2) ---
993
994    #[test]
995    fn carrier_wrappers_wrap_compression_in_markers() {
996        // Persistent carriers must delimit the compression payload so coverage
997        // and dedup can detect/thin it (#684/#548).
998        for wrapper in [Wrapper::Longform, Wrapper::Dedicated, Wrapper::Shared] {
999            let out = render(false, wrapper, CompressionLevel::Standard, &tp());
1000            assert!(
1001                out.contains(COMPRESSION_BLOCK_START) && out.contains(COMPRESSION_BLOCK_END),
1002                "{wrapper:?} must wrap compression in COMPRESSION_BLOCK markers"
1003            );
1004            // The marked region must actually contain the prompt body.
1005            let start = out.find(COMPRESSION_BLOCK_START).unwrap();
1006            let end = out.find(COMPRESSION_BLOCK_END).unwrap();
1007            assert!(start < end, "{wrapper:?}: start marker precedes end marker");
1008            assert!(out[start..end].contains("OUTPUT STYLE: dense"));
1009        }
1010    }
1011
1012    #[test]
1013    fn bare_wrapper_emits_compression_without_markers() {
1014        // The ephemeral MCP channel keeps the payload unmarked — its inclusion is
1015        // governed by carrier coverage, so per-session markers would be noise.
1016        let out = render(false, Wrapper::Bare, CompressionLevel::Standard, &tp());
1017        assert!(out.contains("OUTPUT STYLE: dense"));
1018        assert!(!out.contains(COMPRESSION_BLOCK_START));
1019        assert!(!out.contains(COMPRESSION_BLOCK_END));
1020    }
1021
1022    #[test]
1023    fn compression_off_emits_no_markers_in_any_wrapper() {
1024        for wrapper in [
1025            Wrapper::Longform,
1026            Wrapper::Dedicated,
1027            Wrapper::Shared,
1028            Wrapper::Bare,
1029        ] {
1030            let out = render(false, wrapper, CompressionLevel::Off, &tp());
1031            assert!(
1032                !out.contains(COMPRESSION_BLOCK_START) && !out.contains(COMPRESSION_BLOCK_END),
1033                "{wrapper:?}: Off must emit no compression markers"
1034            );
1035        }
1036    }
1037
1038    #[test]
1039    fn rendered_carrier_block_is_seen_as_carrying_compression() {
1040        // The detection helper that coverage/dedup rely on must agree with the
1041        // writer's output (the bug this slice fixes: it previously never did).
1042        let dedicated = render(false, Wrapper::Dedicated, CompressionLevel::Lite, &tp());
1043        assert!(crate::core::rules_channel::carries_full_rules(&dedicated));
1044        assert!(dedicated.contains(COMPRESSION_BLOCK_START));
1045    }
1046
1047    // --- Wrapper round-trip ---
1048
1049    #[test]
1050    fn all_wrappers_produce_output() {
1051        for shadow in [false, true] {
1052            for wrapper in [
1053                Wrapper::Longform,
1054                Wrapper::Dedicated,
1055                Wrapper::Shared,
1056                Wrapper::Bare,
1057            ] {
1058                let out = render(shadow, wrapper, CompressionLevel::Off, &tp());
1059                assert!(!out.is_empty(), "{wrapper:?} shadow={shadow} is empty");
1060            }
1061        }
1062    }
1063
1064    // --- RulesFile ---
1065
1066    #[test]
1067    fn rules_file_parses_version() {
1068        let content = format!(
1069            "stuff before\n{START_MARK}\n<!-- version: {RULES_VERSION} -->\n\nbody\n{END_MARK}\nstuff after"
1070        );
1071        let f = RulesFile::parse(&content);
1072        assert!(f.has_content());
1073        assert_eq!(f.version(), RULES_VERSION);
1074        assert!(f.is_current());
1075        assert!(f.prefix().contains("stuff before"));
1076        assert!(f.suffix().contains("stuff after"));
1077    }
1078
1079    #[test]
1080    fn rules_file_no_version_defaults_to_zero() {
1081        let content = format!("{START_MARK}\nbody\n{END_MARK}");
1082        let f = RulesFile::parse(&content);
1083        assert!(f.has_content());
1084        assert_eq!(f.version(), 0);
1085        assert!(!f.is_current());
1086    }
1087
1088    #[test]
1089    fn rules_file_no_start_marker_no_content() {
1090        let f = RulesFile::parse("just user stuff");
1091        assert!(!f.has_content());
1092        assert_eq!(f.version(), 0);
1093    }
1094
1095    #[test]
1096    fn block_matches_render_true_for_fresh_render() {
1097        let fresh = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
1098        let content = format!("user before\n{fresh}\nuser after");
1099        let f = RulesFile::parse(&content);
1100        assert!(f.is_current(), "fresh render carries the current version");
1101        assert!(
1102            f.block_matches_render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp()),
1103            "an unchanged block must compare equal to a fresh render"
1104        );
1105    }
1106
1107    #[test]
1108    fn block_matches_render_false_on_compression_change() {
1109        // Body rendered at Off, then asked whether it matches a Max render:
1110        // the version is identical but the compression payload differs (#548).
1111        let content = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
1112        let f = RulesFile::parse(&content);
1113        assert!(f.is_current());
1114        assert!(
1115            !f.block_matches_render(false, Wrapper::Dedicated, CompressionLevel::Max, &tp()),
1116            "a compression-level change must be detected as drift"
1117        );
1118    }
1119
1120    #[test]
1121    fn block_matches_render_false_on_shadow_change() {
1122        let content = render(false, Wrapper::Dedicated, CompressionLevel::Lite, &tp());
1123        let f = RulesFile::parse(&content);
1124        assert!(
1125            !f.block_matches_render(true, Wrapper::Dedicated, CompressionLevel::Lite, &tp()),
1126            "a shadow-mode toggle must be detected as drift"
1127        );
1128    }
1129
1130    #[test]
1131    fn block_matches_render_false_without_block() {
1132        let f = RulesFile::parse("plain user content, no markers");
1133        assert!(!f.block_matches_render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp()));
1134    }
1135
1136    #[test]
1137    fn rules_file_merged_replaces_section() {
1138        let content =
1139            format!("before\n{START_MARK}\n<!-- version: 1 -->\n\nold\n{END_MARK}\nafter");
1140        let f = RulesFile::parse(&content);
1141        let merged = f.merged(false, Wrapper::Shared, CompressionLevel::Off, &tp());
1142        assert!(merged.contains("before"), "prefix preserved");
1143        assert!(merged.contains("after"), "suffix preserved");
1144        assert!(!merged.contains("old"), "old content replaced");
1145        assert!(merged.contains(&format!("<!-- version: {RULES_VERSION} -->")));
1146    }
1147
1148    #[test]
1149    fn rules_file_merged_appends_when_no_section() {
1150        let content = "user content";
1151        let f = RulesFile::parse(content);
1152        assert!(!f.has_content());
1153        let merged = f.merged(false, Wrapper::Bare, CompressionLevel::Off, &tp());
1154        assert!(merged.contains("user content"));
1155        assert!(merged.contains(BULLETS));
1156    }
1157
1158    #[test]
1159    fn rules_file_without_section_strips_content() {
1160        let content =
1161            format!("header\n{START_MARK}\n<!-- version: 1 -->\n\nbody\n{END_MARK}\nfooter");
1162        let f = RulesFile::parse(&content);
1163        let stripped = f.without_section();
1164        assert!(stripped.contains("header"));
1165        assert!(stripped.contains("footer"));
1166        assert!(!stripped.contains("body"));
1167        assert!(!stripped.contains(START_MARK));
1168    }
1169
1170    #[test]
1171    fn rules_file_without_section_noop_when_no_content() {
1172        let content = "just user text";
1173        let f = RulesFile::parse(content);
1174        assert_eq!(f.without_section(), content);
1175    }
1176
1177    #[test]
1178    fn bullets_lead_with_four_core_redirects() {
1179        // Most-used routes (Read/Grep/Shell/Glob) lead; ls->ctx_tree trails.
1180        let read = BULLETS.find("ctx_read").expect("ctx_read mapping present");
1181        let search = BULLETS
1182            .find("ctx_search")
1183            .expect("ctx_search mapping present");
1184        let shell = BULLETS
1185            .find("ctx_shell")
1186            .expect("ctx_shell mapping present");
1187        let glob = BULLETS.find("ctx_glob").expect("ctx_glob mapping present");
1188        let tree = BULLETS.find("ctx_tree").expect("ctx_tree mapping present");
1189        assert!(
1190            read < search && search < shell && shell < glob && glob < tree,
1191            "core redirects (read<search<shell<glob) must precede ctx_tree"
1192        );
1193    }
1194
1195    #[test]
1196    fn never_carries_self_correction() {
1197        // Self-correction reinforces the redirect harder than a bare prohibition.
1198        assert!(
1199            NEVER.contains("SELF-CORRECT"),
1200            "NEVER must teach self-correction"
1201        );
1202        assert!(
1203            NEVER.contains("call"),
1204            "NEVER must spell out the corrective action"
1205        );
1206    }
1207
1208    #[test]
1209    fn critical_names_ctx_family() {
1210        assert!(
1211            CRITICAL.contains("ctx_*"),
1212            "CRITICAL must name the ctx_* family"
1213        );
1214    }
1215
1216    // --- HookCovered profile (GL #1153) ---
1217
1218    #[test]
1219    fn hook_covered_carries_strict_mapping() {
1220        // v8: HookCovered is strict — always prefer ctx_* over native tools.
1221        // The MANDATORY MAPPING replaces the old "no native equivalent" list.
1222        let out = render(false, Wrapper::HookCovered, CompressionLevel::Off, &tp());
1223        assert!(
1224            !out.contains(NEVER),
1225            "HookCovered uses its own strict header, not the NEVER constant"
1226        );
1227        assert!(
1228            out.contains(HOOK_COVERED_HEADER),
1229            "must carry the strict preference header"
1230        );
1231        assert!(
1232            out.contains("MANDATORY MAPPING")
1233                && out.contains("ctx_read")
1234                && out.contains("ctx_search"),
1235            "must carry the full mandatory mapping"
1236        );
1237        assert!(
1238            out.contains("ctx_compose") && out.contains("action=symbol|semantic"),
1239            "must advertise the search capabilities"
1240        );
1241    }
1242
1243    #[test]
1244    fn hook_covered_keeps_markers_version_and_recovery() {
1245        // Coverage detection (rules_channel::carries_full_rules /
1246        // client_autoloads_rules) and the injector's drift check both key on
1247        // the canonical markers — HookCovered must stay a first-class carrier.
1248        let out = render(false, Wrapper::HookCovered, CompressionLevel::Off, &tp());
1249        assert!(out.contains(START_MARK) && out.contains(END_MARK));
1250        assert!(out.contains(&format!("<!-- version: {RULES_VERSION} -->")));
1251        assert!(out.contains(RECOVER_COMPACT), "recovery line must survive");
1252        assert!(out.contains("(no MCP)"), "MCP-free recovery path stays");
1253    }
1254
1255    #[test]
1256    fn hook_covered_is_leaner_than_full() {
1257        let covered = render(false, Wrapper::HookCovered, CompressionLevel::Off, &tp());
1258        let full = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
1259        assert!(
1260            covered.len() < full.len(),
1261            "HookCovered ({}) must be a strict reduction of FULL ({})",
1262            covered.len(),
1263            full.len()
1264        );
1265    }
1266
1267    #[test]
1268    fn hook_covered_shadow_collapses_to_minimal() {
1269        // Interception supersedes hook coverage — same minimal profile as
1270        // Dedicated shadow.
1271        let covered_shadow = render(true, Wrapper::HookCovered, CompressionLevel::Off, &tp());
1272        let dedicated_shadow = render(true, Wrapper::Dedicated, CompressionLevel::Off, &tp());
1273        assert_eq!(covered_shadow, dedicated_shadow);
1274    }
1275
1276    #[test]
1277    fn hook_covered_wraps_compression_in_markers() {
1278        let out = render(
1279            false,
1280            Wrapper::HookCovered,
1281            CompressionLevel::Standard,
1282            &tp(),
1283        );
1284        assert!(out.contains(COMPRESSION_BLOCK_START) && out.contains(COMPRESSION_BLOCK_END));
1285        assert!(out.contains("OUTPUT STYLE: dense"));
1286    }
1287
1288    // --- Profile-aware rules (#756) ---
1289
1290    #[test]
1291    fn rules_only_mention_enabled_tools() {
1292        use super::super::rules_sections;
1293        use super::super::tool_profiles::ToolProfile;
1294        let exclusive_tools = ["ctx_compose", "ctx_callgraph", "ctx_patch"];
1295        for profile in [ToolProfile::Minimal, ToolProfile::Standard] {
1296            let mut sections = vec![
1297                rules_sections::intent_section(&profile),
1298                rules_sections::hook_covered_tools_section(&profile),
1299                rules_sections::shadow_minimal_section(&profile),
1300                rules_sections::anti_section(&profile),
1301                rules_sections::litm_end_section(&profile),
1302            ];
1303            if let Some(fb) = rules_sections::ctx_call_fallback(&profile) {
1304                sections.push(fb);
1305            }
1306            for tool in &exclusive_tools {
1307                if !profile.is_tool_enabled(tool) {
1308                    for section in &sections {
1309                        assert!(
1310                            !section.contains(tool),
1311                            "profile {:?} dynamic section must not mention disabled tool {tool}",
1312                            profile.as_str()
1313                        );
1314                    }
1315                }
1316            }
1317        }
1318    }
1319
1320    #[test]
1321    fn minimal_rules_shorter_than_standard() {
1322        use super::super::tool_profiles::ToolProfile;
1323        let min = render(
1324            false,
1325            Wrapper::Dedicated,
1326            CompressionLevel::Off,
1327            &ToolProfile::Minimal,
1328        );
1329        let std = render(
1330            false,
1331            Wrapper::Dedicated,
1332            CompressionLevel::Off,
1333            &ToolProfile::Standard,
1334        );
1335        assert!(
1336            min.len() < std.len(),
1337            "minimal ({}) must be shorter than standard ({})",
1338            min.len(),
1339            std.len()
1340        );
1341    }
1342
1343    #[test]
1344    fn power_profile_output_identical_to_default() {
1345        use super::super::tool_profiles::ToolProfile;
1346        let power = render(
1347            false,
1348            Wrapper::Dedicated,
1349            CompressionLevel::Off,
1350            &ToolProfile::Power,
1351        );
1352        assert!(
1353            power.contains("ctx_compose"),
1354            "Power must include all tools"
1355        );
1356        assert!(
1357            power.contains("ctx_callgraph"),
1358            "Power must include all tools"
1359        );
1360        assert!(
1361            power.contains("ctx_session"),
1362            "Power must include all tools"
1363        );
1364    }
1365
1366    #[test]
1367    fn render_is_deterministic_across_profiles() {
1368        use super::super::tool_profiles::ToolProfile;
1369        for profile in [
1370            ToolProfile::Minimal,
1371            ToolProfile::Standard,
1372            ToolProfile::Power,
1373        ] {
1374            let a = render(false, Wrapper::Dedicated, CompressionLevel::Off, &profile);
1375            let b = render(false, Wrapper::Dedicated, CompressionLevel::Off, &profile);
1376            assert_eq!(
1377                a,
1378                b,
1379                "render must be deterministic for {:?}",
1380                profile.as_str()
1381            );
1382        }
1383    }
1384
1385    #[test]
1386    fn minimal_has_ctx_call_fallback() {
1387        use super::super::tool_profiles::ToolProfile;
1388        let rules = render(
1389            false,
1390            Wrapper::Dedicated,
1391            CompressionLevel::Off,
1392            &ToolProfile::Minimal,
1393        );
1394        assert!(
1395            rules.contains("ctx_call"),
1396            "minimal profile must include ctx_call gateway hint"
1397        );
1398    }
1399
1400    #[test]
1401    fn power_has_no_ctx_call_fallback() {
1402        use super::super::tool_profiles::ToolProfile;
1403        let rules = render(
1404            false,
1405            Wrapper::Dedicated,
1406            CompressionLevel::Off,
1407            &ToolProfile::Power,
1408        );
1409        assert!(
1410            !rules.contains("ctx_call(tool="),
1411            "power profile must not include ctx_call gateway hint"
1412        );
1413    }
1414}