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