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