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. Two profiles (FULL,
4//! COMPACT) define which sections compose each output format. Three wrappers
5//! (Dedicated, Shared, Bare) select the profile and wrapping style. One
6//! `render()` function assembles everything, including the compression-level
7//! output-style prompt (Lite / Standard / Max).
8//!
9//! ***Every*** template, injected rule file, AGENTS.md block, and MCP
10//! instructions field MUST derive its content from this module.
11
12use crate::core::config::CompressionLevel;
13
14/// Stable HTML-comment anchor that marks the start of any lean-ctx rule
15/// section.  Never changes — used for find/replace in shared files and for
16/// ownership detection in dedicated files.  The version number follows on the
17/// next line (see `render`).
18pub const START_MARK: &str = "<!-- lean-ctx-rules -->";
19
20/// Prefix shared by every lean-ctx rules marker including legacy versioned
21/// formats (`<!-- lean-ctx-rules-v9 -->`). Use for substring detection when
22/// the exact constant would miss older installs.
23pub const RULES_MARKER_PREFIX: &str = "<!-- lean-ctx-rules";
24
25/// Start marker for lightweight AGENTS.md/CODEBUDDY.md/CLAUDE.md pointer
26/// blocks. These are deliberately separate from `START_MARK` / `<!-- lean-ctx-rules -->`
27/// because the pointer-only vs full-rules distinction drives duplicate detection
28/// in `doctor overhead` — a pointer-only file (`is_pointer_only`) must not be
29/// counted as a second source for its client.
30pub const AGENTS_BLOCK_START: &str = "<!-- lean-ctx -->";
31
32/// End marker for AGENTS.md/CODEBUDDY.md/CLAUDE.md pointer blocks.
33pub const AGENTS_BLOCK_END: &str = "<!-- /lean-ctx -->";
34
35/// Closing marker that ends a lean-ctx rule section.
36pub const END_MARK: &str = "<!-- /lean-ctx-rules -->";
37
38/// Markers of the heavy compression / output-style block — the per-turn payload
39/// that drives cross-channel duplication (#684/#548).
40///
41/// `render()` wraps the compression prompt in these markers for **persistent
42/// carriers** (the `Dedicated` and `Shared` wrappers, i.e. every injected rule
43/// file). This is the single carrier/marker model: coverage and dedup
44/// (`core::rules_channel`, `cli::rules_dedup`) detect and thin the payload by
45/// these markers, so the writer and the readers can never disagree again. The
46/// ephemeral `Bare` MCP-instructions channel deliberately omits the markers —
47/// its inclusion is *governed* by carrier coverage (`client_autoloads_compression`),
48/// so a per-session marker would be pure noise.
49pub const COMPRESSION_BLOCK_START: &str = "<!-- lean-ctx-compression -->";
50
51/// Closing marker of the compression / output-style block (see
52/// [`COMPRESSION_BLOCK_START`]).
53pub const COMPRESSION_BLOCK_END: &str = "<!-- /lean-ctx-compression -->";
54
55/// Current rules version (monotonically increasing integer).  Embedded as
56/// `<!-- version: {RULES_VERSION} -->` right after `START_MARK` so the
57/// injection layer can parse it and decide whether a file is up-to-date.
58pub const RULES_VERSION: usize = 1;
59
60/// Banner placed at the top of dedicated rule files (non-shadow only).
61pub const CRITICAL: &str = "CRITICAL: ALWAYS use lean-ctx tools instead of native equivalents. \
62     This is NOT optional.";
63
64/// Compact bullet-list mapping (for both dedicated and shared contexts).
65pub const BULLETS: &str = "\
66MANDATORY MAPPING:\n\
67• Read/cat -> ctx_read(path, mode)\n\
68• Glob/find -> ctx_glob(pattern)\n\
69• Shell/bash -> ctx_shell(command)\n\
70• Grep -> ctx_search(pattern, path)\n\
71• ls/find -> ctx_tree(path, depth)";
72
73/// One-line admonition reinforcing the tool preference.  Always right after
74/// `BULLETS` in both profiles.
75pub const NEVER: &str =
76    "NEVER use native Read/Grep/Shell/Glob when ctx_* equivalents are available.";
77
78/// Intent-to-tool playbook — maps common agent questions to the right tool.
79pub const INTENT: &str = "\
80Tool selection by intent:\n\
81• Understand code / find answers / before editing -> ctx_compose (call FIRST)\n\
82• Read a file -> ctx_read(path, mode=signatures|map|full)\n\
83• Find a symbol by name (exact) -> ctx_symbol\n\
84• Search code by pattern (fuzzy) -> ctx_search\n\
85• Search by meaning (concepts) -> ctx_semantic_search\n\
86• Find files by pattern (glob) -> ctx_glob\n\
87• Project structure -> ctx_tree\n\
88• Who calls this / call graph -> ctx_callgraph\n\
89• Session state / memory -> ctx_session / ctx_knowledge";
90
91/// Anti-patterns that waste tokens and round-trips.
92pub const ANTI: &str = "\
93Anti-patterns — do NOT:\n\
94• Chain ctx_search -> ctx_read -> ctx_symbol — one ctx_compose replaces all three\n\
95• Grep for symbol definitions — ctx_symbol is faster + more precise\n\
96• Use ctx_read(mode=full) for orientation — use mode=signatures\n\
97• Use ctx_callgraph or ctx_graph for const/static/variable references — they track\n\
98  function call edges and file-level deps only. Use grep or ctx_compose instead";
99
100/// Encourages parallel tool calls to reduce round-trips.
101pub const PARALLEL: &str = "\
102PARALLEL tool calls: fire independent calls in the SAME turn — don't sequence them.\n\
103One turn with 5 parallel ctx_read calls completes faster than 5 sequential turns.\n\
104ctx_compose bundles multiple lookups into one call; for anything it doesn't\n\
105cover, batch independent reads/searches together.";
106
107/// One-line automation reminder.
108pub const AUTO: &str = "Auto: preload/dedup/compress run in background. \
109    ctx_session=memory, ctx_knowledge=facts, ctx_semantic_search=meaning search, \
110    ctx_shell raw=true=uncompressed. Details: LEAN-CTX.md";
111
112/// Context Engineering Protocol version reference.
113pub const CEP: &str = "CEP v1: 1.ACT FIRST 2.DELTA ONLY (Fn refs) 3.STRUCTURED (+/-/~) \
114     4.ONE LINE PER ACTION 5.QUALITY ANCHOR";
115
116/// Output style rule.
117pub const INTELLIGENCE: &str =
118    "OUTPUT: never echo tool output, no narration comments, show only changed code.";
119
120/// LITM end-of-instructions preference line.
121pub const LITM_END: &str = "TOOL PREFERENCE (END): ctx_compose>chain ctx_read>Read ctx_shell>Shell \
122     ctx_search>Grep ctx_glob>Glob ctx_tree>ls | Edit/Write/Delete=native";
123
124// ── Output-style compression prompts ───────────────────────────
125
126/// Lite compression — concise, bullet-point output.
127pub const LITE_PROMPT: &str = "\
128OUTPUT STYLE: concise
129- Bullet points over paragraphs
130- Skip filler words and hedging (\"I think\", \"probably\", \"it seems\")
131- 1-sentence explanations max, then code/action
132- No repeating what the user said";
133
134/// Standard compression — dense, atomic fact lines, abbreviations.
135pub const STANDARD_PROMPT: &str = "\
136OUTPUT STYLE: dense
137- Each statement = one atomic fact line
138- Use abbreviations: fn, cfg, impl, deps, req, res, ctx, err, ret
139- Diff lines only (+/-/~), never repeat unchanged code
140- Symbols: → (causes), + (adds), − (removes), ~ (modifies), ∴ (therefore)
141- No narration, no filler, no hedging
142- BUDGET: ≤200 tokens per response unless code block required";
143
144/// Max compression — expert-terse, telegraph format, symbolic vocabulary.
145pub const MAX_PROMPT: &str = "\
146OUTPUT STYLE: expert-terse
147- Telegraph format: subject-verb-object, drop articles/prepositions
148- Symbolic vocabulary: → cause, ∵ because, ∴ therefore, ⊕ add, ⊖ remove, Δ change, ≈ similar, ≠ different, ∈ in/member, ∅ empty/none, ✓ ok, ✗ fail
149- Code blocks: untouched (never compress code syntax)
150- Each line: max 80 chars
151- Zero narration, zero filler
152- BUDGET: ≤100 tokens per non-code response";
153
154/// Return the compression prompt text for a given level (empty string for Off).
155pub fn compression_text(level: CompressionLevel) -> &'static str {
156    match level {
157        CompressionLevel::Off => "",
158        CompressionLevel::Lite => LITE_PROMPT,
159        CompressionLevel::Standard => STANDARD_PROMPT,
160        CompressionLevel::Max => MAX_PROMPT,
161    }
162}
163
164const FULL_NON_SHADOW: &[&str] = &[
165    CRITICAL,
166    BULLETS,
167    NEVER,
168    INTENT,
169    ANTI,
170    PARALLEL,
171    AUTO,
172    CEP,
173    INTELLIGENCE,
174    LITM_END,
175];
176
177const FULL_SHADOW: &[&str] = &[INTENT, ANTI, PARALLEL, AUTO, CEP, INTELLIGENCE, LITM_END];
178
179const COMPACT_NON_SHADOW: &[&str] = &[CRITICAL, BULLETS, NEVER, INTENT, ANTI, PARALLEL];
180
181const COMPACT_SHADOW: &[&str] = &[INTENT, ANTI, PARALLEL];
182
183/// Selects the profile (FULL vs COMPACT) and the wrapping style (markers,
184/// headers, footers) for `render()`.
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub enum Wrapper {
187    /// **Dedicated rule file.**  FULL profile.  Wrapped with `START_MARK`,
188    /// `<!-- version: N -->`, and `END_MARK`.  Non-shadow includes the
189    /// `CRITICAL` banner before the body.  The whole file is lean-ctx–owned;
190    /// the injection layer detects staleness by parsing the version comment.
191    Dedicated,
192
193    /// **Shared file section** (appended to AGENTS.md, GEMINI.md, etc.).
194    /// COMPACT profile.  Same marker wrapping for find/replace within a
195    /// larger shared file.  Non-shadow includes `## Tool Mapping` header.
196    Shared,
197
198    /// **MCP session instructions.**  COMPACT profile.  No markers or
199    /// headers — bare content used inline in per-session MCP instructions.
200    Bare,
201}
202
203/// Render lean-ctx rules for a given wrapper, shadow mode, and compression level.
204///
205/// * `shadow` — when true, tool-mapping sections (BULLETS, NEVER,
206///   CRITICAL banner, "## Tool Mapping" header) are omitted.
207/// * `wrapper` — selects the profile (FULL / COMPACT) and wrapping style.
208/// * `level` — selects the output-style compression prompt (Lite / Standard /
209///   Max) which is appended to the body. `Off` omits it.
210pub fn render(shadow: bool, wrapper: Wrapper, level: CompressionLevel) -> String {
211    let profile = match (wrapper, shadow) {
212        (Wrapper::Dedicated, false) => FULL_NON_SHADOW,
213        (Wrapper::Dedicated, true) => FULL_SHADOW,
214        (_, false) => COMPACT_NON_SHADOW,
215        (_, true) => COMPACT_SHADOW,
216    };
217
218    let mut body = profile.join("\n\n");
219
220    // Append the compression / output-style prompt for active levels. Persistent
221    // carriers (Dedicated, Shared) wrap it in the canonical COMPRESSION_BLOCK
222    // markers so coverage/dedup (rules_channel, rules_dedup) can detect and thin
223    // it; the ephemeral Bare MCP channel keeps it unmarked (#684/#548).
224    let compression = compression_text(level);
225    if !compression.is_empty() {
226        body.push('\n');
227        if matches!(wrapper, Wrapper::Bare) {
228            body.push_str(compression);
229        } else {
230            body.push_str(COMPRESSION_BLOCK_START);
231            body.push('\n');
232            body.push_str(compression);
233            body.push('\n');
234            body.push_str(COMPRESSION_BLOCK_END);
235        }
236    }
237
238    if matches!(wrapper, Wrapper::Bare) {
239        return body;
240    }
241
242    let version_line = format!("<!-- version: {RULES_VERSION} -->");
243
244    format!("{START_MARK}\n{version_line}\n\n{body}\n{END_MARK}")
245}
246// ============================================================
247// RULES FILE — centralized interface for reading rule files
248// ============================================================
249
250/// A parsed lean-ctx rules section from a file on disk.
251///
252/// Handles version detection, content boundary discovery, and prefix/suffix
253/// extraction.  This is the **only** place that parses `START_MARK` / version
254/// comments — every consumer (injection, drift detection, status reporting)
255/// goes through this struct.
256#[derive(Debug)]
257pub struct RulesFile<'a> {
258    content: &'a str,
259    /// Byte offset of `START_MARK` (or the first old-format marker found).
260    start: Option<usize>,
261    /// Byte offset of `END_MARK`.
262    end: Option<usize>,
263    /// Parsed version number (0 if no `<!-- version: N -->` comment found).
264    version: usize,
265}
266
267/// Parse the version number from the first `<!-- version: N -->` comment
268/// found at or after `search_start`.
269fn parse_version_number(s: &str) -> Option<usize> {
270    let prefix = "<!-- version: ";
271    let vs = s.find(prefix)?;
272    let num_start = vs + prefix.len();
273    let end = s[num_start..].find(" -->")?;
274    s[num_start..num_start + end].parse().ok()
275}
276
277impl<'a> RulesFile<'a> {
278    /// Parse `content`, scanning for `START_MARK` and version comment.
279    ///
280    /// * `START_MARK` not found → `has_content() = false`, version = 0.
281    /// * `START_MARK` found but no version → `has_content() = true`, version = 0
282    ///   (assume older than current → needs update).
283    pub fn parse(content: &'a str) -> Self {
284        let start = content.find(START_MARK);
285        let version = start
286            .and_then(|s| parse_version_number(&content[s + START_MARK.len()..]))
287            .unwrap_or(0);
288        let end = content.find(END_MARK);
289        RulesFile {
290            content,
291            start,
292            end,
293            version,
294        }
295    }
296
297    /// Whether the file carries any lean-ctx rules content.
298    pub fn has_content(&self) -> bool {
299        self.start.is_some()
300    }
301
302    /// The detected version (0 if no version marker — treat as older than
303    /// `RULES_VERSION`).
304    pub fn version(&self) -> usize {
305        self.version
306    }
307
308    /// Whether the file's version is at least `RULES_VERSION`.
309    pub fn is_current(&self) -> bool {
310        self.version >= RULES_VERSION
311    }
312
313    /// Content before the first `START_MARK` (user content / frontmatter).
314    /// Returns an empty string if no start marker was found.
315    pub fn prefix(&self) -> &'a str {
316        self.start.map_or("", |s| self.content[..s].trim())
317    }
318
319    /// Content after the last `END_MARK` (user content after the lean-ctx
320    /// block).  Returns an empty string if no end marker was found.
321    pub fn suffix(&self) -> &'a str {
322        self.end
323            .map_or("", |e| self.content[e + END_MARK.len()..].trim())
324    }
325
326    /// The lean-ctx block on disk, from `START_MARK` through `END_MARK`
327    /// (inclusive), if both markers are present.
328    fn block(&self) -> Option<&'a str> {
329        match (self.start, self.end) {
330            (Some(s), Some(e)) if e >= s => Some(&self.content[s..e + END_MARK.len()]),
331            _ => None,
332        }
333    }
334
335    /// Whether the on-disk block is already byte-identical (ignoring surrounding
336    /// whitespace) to a fresh [`render`] for these parameters.
337    ///
338    /// [`is_current`](Self::is_current) only compares the embedded
339    /// `<!-- version: N -->` against [`RULES_VERSION`], so a change that keeps
340    /// the version but alters the rendered body — toggling `shadow_mode`,
341    /// switching `compression_level`, or editing a canonical section without a
342    /// version bump — would otherwise be skipped by the injector. Callers pair
343    /// this with `is_current()` to detect that content/compression drift (#548).
344    pub fn block_matches_render(
345        &self,
346        shadow: bool,
347        wrapper: Wrapper,
348        level: CompressionLevel,
349    ) -> bool {
350        match self.block() {
351            Some(block) => block.trim() == render(shadow, wrapper, level).trim(),
352            None => false,
353        }
354    }
355
356    /// Merge freshly-rendered rules into this file.
357    ///
358    /// * If a lean-ctx section exists → replaces content between `START_MARK`
359    ///   and `END_MARK`, preserving user content before/after.
360    /// * If no section exists → appends fresh content at the end.
361    pub fn merged(&self, shadow: bool, wrapper: Wrapper, level: CompressionLevel) -> String {
362        let fresh = render(shadow, wrapper, level);
363        if self.start.is_some() {
364            let before = self.prefix();
365            let after = self.suffix();
366            let mut out = String::new();
367            if !before.is_empty() {
368                out.push_str(before);
369                out.push('\n');
370                out.push('\n');
371            }
372            out.push_str(&fresh);
373            if !after.is_empty() {
374                out.push('\n');
375                out.push('\n');
376                out.push_str(after);
377            }
378            if !out.ends_with('\n') {
379                out.push('\n');
380            }
381            out
382        } else {
383            // No existing section — append.
384            let trimmed = self.content.trim_end();
385            let mut out = trimmed.to_string();
386            if !out.is_empty() {
387                out.push('\n');
388                out.push('\n');
389            }
390            out.push_str(&fresh);
391            out
392        }
393    }
394
395    /// Create initial rules content (no existing section to merge with).
396    pub fn initial(shadow: bool, wrapper: Wrapper, level: CompressionLevel) -> String {
397        render(shadow, wrapper, level)
398    }
399
400    // ── Delete ─────────────────────────────────────────────────
401
402    /// Strip the lean-ctx section, keeping only user content before/after.
403    pub fn without_section(&self) -> String {
404        if let Some(start_pos) = self.start {
405            let before = self.content[..start_pos].trim();
406            let after = self.suffix();
407            let mut out = String::new();
408            if !before.is_empty() {
409                out.push_str(before);
410                out.push('\n');
411            }
412            if !after.is_empty() {
413                out.push('\n');
414                out.push_str(after);
415            }
416            out
417        } else {
418            self.content.to_string()
419        }
420    }
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426
427    // --- Constants ---
428
429    #[test]
430    fn bullets_uses_ctx_shell() {
431        assert!(BULLETS.contains("ctx_shell"));
432        assert!(!BULLETS.contains("lean-ctx -c"));
433        assert!(!BULLETS.contains("ctx_edit"));
434    }
435
436    #[test]
437    fn sections_not_empty() {
438        assert!(!BULLETS.is_empty());
439        assert!(!NEVER.is_empty());
440        assert!(!INTENT.is_empty());
441        assert!(!ANTI.is_empty());
442        assert!(!PARALLEL.is_empty());
443        assert!(!AUTO.is_empty());
444        assert!(!CEP.is_empty());
445        assert!(!INTELLIGENCE.is_empty());
446        assert!(!LITM_END.is_empty());
447        assert!(!CRITICAL.is_empty());
448    }
449
450    #[test]
451    fn intent_contains_ctx_compose() {
452        assert!(INTENT.contains("ctx_compose"));
453    }
454
455    #[test]
456    fn anti_contains_do_not() {
457        assert!(ANTI.contains("do NOT"));
458    }
459
460    #[test]
461    fn parallel_contains_parallel() {
462        assert!(PARALLEL.contains("PARALLEL"));
463    }
464
465    // --- render() — Dedicated ---
466
467    #[test]
468    fn dedicated_has_markers_and_version() {
469        let out = render(false, Wrapper::Dedicated, CompressionLevel::Off);
470        assert!(out.contains(START_MARK));
471        assert!(out.contains(&format!("<!-- version: {RULES_VERSION} -->")));
472        assert!(out.contains(END_MARK));
473        assert!(out.contains(BULLETS));
474        assert!(out.contains(NEVER));
475        assert!(out.contains("CRITICAL"));
476    }
477
478    #[test]
479    fn dedicated_shadow_omits_mapping() {
480        let out = render(true, Wrapper::Dedicated, CompressionLevel::Off);
481        assert!(out.contains(START_MARK));
482        assert!(
483            !out.contains("MANDATORY MAPPING"),
484            "shadow must not contain BULLETS"
485        );
486        assert!(!out.contains(NEVER), "shadow must not contain NEVER");
487        assert!(
488            !out.contains("CRITICAL"),
489            "shadow must not contain CRITICAL"
490        );
491        assert!(
492            out.contains(INTENT),
493            "shadow must keep non-mapping sections"
494        );
495    }
496
497    #[test]
498    fn dedicated_litm_structure() {
499        let out = render(false, Wrapper::Dedicated, CompressionLevel::Off);
500        let lines: Vec<&str> = out.lines().collect();
501        let first_5 = lines[..5.min(lines.len())].join("\n");
502        assert!(
503            first_5.contains("CRITICAL") || first_5.contains("MUST"),
504            "LITM: MUST/CRITICAL instruction near start"
505        );
506        // LITM_END or NEVER should appear in the final content lines (before END_MARK).
507        let tail = lines[lines.len().saturating_sub(8)..].join("\n");
508        assert!(
509            tail.contains("PREFERENCE") || tail.contains("NEVER"),
510            "LITM: reinforcement near end, tail={tail:?}"
511        );
512    }
513
514    // --- render() — Shared ---
515
516    #[test]
517    fn shared_has_markers_and_header() {
518        let out = render(false, Wrapper::Shared, CompressionLevel::Off);
519        assert!(out.contains(START_MARK));
520        assert!(out.contains(END_MARK));
521        assert!(out.contains("MANDATORY MAPPING"));
522        assert!(out.contains(BULLETS));
523    }
524
525    #[test]
526    fn shared_shadow_omits_mapping() {
527        let out = render(true, Wrapper::Shared, CompressionLevel::Off);
528        assert!(out.contains(START_MARK));
529        assert!(
530            !out.contains("MANDATORY MAPPING"),
531            "shadow must not have header"
532        );
533        assert!(
534            !out.contains("MANDATORY MAPPING"),
535            "shadow must not contain BULLETS"
536        );
537    }
538
539    // --- render() — Bare ---
540
541    #[test]
542    fn bare_has_no_markers() {
543        let out = render(false, Wrapper::Bare, CompressionLevel::Off);
544        assert!(!out.contains(START_MARK), "Bare must not have START_MARK");
545        assert!(!out.contains(END_MARK), "Bare must not have END_MARK");
546        assert!(!out.contains("<!-- version:"), "Bare must not have version");
547        assert!(out.contains(BULLETS));
548        assert!(out.contains(NEVER));
549    }
550
551    #[test]
552    fn bare_shadow_only_read_modes() {
553        let out = render(true, Wrapper::Bare, CompressionLevel::Off);
554        assert!(!out.contains(NEVER), "shadow Bare must not have NEVER");
555        assert!(
556            !out.contains("MANDATORY MAPPING"),
557            "shadow Bare must not have BULLETS"
558        );
559    }
560
561    // --- Compression level tests ---
562
563    #[test]
564    fn render_includes_lite_prompt() {
565        let out = render(false, Wrapper::Bare, CompressionLevel::Lite);
566        assert!(out.contains("OUTPUT STYLE: concise"));
567        assert!(out.contains("Bullet points"));
568    }
569
570    #[test]
571    fn render_includes_standard_prompt() {
572        let out = render(false, Wrapper::Bare, CompressionLevel::Standard);
573        assert!(out.contains("OUTPUT STYLE: dense"));
574        assert!(out.contains("atomic fact"));
575    }
576
577    #[test]
578    fn render_includes_max_prompt() {
579        let out = render(false, Wrapper::Bare, CompressionLevel::Max);
580        assert!(out.contains("OUTPUT STYLE: expert-terse"));
581        assert!(out.contains("Telegraph"));
582    }
583
584    #[test]
585    fn render_off_excludes_compression() {
586        let out = render(false, Wrapper::Bare, CompressionLevel::Off);
587        assert!(!out.contains("OUTPUT STYLE:"));
588    }
589
590    #[test]
591    fn compression_text_matches_level() {
592        assert!(compression_text(CompressionLevel::Off).is_empty());
593        assert!(compression_text(CompressionLevel::Lite).contains("Bullet"));
594        assert!(compression_text(CompressionLevel::Standard).contains("fn, cfg"));
595        assert!(compression_text(CompressionLevel::Max).contains("Telegraph"));
596    }
597
598    // --- Compression marker model (#548 B2) ---
599
600    #[test]
601    fn carrier_wrappers_wrap_compression_in_markers() {
602        // Persistent carriers must delimit the compression payload so coverage
603        // and dedup can detect/thin it (#684/#548).
604        for wrapper in [Wrapper::Dedicated, Wrapper::Shared] {
605            let out = render(false, wrapper, CompressionLevel::Standard);
606            assert!(
607                out.contains(COMPRESSION_BLOCK_START) && out.contains(COMPRESSION_BLOCK_END),
608                "{wrapper:?} must wrap compression in COMPRESSION_BLOCK markers"
609            );
610            // The marked region must actually contain the prompt body.
611            let start = out.find(COMPRESSION_BLOCK_START).unwrap();
612            let end = out.find(COMPRESSION_BLOCK_END).unwrap();
613            assert!(start < end, "{wrapper:?}: start marker precedes end marker");
614            assert!(out[start..end].contains("OUTPUT STYLE: dense"));
615        }
616    }
617
618    #[test]
619    fn bare_wrapper_emits_compression_without_markers() {
620        // The ephemeral MCP channel keeps the payload unmarked — its inclusion is
621        // governed by carrier coverage, so per-session markers would be noise.
622        let out = render(false, Wrapper::Bare, CompressionLevel::Standard);
623        assert!(out.contains("OUTPUT STYLE: dense"));
624        assert!(!out.contains(COMPRESSION_BLOCK_START));
625        assert!(!out.contains(COMPRESSION_BLOCK_END));
626    }
627
628    #[test]
629    fn compression_off_emits_no_markers_in_any_wrapper() {
630        for wrapper in [Wrapper::Dedicated, Wrapper::Shared, Wrapper::Bare] {
631            let out = render(false, wrapper, CompressionLevel::Off);
632            assert!(
633                !out.contains(COMPRESSION_BLOCK_START) && !out.contains(COMPRESSION_BLOCK_END),
634                "{wrapper:?}: Off must emit no compression markers"
635            );
636        }
637    }
638
639    #[test]
640    fn rendered_carrier_block_is_seen_as_carrying_compression() {
641        // The detection helper that coverage/dedup rely on must agree with the
642        // writer's output (the bug this slice fixes: it previously never did).
643        let dedicated = render(false, Wrapper::Dedicated, CompressionLevel::Lite);
644        assert!(crate::core::rules_channel::carries_full_rules(&dedicated));
645        assert!(dedicated.contains(COMPRESSION_BLOCK_START));
646    }
647
648    // --- Wrapper round-trip ---
649
650    #[test]
651    fn all_wrappers_produce_output() {
652        for shadow in [false, true] {
653            for wrapper in [Wrapper::Dedicated, Wrapper::Shared, Wrapper::Bare] {
654                let out = render(shadow, wrapper, CompressionLevel::Off);
655                assert!(!out.is_empty(), "{wrapper:?} shadow={shadow} is empty");
656            }
657        }
658    }
659
660    // --- RulesFile ---
661
662    #[test]
663    fn rules_file_parses_version() {
664        let content = format!(
665            "stuff before\n{START_MARK}\n<!-- version: {RULES_VERSION} -->\n\nbody\n{END_MARK}\nstuff after"
666        );
667        let f = RulesFile::parse(&content);
668        assert!(f.has_content());
669        assert_eq!(f.version(), RULES_VERSION);
670        assert!(f.is_current());
671        assert!(f.prefix().contains("stuff before"));
672        assert!(f.suffix().contains("stuff after"));
673    }
674
675    #[test]
676    fn rules_file_no_version_defaults_to_zero() {
677        let content = format!("{START_MARK}\nbody\n{END_MARK}");
678        let f = RulesFile::parse(&content);
679        assert!(f.has_content());
680        assert_eq!(f.version(), 0);
681        assert!(!f.is_current());
682    }
683
684    #[test]
685    fn rules_file_no_start_marker_no_content() {
686        let f = RulesFile::parse("just user stuff");
687        assert!(!f.has_content());
688        assert_eq!(f.version(), 0);
689    }
690
691    #[test]
692    fn block_matches_render_true_for_fresh_render() {
693        let fresh = render(false, Wrapper::Dedicated, CompressionLevel::Off);
694        let content = format!("user before\n{fresh}\nuser after");
695        let f = RulesFile::parse(&content);
696        assert!(f.is_current(), "fresh render carries the current version");
697        assert!(
698            f.block_matches_render(false, Wrapper::Dedicated, CompressionLevel::Off),
699            "an unchanged block must compare equal to a fresh render"
700        );
701    }
702
703    #[test]
704    fn block_matches_render_false_on_compression_change() {
705        // Body rendered at Off, then asked whether it matches a Max render:
706        // the version is identical but the compression payload differs (#548).
707        let content = render(false, Wrapper::Dedicated, CompressionLevel::Off);
708        let f = RulesFile::parse(&content);
709        assert!(f.is_current());
710        assert!(
711            !f.block_matches_render(false, Wrapper::Dedicated, CompressionLevel::Max),
712            "a compression-level change must be detected as drift"
713        );
714    }
715
716    #[test]
717    fn block_matches_render_false_on_shadow_change() {
718        let content = render(false, Wrapper::Dedicated, CompressionLevel::Lite);
719        let f = RulesFile::parse(&content);
720        assert!(
721            !f.block_matches_render(true, Wrapper::Dedicated, CompressionLevel::Lite),
722            "a shadow-mode toggle must be detected as drift"
723        );
724    }
725
726    #[test]
727    fn block_matches_render_false_without_block() {
728        let f = RulesFile::parse("plain user content, no markers");
729        assert!(!f.block_matches_render(false, Wrapper::Dedicated, CompressionLevel::Off));
730    }
731
732    #[test]
733    fn rules_file_merged_replaces_section() {
734        let content =
735            format!("before\n{START_MARK}\n<!-- version: 1 -->\n\nold\n{END_MARK}\nafter");
736        let f = RulesFile::parse(&content);
737        let merged = f.merged(false, Wrapper::Shared, CompressionLevel::Off);
738        assert!(merged.contains("before"), "prefix preserved");
739        assert!(merged.contains("after"), "suffix preserved");
740        assert!(!merged.contains("old"), "old content replaced");
741        assert!(merged.contains(&format!("<!-- version: {RULES_VERSION} -->")));
742    }
743
744    #[test]
745    fn rules_file_merged_appends_when_no_section() {
746        let content = "user content";
747        let f = RulesFile::parse(content);
748        assert!(!f.has_content());
749        let merged = f.merged(false, Wrapper::Bare, CompressionLevel::Off);
750        assert!(merged.contains("user content"));
751        assert!(merged.contains(BULLETS));
752    }
753
754    #[test]
755    fn rules_file_without_section_strips_content() {
756        let content =
757            format!("header\n{START_MARK}\n<!-- version: 1 -->\n\nbody\n{END_MARK}\nfooter");
758        let f = RulesFile::parse(&content);
759        let stripped = f.without_section();
760        assert!(stripped.contains("header"));
761        assert!(stripped.contains("footer"));
762        assert!(!stripped.contains("body"));
763        assert!(!stripped.contains(START_MARK));
764    }
765
766    #[test]
767    fn rules_file_without_section_noop_when_no_content() {
768        let content = "just user text";
769        let f = RulesFile::parse(content);
770        assert_eq!(f.without_section(), content);
771    }
772}