1use crate::core::config::CompressionLevel;
19
20pub const START_MARK: &str = "<!-- lean-ctx-rules -->";
25
26pub const RULES_MARKER_PREFIX: &str = "<!-- lean-ctx-rules";
30
31pub const AGENTS_BLOCK_START: &str = "<!-- lean-ctx -->";
37
38pub const AGENTS_BLOCK_END: &str = "<!-- /lean-ctx -->";
40
41pub const PROJECT_LEAN_CTX_OWNED_MARKER: &str = "<!-- lean-ctx-owned: PROJECT-LEAN-CTX.md v1 -->";
47
48pub const END_MARK: &str = "<!-- /lean-ctx-rules -->";
50
51pub const COMPRESSION_BLOCK_START: &str = "<!-- lean-ctx-compression -->";
63
64pub const COMPRESSION_BLOCK_END: &str = "<!-- /lean-ctx-compression -->";
67
68pub const SOLUTION_BLOCK_START: &str = "<!-- lean-ctx-solution -->";
70
71pub const SOLUTION_BLOCK_END: &str = "<!-- /lean-ctx-solution -->";
73
74pub 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
90pub const RULES_VERSION: usize = 11;
117
118pub const CRITICAL: &str = "CRITICAL: ALWAYS use lean-ctx ctx_* tools as mapped below.";
128
129pub const MUST_INVOKE: &str = "ACTUALLY EMIT the ctx_* tool call (ctx_compose first) — \
140 describing a tool is not calling it.";
141
142pub const BULLETS: &str = "\
144MANDATORY MAPPING:\n\
145• Read/cat -> ctx_read(path, mode)\n\
146• Grep -> ctx_search(pattern, path)\n\
147• Shell/bash -> ctx_shell(command)\n\
148• Glob/find -> ctx_glob(pattern)\n\
149• ls/find -> ctx_tree(path, depth)";
150
151pub const NEVER: &str = "NEVER use built-in Read/Grep/Shell/Glob for these jobs. \
163 SELF-CORRECT: the moment you reach for one, stop and call the ctx_* tool \
164 instead. Other MCP servers keep their own jobs.";
165
166pub const INTENT: &str = "\
171Tool selection by intent:\n\
172• Orient in this codebase (call FIRST) -> ctx_compose\n\
173• Read a file -> ctx_read(path, mode=signatures|map|full); edit after reading -> ctx_patch\n\
174• Exact symbol -> ctx_search(action=symbol); pattern -> ctx_search; by meaning -> ctx_search(action=semantic)\n\
175• Files by glob -> ctx_glob; structure -> ctx_tree; callers/impact -> ctx_callgraph\n\
176• Verify after edits -> ctx_shell(test/build); memory -> ctx_session / ctx_knowledge\n\
177Semantic questions -> search tools, not whole-file reads: reading more ≠ understanding more.";
178
179pub const ANTI: &str = "\
181Anti-patterns — do NOT:\n\
182• Chain ctx_search -> ctx_read -> ctx_search(action=symbol) — one ctx_compose replaces all three\n\
183• Use ctx_read(mode=full) for orientation — use mode=signatures\n\
184• Use ctx_callgraph/ctx_graph for const/static/variable refs — they track call\n\
185 edges and file deps only; use ctx_search instead";
186
187pub const PARALLEL: &str = "\
189PARALLEL: fire independent tool calls in the SAME turn — ctx_compose bundles \
190multiple lookups into one call.";
191
192pub const AGENT_LOOP: &str = "\
197AGENT LOOP (phase -> tool):\n\
198• Orient — understand before acting -> ctx_compose\n\
199• Find — exact symbol by name -> ctx_search(action=symbol)\n\
200• Read — a file, structurally -> ctx_read(mode=signatures|map)\n\
201• Locate — a pattern across files -> ctx_search\n\
202• Trace — callers / callees / blast radius -> ctx_callgraph\n\
203• Verify — after an edit -> ctx_shell(test/build) + native lints";
204
205pub const NAV_PARADOX: &str = "\
210NAVIGATION PARADOX: reading more ≠ understanding more.\n\
211• Semantic question (\"where/how is X handled?\") -> ctx_search (BM25) + ctx_search(action=semantic) (meaning), not whole-file reads\n\
212• Hidden architectural deps (who calls this, what breaks) -> ctx_callgraph / ctx_graph — for these only\n\
213• Navigate structure (signatures, symbols) before reading entire files";
214
215pub const AUTO: &str = "Long shell jobs: ctx_shell(run_in_background=true), then poll job_id. \
217 ctx_session=memory; full guide: LEAN-CTX.md";
218
219pub const RECOVER: &str = "RECOVER: compressed output is reversible — never re-read line-by-line. \
228 Need full/exact? Read the shown file path with any tool (no MCP), or \
229 ctx_read(mode=full|raw=true); [Archived]/tee/firewall → ctx_expand(id=...).";
230
231pub const RECOVER_COMPACT: &str = "RECOVER: compression is reversible — read the shown path \
238 (no MCP) or ctx_read(raw=true), never re-read line-by-line.";
239
240pub const ROOT_RESTRICTION: &str = "ROOTS: ctx_* refuses paths outside project root + allow_paths. \
244 Use native Read for out-of-root; `lean-ctx doctor` shows effective roots.";
245
246pub const CEP: &str = "CEP v1: 1.ACT FIRST 2.DELTA ONLY (Fn refs) 3.STRUCTURED (+/-/~) \
248 4.ONE LINE PER ACTION 5.QUALITY ANCHOR";
249
250pub const LITM_END: &str = "TOOL PREFERENCE (END): ctx_compose>chain ctx_read>Read ctx_shell>Shell \
252 ctx_search>Grep ctx_glob>Glob ctx_tree>ls | Edit/Write/Delete=native";
253
254pub const SHADOW_MINIMAL: &str = "\
260lean-ctx shadow mode: native read/search/shell calls auto-route to ctx_* — no tool-mapping needed.\n\
261File editing → the host's native edit tool (lean-ctx only handles reads); if denied, use ctx_patch.\n\
262Exclusive tools (no native trigger): ctx_compose (understand code, call first), ctx_search(action=symbol) (exact symbol), ctx_search(action=semantic) (by meaning), ctx_callgraph (callers), ctx_knowledge / ctx_session (memory).";
263
264pub const HOOK_COVERED_HEADER: &str = "\
272CRITICAL: ALWAYS prefer lean-ctx ctx_* tools over native equivalents — ctx_* tools \
273provide superior caching, compression, and session memory. Hooks compress native \
274Shell/Read/Grep as fallback, but direct ctx_* calls are the primary path.\n\
275ACTUALLY EMIT the ctx_* tool call (ctx_compose first) — describing a tool is not calling it.\n\
276WHY ctx_read > native Read: ctx_read picks the optimal mode (map/signatures/terse) \
277per file, caches unchanged full/auto re-reads (~13 tokens), and compresses 26-92%. Native \
278Read through hook redirect is limited to verbatim pass-through (~5% savings).";
279
280pub const HOOK_COVERED_TOOLS: &str = "\
284MANDATORY MAPPING (always use ctx_* instead of native):\n\
285• Read/cat -> ctx_read(path, mode) — cached, 10 modes, unchanged full/auto re-reads ~13 tokens\n\
286• Grep/search -> ctx_search(pattern, path) — also action=symbol|semantic for definitions/meaning\n\
287• Shell/bash -> ctx_shell(command) — 95+ compression patterns\n\
288• ctx_compose — orient in code FIRST (bundles search + read + symbols) — call before editing/debugging\n\
289• ctx_callgraph — callers, callees, blast radius — use instead of manual file reading\n\
290• ctx_session / ctx_knowledge — persistent memory — record decisions & progress after milestones\n\
291• ctx_expand — recover full text from [Archived]/compressed output";
292
293pub const LITE_PROMPT: &str = "\
297OUTPUT STYLE: concise
298- Bullet points over paragraphs
299- Skip filler words and hedging (\"I think\", \"probably\", \"it seems\")
300- 1-sentence explanations max, then code/action
301- No repeating what the user said";
302
303pub const STANDARD_PROMPT: &str = "\
305OUTPUT STYLE: dense
306- Each statement = one atomic fact line
307- Use abbreviations: fn, cfg, impl, deps, req, res, ctx, err, ret
308- Diff lines only (+/-/~), never repeat unchanged code
309- Symbols: → (causes), + (adds), − (removes), ~ (modifies), ∴ (therefore)
310- No narration, no filler, no hedging
311- BUDGET: ≤200 tokens per response unless code block required";
312
313pub const MAX_PROMPT: &str = "\
315OUTPUT STYLE: expert-terse
316- Telegraph format: subject-verb-object, drop articles/prepositions
317- Symbolic vocabulary: → cause, ∵ because, ∴ therefore, ⊕ add, ⊖ remove, Δ change, ≈ similar, ≠ different, ∈ in/member, ∅ empty/none, ✓ ok, ✗ fail
318- Code blocks: untouched (never compress code syntax)
319- Each line: max 80 chars
320- Zero narration, zero filler
321- BUDGET: ≤100 tokens per non-code response";
322
323pub const RAW_PROMPT: &str = "\
326OUTPUT STYLE: raw-dense
327- Bullet points ONLY, zero prose, no intro, no outro, no greetings
328- Diff-style facts: +added, -removed, ~changed, !breaking
329- One fact per line, max 60 chars
330- Symbolic: → ∵ ∴ ⊕ ⊖ Δ ≈ ≠ ∈ ∅ ✓ ✗ (same as expert-terse)
331- Code blocks: untouched
332- BUDGET: ≤50 tokens per non-code response
333- NEVER explain what you did — show only the result";
334
335pub fn compression_text(level: CompressionLevel) -> &'static str {
337 match level {
338 CompressionLevel::Off => "",
339 CompressionLevel::Lite => LITE_PROMPT,
340 CompressionLevel::Standard => STANDARD_PROMPT,
341 CompressionLevel::Max => MAX_PROMPT,
342 CompressionLevel::Raw => RAW_PROMPT,
343 }
344}
345
346fn s(c: &str) -> String {
357 c.to_string()
358}
359
360fn longform_non_shadow_sections(p: &super::tool_profiles::ToolProfile) -> Vec<String> {
361 use super::rules_sections as rs;
362 let mut v = vec![
363 s(CRITICAL),
364 rs::must_invoke_section(p),
365 s(BULLETS),
366 s(NEVER),
367 rs::intent_section(p),
368 s(AGENT_LOOP), rs::anti_section(p),
370 s(NAV_PARADOX), rs::parallel_section(p),
372 s(AUTO),
373 s(RECOVER),
374 s(ROOT_RESTRICTION),
375 s(CEP),
376 rs::litm_end_section(p),
377 ];
378 if let Some(fb) = rs::ctx_call_fallback(p) {
379 v.push(fb);
380 }
381 v
382}
383
384fn full_non_shadow_sections(p: &super::tool_profiles::ToolProfile) -> Vec<String> {
385 use super::rules_sections as rs;
386 let mut v = vec![
387 s(CRITICAL),
388 rs::must_invoke_section(p),
389 s(BULLETS),
390 s(NEVER),
391 rs::intent_section(p),
392 rs::anti_section(p),
393 rs::parallel_section(p),
394 s(AUTO),
395 s(RECOVER_COMPACT),
396 s(ROOT_RESTRICTION),
397 rs::litm_end_section(p),
398 ];
399 if let Some(fb) = rs::ctx_call_fallback(p) {
400 v.push(fb);
401 }
402 v
403}
404
405fn full_shadow_sections(p: &super::tool_profiles::ToolProfile) -> Vec<String> {
406 use super::rules_sections as rs;
407 vec![rs::shadow_minimal_section(p)]
408}
409
410fn hook_covered_non_shadow_sections(p: &super::tool_profiles::ToolProfile) -> Vec<String> {
411 use super::rules_sections as rs;
412 let mut v = vec![
413 s(HOOK_COVERED_HEADER),
414 rs::hook_covered_tools_section(p),
415 rs::parallel_section(p),
416 s(RECOVER_COMPACT),
417 s(ROOT_RESTRICTION),
418 ];
419 if let Some(fb) = rs::ctx_call_fallback(p) {
420 v.push(fb);
421 }
422 v
423}
424
425fn compact_non_shadow_sections(p: &super::tool_profiles::ToolProfile) -> Vec<String> {
426 use super::rules_sections as rs;
427 let mut v = vec![
428 s(CRITICAL),
429 s(BULLETS),
430 s(NEVER),
431 rs::intent_section(p),
432 rs::anti_section(p),
433 rs::parallel_section(p),
434 s(RECOVER_COMPACT),
435 s(ROOT_RESTRICTION),
436 ];
437 if let Some(fb) = rs::ctx_call_fallback(p) {
438 v.push(fb);
439 }
440 v
441}
442
443fn compact_shadow_sections(p: &super::tool_profiles::ToolProfile) -> Vec<String> {
444 use super::rules_sections as rs;
445 vec![rs::shadow_minimal_section(p)]
446}
447
448#[derive(Debug, Clone, Copy, PartialEq, Eq)]
451pub enum Wrapper {
452 Longform,
457
458 Dedicated,
463
464 Shared,
468
469 Bare,
472
473 HookCovered,
480}
481
482pub fn render(
493 shadow: bool,
494 wrapper: Wrapper,
495 level: CompressionLevel,
496 tool_profile: &super::tool_profiles::ToolProfile,
497) -> String {
498 let cfg = crate::core::config::Config::load();
499 render_with_solution(shadow, wrapper, level, tool_profile, &cfg.solution)
500}
501
502pub(crate) fn render_with_solution(
507 shadow: bool,
508 wrapper: Wrapper,
509 level: CompressionLevel,
510 tool_profile: &super::tool_profiles::ToolProfile,
511 solution: &super::config::solution::SolutionConfig,
512) -> String {
513 use super::rules_sections as rs;
514
515 let sections: Vec<String> = match (wrapper, shadow) {
516 (Wrapper::Longform, false) => longform_non_shadow_sections(tool_profile),
517 (Wrapper::Longform | Wrapper::Dedicated | Wrapper::HookCovered, true) => {
518 full_shadow_sections(tool_profile)
519 }
520 (Wrapper::Dedicated, false) => full_non_shadow_sections(tool_profile),
521 (Wrapper::HookCovered, false) => hook_covered_non_shadow_sections(tool_profile),
522 (_, false) => compact_non_shadow_sections(tool_profile),
523 (_, true) => compact_shadow_sections(tool_profile),
524 };
525
526 let mut body: String = sections
529 .into_iter()
530 .filter(|s| !s.is_empty())
531 .collect::<Vec<_>>()
532 .join("\n\n");
533 let _ = rs::intent_section; let compression = compression_text(level);
540 if !compression.is_empty() {
541 body.push('\n');
542 if matches!(wrapper, Wrapper::Bare) {
543 body.push_str(compression);
544 } else {
545 body.push_str(COMPRESSION_BLOCK_START);
546 body.push('\n');
547 body.push_str(compression);
548 body.push('\n');
549 body.push_str(COMPRESSION_BLOCK_END);
550 }
551 }
552
553 let ladder = solution.ladder_text();
555 if !ladder.is_empty() {
556 body.push('\n');
557 if matches!(wrapper, Wrapper::Bare) {
558 body.push_str(ladder);
559 } else {
560 body.push_str(SOLUTION_BLOCK_START);
561 body.push('\n');
562 body.push_str("SOLUTION EFFICIENCY: stop at first level that applies:\n");
563 body.push_str("skip (YAGNI) → reuse codebase → stdlib → native platform → installed dep → one-line → minimum code.\n");
564 body.push_str("Never skip: validation, security, error handling.\n");
565 body.push_str(SOLUTION_BLOCK_END);
566 }
567 }
568
569 if matches!(wrapper, Wrapper::Bare) {
570 return body;
571 }
572
573 let version_line = format!("<!-- version: {RULES_VERSION} -->");
574
575 format!("{START_MARK}\n{version_line}\n\n{body}\n{END_MARK}")
576}
577
578pub fn render_hook_covered_bare(
585 shadow: bool,
586 level: CompressionLevel,
587 tool_profile: &super::tool_profiles::ToolProfile,
588) -> String {
589 if shadow {
590 return render(true, Wrapper::Bare, level, tool_profile);
591 }
592 let sections = hook_covered_non_shadow_sections(tool_profile);
593 let mut body: String = sections
594 .into_iter()
595 .filter(|s| !s.is_empty())
596 .collect::<Vec<_>>()
597 .join("\n\n");
598 let compression = compression_text(level);
599 if !compression.is_empty() {
600 body.push('\n');
601 body.push_str(compression);
602 }
603 body
604}
605pub use super::rules_validation::RulesFile;
607
608#[cfg(test)]
609mod tests {
610 use super::*;
611
612 fn tp() -> super::super::tool_profiles::ToolProfile {
613 super::super::tool_profiles::ToolProfile::Power
614 }
615
616 #[test]
619 fn bullets_uses_ctx_shell() {
620 assert!(BULLETS.contains("ctx_shell"));
621 assert!(!BULLETS.contains("lean-ctx -c"));
622 assert!(!BULLETS.contains("ctx_edit"));
623 }
624
625 #[test]
626 fn sections_not_empty() {
627 assert!(!BULLETS.is_empty());
628 assert!(!NEVER.is_empty());
629 assert!(!INTENT.is_empty());
630 assert!(!ANTI.is_empty());
631 assert!(!PARALLEL.is_empty());
632 assert!(!AUTO.is_empty());
633 assert!(!CEP.is_empty());
634 assert!(!LITM_END.is_empty());
635 assert!(!CRITICAL.is_empty());
636 }
637
638 #[test]
639 fn intent_contains_ctx_compose() {
640 assert!(INTENT.contains("ctx_compose"));
641 }
642
643 #[test]
644 fn anti_contains_do_not() {
645 assert!(ANTI.contains("do NOT"));
646 }
647
648 #[test]
649 fn parallel_contains_parallel() {
650 assert!(PARALLEL.contains("PARALLEL"));
651 }
652
653 #[test]
656 fn agent_loop_names_every_phase() {
657 for phase in ["Orient", "Find", "Read", "Locate", "Trace", "Verify"] {
658 assert!(AGENT_LOOP.contains(phase), "AGENT_LOOP must name {phase}");
659 }
660 assert!(AGENT_LOOP.contains("ctx_compose") && AGENT_LOOP.contains("ctx_callgraph"));
661 }
662
663 #[test]
664 fn nav_paradox_steers_semantic_vs_graph() {
665 assert!(
666 NAV_PARADOX.contains("ctx_search(action=semantic)"),
667 "semantic route must use folded action (#509)"
668 );
669 assert!(NAV_PARADOX.contains("ctx_callgraph"), "graph route");
670 assert!(
671 NAV_PARADOX.contains("≠"),
672 "must carry the reading≠understanding thesis"
673 );
674 }
675
676 #[test]
677 fn longform_carries_loop_and_paradox_injected_full_does_not() {
678 let long = render(false, Wrapper::Longform, CompressionLevel::Off, &tp());
682 assert!(
683 long.contains("AGENT LOOP"),
684 "LONGFORM must carry AGENT_LOOP"
685 );
686 assert!(
687 long.contains("NAVIGATION PARADOX"),
688 "LONGFORM must carry NAV_PARADOX"
689 );
690 assert!(long.contains(CEP), "LONGFORM must carry CEP");
691
692 let full = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
693 assert!(
694 !full.contains("AGENT LOOP (phase -> tool):"),
695 "injected FULL must not inline the multi-line AGENT_LOOP block"
696 );
697 assert!(
698 !full.contains("NAVIGATION PARADOX: reading"),
699 "injected FULL must not inline the multi-line NAV_PARADOX block"
700 );
701 assert!(
702 full.contains('≠'),
703 "INTENT must keep the reading≠understanding thesis in FULL"
704 );
705 for phase_tool in [
707 "ctx_compose",
708 "ctx_search(action=symbol)",
709 "ctx_search",
710 "ctx_callgraph",
711 ] {
712 assert!(
713 full.contains(phase_tool),
714 "FULL keeps the loop tools via INTENT: {phase_tool}"
715 );
716 }
717 }
718
719 #[test]
720 fn injected_profiles_stay_lean() {
721 let full = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
725 eprintln!(
726 "rules footprint: dedicated={} chars (~{} tok), longform={} chars, bare={} chars",
727 full.len(),
728 full.len() / 4,
729 render(false, Wrapper::Longform, CompressionLevel::Off, &tp()).len(),
730 render(false, Wrapper::Bare, CompressionLevel::Off, &tp()).len(),
731 );
732 assert!(
733 full.len() <= 2400,
734 "injected dedicated rules must stay ≤2400 chars (~600 tok), got {} chars (~{} tok)",
735 full.len(),
736 full.len() / 4
737 );
738 let long = render(false, Wrapper::Longform, CompressionLevel::Off, &tp());
739 assert!(
740 long.len() > full.len(),
741 "Longform ({}) must carry more than the injected profile ({})",
742 long.len(),
743 full.len()
744 );
745 let compact = render(false, Wrapper::Bare, CompressionLevel::Off, &tp());
746 assert!(
747 compact.len() < full.len(),
748 "COMPACT/Bare ({}) must stay below the dedicated profile ({})",
749 compact.len(),
750 full.len()
751 );
752 }
753
754 #[test]
755 fn compact_profile_has_no_multiline_teaching_sections() {
756 let out = render(false, Wrapper::Shared, CompressionLevel::Off, &tp());
759 assert!(
760 !out.contains("AGENT LOOP (phase -> tool):"),
761 "COMPACT must not inline the multi-line AGENT_LOOP block"
762 );
763 assert!(
764 !out.contains("NAVIGATION PARADOX: reading"),
765 "COMPACT must not inline the multi-line NAV_PARADOX block"
766 );
767 assert!(
768 out.contains('≠'),
769 "COMPACT keeps the reading≠understanding thesis via INTENT"
770 );
771 }
772
773 #[test]
774 fn shadow_omits_loop_and_paradox() {
775 for wrapper in [Wrapper::Longform, Wrapper::Dedicated, Wrapper::Shared] {
778 let out = render(true, wrapper, CompressionLevel::Off, &tp());
779 assert!(!out.contains("AGENT LOOP"), "{wrapper:?} shadow drops loop");
780 assert!(
781 !out.contains("NAVIGATION PARADOX"),
782 "{wrapper:?} shadow drops paradox"
783 );
784 }
785 }
786
787 #[test]
788 fn recover_reaches_every_non_shadow_carrier() {
789 let long = render(false, Wrapper::Longform, CompressionLevel::Off, &tp());
796 assert!(
797 long.contains(RECOVER),
798 "Longform must carry the verbose RECOVER verbatim"
799 );
800 for wrapper in [Wrapper::Dedicated, Wrapper::Shared, Wrapper::Bare] {
801 let out = render(false, wrapper, CompressionLevel::Off, &tp());
802 assert!(
803 out.contains(RECOVER_COMPACT),
804 "{wrapper:?} must carry RECOVER_COMPACT verbatim"
805 );
806 assert!(
807 !out.contains(RECOVER),
808 "{wrapper:?} must not inline the verbose RECOVER block"
809 );
810 }
811 for wrapper in [
812 Wrapper::Longform,
813 Wrapper::Dedicated,
814 Wrapper::Shared,
815 Wrapper::Bare,
816 ] {
817 assert!(
818 render(false, wrapper, CompressionLevel::Off, &tp()).contains("(no MCP)"),
819 "{wrapper:?} recovery line must keep the MCP-free path"
820 );
821 }
822 for wrapper in [Wrapper::Dedicated, Wrapper::Shared] {
823 let out = render(true, wrapper, CompressionLevel::Off, &tp());
824 assert!(
825 !out.contains(RECOVER) && !out.contains(RECOVER_COMPACT),
826 "{wrapper:?} shadow drops all RECOVER guidance"
827 );
828 }
829 }
830
831 #[test]
834 fn dedicated_has_markers_and_version() {
835 let out = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
836 assert!(out.contains(START_MARK));
837 assert!(out.contains(&format!("<!-- version: {RULES_VERSION} -->")));
838 assert!(out.contains(END_MARK));
839 assert!(out.contains(BULLETS));
840 assert!(out.contains(NEVER));
841 assert!(out.contains("CRITICAL"));
842 }
843
844 #[test]
845 fn dedicated_shadow_is_minimal() {
846 let out = render(true, Wrapper::Dedicated, CompressionLevel::Off, &tp());
849 assert!(out.contains(START_MARK));
850 assert!(!out.contains("MANDATORY MAPPING"), "no BULLETS in shadow");
851 assert!(!out.contains(NEVER), "no NEVER in shadow");
852 assert!(!out.contains("CRITICAL"), "no CRITICAL banner in shadow");
853 assert!(
854 !out.contains("Tool selection by intent"),
855 "routing INTENT block is redundant under interception"
856 );
857 assert!(
858 !out.contains("Anti-patterns") && !out.contains("PARALLEL tool calls"),
859 "ANTI/PARALLEL routing guidance is dropped in shadow"
860 );
861 assert!(
862 out.contains("shadow mode") && out.contains("ctx_compose"),
863 "shadow keeps the exclusive-tool advert"
864 );
865 }
866
867 #[test]
868 fn shadow_is_smaller_than_non_shadow() {
869 let shadow = render(true, Wrapper::Dedicated, CompressionLevel::Off, &tp());
871 let full = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
872 assert!(
873 shadow.len() < full.len(),
874 "shadow ({}) must be smaller than non-shadow ({})",
875 shadow.len(),
876 full.len()
877 );
878 }
879
880 #[test]
881 fn dedicated_litm_structure() {
882 let out = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
883 let lines: Vec<&str> = out.lines().collect();
884 let first_5 = lines[..5.min(lines.len())].join("\n");
885 assert!(
886 first_5.contains("CRITICAL") || first_5.contains("MUST"),
887 "LITM: MUST/CRITICAL instruction near start"
888 );
889 let tail = lines[lines.len().saturating_sub(8)..].join("\n");
891 assert!(
892 tail.contains("PREFERENCE") || tail.contains("NEVER"),
893 "LITM: reinforcement near end, tail={tail:?}"
894 );
895 }
896
897 #[test]
898 fn dedicated_carries_weak_model_invoke_nudge() {
899 let dedicated = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
904 assert!(
905 dedicated.contains(MUST_INVOKE),
906 "dedicated non-shadow rules must carry the MUST_INVOKE nudge"
907 );
908 assert!(
909 !render(true, Wrapper::Dedicated, CompressionLevel::Off, &tp()).contains(MUST_INVOKE),
910 "shadow mode must not carry the nudge (routing is enforced at the call layer)"
911 );
912 assert!(
913 !render(false, Wrapper::Bare, CompressionLevel::Off, &tp()).contains(MUST_INVOKE),
914 "Bare/instructions channel is capped separately and carries no copy"
915 );
916 }
917
918 #[test]
921 fn shared_has_markers_and_header() {
922 let out = render(false, Wrapper::Shared, CompressionLevel::Off, &tp());
923 assert!(out.contains(START_MARK));
924 assert!(out.contains(END_MARK));
925 assert!(out.contains("MANDATORY MAPPING"));
926 assert!(out.contains(BULLETS));
927 }
928
929 #[test]
930 fn shared_shadow_omits_mapping() {
931 let out = render(true, Wrapper::Shared, CompressionLevel::Off, &tp());
932 assert!(out.contains(START_MARK));
933 assert!(
934 !out.contains("MANDATORY MAPPING"),
935 "shadow must not have header"
936 );
937 assert!(
938 !out.contains("MANDATORY MAPPING"),
939 "shadow must not contain BULLETS"
940 );
941 }
942
943 #[test]
946 fn bare_has_no_markers() {
947 let out = render(false, Wrapper::Bare, CompressionLevel::Off, &tp());
948 assert!(!out.contains(START_MARK), "Bare must not have START_MARK");
949 assert!(!out.contains(END_MARK), "Bare must not have END_MARK");
950 assert!(!out.contains("<!-- version:"), "Bare must not have version");
951 assert!(out.contains(BULLETS));
952 assert!(out.contains(NEVER));
953 }
954
955 #[test]
956 fn bare_shadow_only_read_modes() {
957 let out = render(true, Wrapper::Bare, CompressionLevel::Off, &tp());
958 assert!(!out.contains(NEVER), "shadow Bare must not have NEVER");
959 assert!(
960 !out.contains("MANDATORY MAPPING"),
961 "shadow Bare must not have BULLETS"
962 );
963 }
964
965 #[test]
968 fn render_includes_lite_prompt() {
969 let out = render(false, Wrapper::Bare, CompressionLevel::Lite, &tp());
970 assert!(out.contains("OUTPUT STYLE: concise"));
971 assert!(out.contains("Bullet points"));
972 }
973
974 #[test]
975 fn render_includes_standard_prompt() {
976 let out = render(false, Wrapper::Bare, CompressionLevel::Standard, &tp());
977 assert!(out.contains("OUTPUT STYLE: dense"));
978 assert!(out.contains("atomic fact"));
979 }
980
981 #[test]
982 fn render_includes_max_prompt() {
983 let out = render(false, Wrapper::Bare, CompressionLevel::Max, &tp());
984 assert!(out.contains("OUTPUT STYLE: expert-terse"));
985 assert!(out.contains("Telegraph"));
986 }
987
988 #[test]
989 fn render_off_excludes_compression() {
990 let out = render(false, Wrapper::Bare, CompressionLevel::Off, &tp());
991 assert!(!out.contains("OUTPUT STYLE:"));
992 }
993
994 #[test]
995 fn compression_text_matches_level() {
996 assert!(compression_text(CompressionLevel::Off).is_empty());
997 assert!(compression_text(CompressionLevel::Lite).contains("Bullet"));
998 assert!(compression_text(CompressionLevel::Standard).contains("fn, cfg"));
999 assert!(compression_text(CompressionLevel::Max).contains("Telegraph"));
1000 }
1001
1002 #[test]
1005 fn carrier_wrappers_wrap_compression_in_markers() {
1006 for wrapper in [Wrapper::Longform, Wrapper::Dedicated, Wrapper::Shared] {
1009 let out = render(false, wrapper, CompressionLevel::Standard, &tp());
1010 assert!(
1011 out.contains(COMPRESSION_BLOCK_START) && out.contains(COMPRESSION_BLOCK_END),
1012 "{wrapper:?} must wrap compression in COMPRESSION_BLOCK markers"
1013 );
1014 let start = out.find(COMPRESSION_BLOCK_START).unwrap();
1016 let end = out.find(COMPRESSION_BLOCK_END).unwrap();
1017 assert!(start < end, "{wrapper:?}: start marker precedes end marker");
1018 assert!(out[start..end].contains("OUTPUT STYLE: dense"));
1019 }
1020 }
1021
1022 #[test]
1023 fn bare_wrapper_emits_compression_without_markers() {
1024 let out = render(false, Wrapper::Bare, CompressionLevel::Standard, &tp());
1027 assert!(out.contains("OUTPUT STYLE: dense"));
1028 assert!(!out.contains(COMPRESSION_BLOCK_START));
1029 assert!(!out.contains(COMPRESSION_BLOCK_END));
1030 }
1031
1032 #[test]
1033 fn compression_off_emits_no_markers_in_any_wrapper() {
1034 for wrapper in [
1035 Wrapper::Longform,
1036 Wrapper::Dedicated,
1037 Wrapper::Shared,
1038 Wrapper::Bare,
1039 ] {
1040 let out = render(false, wrapper, CompressionLevel::Off, &tp());
1041 assert!(
1042 !out.contains(COMPRESSION_BLOCK_START) && !out.contains(COMPRESSION_BLOCK_END),
1043 "{wrapper:?}: Off must emit no compression markers"
1044 );
1045 }
1046 }
1047
1048 #[test]
1049 fn rendered_carrier_block_is_seen_as_carrying_compression() {
1050 let dedicated = render(false, Wrapper::Dedicated, CompressionLevel::Lite, &tp());
1053 assert!(crate::core::rules_channel::carries_full_rules(&dedicated));
1054 assert!(dedicated.contains(COMPRESSION_BLOCK_START));
1055 }
1056
1057 #[test]
1060 fn all_wrappers_produce_output() {
1061 for shadow in [false, true] {
1062 for wrapper in [
1063 Wrapper::Longform,
1064 Wrapper::Dedicated,
1065 Wrapper::Shared,
1066 Wrapper::Bare,
1067 ] {
1068 let out = render(shadow, wrapper, CompressionLevel::Off, &tp());
1069 assert!(!out.is_empty(), "{wrapper:?} shadow={shadow} is empty");
1070 }
1071 }
1072 }
1073
1074 #[test]
1077 fn rules_file_parses_version() {
1078 let content = format!(
1079 "stuff before\n{START_MARK}\n<!-- version: {RULES_VERSION} -->\n\nbody\n{END_MARK}\nstuff after"
1080 );
1081 let f = RulesFile::parse(&content);
1082 assert!(f.has_content());
1083 assert_eq!(f.version(), RULES_VERSION);
1084 assert!(f.is_current());
1085 assert!(f.prefix().contains("stuff before"));
1086 assert!(f.suffix().contains("stuff after"));
1087 }
1088
1089 #[test]
1090 fn rules_file_no_version_defaults_to_zero() {
1091 let content = format!("{START_MARK}\nbody\n{END_MARK}");
1092 let f = RulesFile::parse(&content);
1093 assert!(f.has_content());
1094 assert_eq!(f.version(), 0);
1095 assert!(!f.is_current());
1096 }
1097
1098 #[test]
1099 fn rules_file_no_start_marker_no_content() {
1100 let f = RulesFile::parse("just user stuff");
1101 assert!(!f.has_content());
1102 assert_eq!(f.version(), 0);
1103 }
1104
1105 #[test]
1106 fn block_matches_render_true_for_fresh_render() {
1107 let fresh = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
1108 let content = format!("user before\n{fresh}\nuser after");
1109 let f = RulesFile::parse(&content);
1110 assert!(f.is_current(), "fresh render carries the current version");
1111 assert!(
1112 f.block_matches_render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp()),
1113 "an unchanged block must compare equal to a fresh render"
1114 );
1115 }
1116
1117 #[test]
1118 fn block_matches_render_false_on_compression_change() {
1119 let content = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
1122 let f = RulesFile::parse(&content);
1123 assert!(f.is_current());
1124 assert!(
1125 !f.block_matches_render(false, Wrapper::Dedicated, CompressionLevel::Max, &tp()),
1126 "a compression-level change must be detected as drift"
1127 );
1128 }
1129
1130 #[test]
1131 fn block_matches_render_false_on_shadow_change() {
1132 let content = render(false, Wrapper::Dedicated, CompressionLevel::Lite, &tp());
1133 let f = RulesFile::parse(&content);
1134 assert!(
1135 !f.block_matches_render(true, Wrapper::Dedicated, CompressionLevel::Lite, &tp()),
1136 "a shadow-mode toggle must be detected as drift"
1137 );
1138 }
1139
1140 #[test]
1141 fn block_matches_render_false_without_block() {
1142 let f = RulesFile::parse("plain user content, no markers");
1143 assert!(!f.block_matches_render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp()));
1144 }
1145
1146 #[test]
1147 fn rules_file_merged_replaces_section() {
1148 let content =
1149 format!("before\n{START_MARK}\n<!-- version: 1 -->\n\nold\n{END_MARK}\nafter");
1150 let f = RulesFile::parse(&content);
1151 let merged = f.merged(false, Wrapper::Shared, CompressionLevel::Off, &tp());
1152 assert!(merged.contains("before"), "prefix preserved");
1153 assert!(merged.contains("after"), "suffix preserved");
1154 assert!(!merged.contains("old"), "old content replaced");
1155 assert!(merged.contains(&format!("<!-- version: {RULES_VERSION} -->")));
1156 }
1157
1158 #[test]
1159 fn rules_file_merged_appends_when_no_section() {
1160 let content = "user content";
1161 let f = RulesFile::parse(content);
1162 assert!(!f.has_content());
1163 let merged = f.merged(false, Wrapper::Bare, CompressionLevel::Off, &tp());
1164 assert!(merged.contains("user content"));
1165 assert!(merged.contains(BULLETS));
1166 }
1167
1168 #[test]
1169 fn rules_file_without_section_strips_content() {
1170 let content =
1171 format!("header\n{START_MARK}\n<!-- version: 1 -->\n\nbody\n{END_MARK}\nfooter");
1172 let f = RulesFile::parse(&content);
1173 let stripped = f.without_section();
1174 assert!(stripped.contains("header"));
1175 assert!(stripped.contains("footer"));
1176 assert!(!stripped.contains("body"));
1177 assert!(!stripped.contains(START_MARK));
1178 }
1179
1180 #[test]
1181 fn rules_file_without_section_noop_when_no_content() {
1182 let content = "just user text";
1183 let f = RulesFile::parse(content);
1184 assert_eq!(f.without_section(), content);
1185 }
1186
1187 #[test]
1188 fn bullets_lead_with_four_core_redirects() {
1189 let read = BULLETS.find("ctx_read").expect("ctx_read mapping present");
1191 let search = BULLETS
1192 .find("ctx_search")
1193 .expect("ctx_search mapping present");
1194 let shell = BULLETS
1195 .find("ctx_shell")
1196 .expect("ctx_shell mapping present");
1197 let glob = BULLETS.find("ctx_glob").expect("ctx_glob mapping present");
1198 let tree = BULLETS.find("ctx_tree").expect("ctx_tree mapping present");
1199 assert!(
1200 read < search && search < shell && shell < glob && glob < tree,
1201 "core redirects (read<search<shell<glob) must precede ctx_tree"
1202 );
1203 }
1204
1205 #[test]
1206 fn never_carries_self_correction() {
1207 assert!(
1209 NEVER.contains("SELF-CORRECT"),
1210 "NEVER must teach self-correction"
1211 );
1212 assert!(
1213 NEVER.contains("call"),
1214 "NEVER must spell out the corrective action"
1215 );
1216 }
1217
1218 #[test]
1219 fn critical_names_ctx_family() {
1220 assert!(
1221 CRITICAL.contains("ctx_*"),
1222 "CRITICAL must name the ctx_* family"
1223 );
1224 }
1225
1226 #[test]
1229 fn hook_covered_carries_strict_mapping() {
1230 let out = render(false, Wrapper::HookCovered, CompressionLevel::Off, &tp());
1233 assert!(
1234 !out.contains(NEVER),
1235 "HookCovered uses its own strict header, not the NEVER constant"
1236 );
1237 assert!(
1238 out.contains(HOOK_COVERED_HEADER),
1239 "must carry the strict preference header"
1240 );
1241 assert!(
1242 out.contains("MANDATORY MAPPING")
1243 && out.contains("ctx_read")
1244 && out.contains("ctx_search"),
1245 "must carry the full mandatory mapping"
1246 );
1247 assert!(
1248 out.contains("ctx_compose") && out.contains("action=symbol|semantic"),
1249 "must advertise the search capabilities"
1250 );
1251 }
1252
1253 #[test]
1254 fn hook_covered_keeps_markers_version_and_recovery() {
1255 let out = render(false, Wrapper::HookCovered, CompressionLevel::Off, &tp());
1259 assert!(out.contains(START_MARK) && out.contains(END_MARK));
1260 assert!(out.contains(&format!("<!-- version: {RULES_VERSION} -->")));
1261 assert!(out.contains(RECOVER_COMPACT), "recovery line must survive");
1262 assert!(out.contains("(no MCP)"), "MCP-free recovery path stays");
1263 }
1264
1265 #[test]
1266 fn hook_covered_is_leaner_than_full() {
1267 let covered = render(false, Wrapper::HookCovered, CompressionLevel::Off, &tp());
1268 let full = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
1269 assert!(
1270 covered.len() < full.len(),
1271 "HookCovered ({}) must be a strict reduction of FULL ({})",
1272 covered.len(),
1273 full.len()
1274 );
1275 }
1276
1277 #[test]
1278 fn hook_covered_shadow_collapses_to_minimal() {
1279 let covered_shadow = render(true, Wrapper::HookCovered, CompressionLevel::Off, &tp());
1282 let dedicated_shadow = render(true, Wrapper::Dedicated, CompressionLevel::Off, &tp());
1283 assert_eq!(covered_shadow, dedicated_shadow);
1284 }
1285
1286 #[test]
1287 fn hook_covered_wraps_compression_in_markers() {
1288 let out = render(
1289 false,
1290 Wrapper::HookCovered,
1291 CompressionLevel::Standard,
1292 &tp(),
1293 );
1294 assert!(out.contains(COMPRESSION_BLOCK_START) && out.contains(COMPRESSION_BLOCK_END));
1295 assert!(out.contains("OUTPUT STYLE: dense"));
1296 }
1297
1298 #[test]
1301 fn rules_only_mention_enabled_tools() {
1302 use super::super::rules_sections;
1303 use super::super::tool_profiles::ToolProfile;
1304 let exclusive_tools = ["ctx_compose", "ctx_callgraph", "ctx_patch"];
1305 for profile in [ToolProfile::Minimal, ToolProfile::Standard] {
1306 let mut sections = vec![
1307 rules_sections::intent_section(&profile),
1308 rules_sections::hook_covered_tools_section(&profile),
1309 rules_sections::shadow_minimal_section(&profile),
1310 rules_sections::anti_section(&profile),
1311 rules_sections::litm_end_section(&profile),
1312 ];
1313 if let Some(fb) = rules_sections::ctx_call_fallback(&profile) {
1314 sections.push(fb);
1315 }
1316 for tool in &exclusive_tools {
1317 if !profile.is_tool_enabled(tool) {
1318 for section in §ions {
1319 assert!(
1320 !section.contains(tool),
1321 "profile {:?} dynamic section must not mention disabled tool {tool}",
1322 profile.as_str()
1323 );
1324 }
1325 }
1326 }
1327 }
1328 }
1329
1330 #[test]
1331 fn minimal_rules_shorter_than_standard() {
1332 use super::super::tool_profiles::ToolProfile;
1333 let min = render(
1334 false,
1335 Wrapper::Dedicated,
1336 CompressionLevel::Off,
1337 &ToolProfile::Minimal,
1338 );
1339 let std = render(
1340 false,
1341 Wrapper::Dedicated,
1342 CompressionLevel::Off,
1343 &ToolProfile::Standard,
1344 );
1345 assert!(
1346 min.len() < std.len(),
1347 "minimal ({}) must be shorter than standard ({})",
1348 min.len(),
1349 std.len()
1350 );
1351 }
1352
1353 #[test]
1354 fn power_profile_output_identical_to_default() {
1355 use super::super::tool_profiles::ToolProfile;
1356 let power = render(
1357 false,
1358 Wrapper::Dedicated,
1359 CompressionLevel::Off,
1360 &ToolProfile::Power,
1361 );
1362 assert!(
1363 power.contains("ctx_compose"),
1364 "Power must include all tools"
1365 );
1366 assert!(
1367 power.contains("ctx_callgraph"),
1368 "Power must include all tools"
1369 );
1370 assert!(
1371 power.contains("ctx_session"),
1372 "Power must include all tools"
1373 );
1374 }
1375
1376 #[test]
1377 fn render_is_deterministic_across_profiles() {
1378 use super::super::tool_profiles::ToolProfile;
1379 for profile in [
1380 ToolProfile::Minimal,
1381 ToolProfile::Standard,
1382 ToolProfile::Power,
1383 ] {
1384 let a = render(false, Wrapper::Dedicated, CompressionLevel::Off, &profile);
1385 let b = render(false, Wrapper::Dedicated, CompressionLevel::Off, &profile);
1386 assert_eq!(
1387 a,
1388 b,
1389 "render must be deterministic for {:?}",
1390 profile.as_str()
1391 );
1392 }
1393 }
1394
1395 #[test]
1396 fn minimal_has_ctx_call_fallback() {
1397 use super::super::tool_profiles::ToolProfile;
1398 let rules = render(
1399 false,
1400 Wrapper::Dedicated,
1401 CompressionLevel::Off,
1402 &ToolProfile::Minimal,
1403 );
1404 assert!(
1405 rules.contains("ctx_call"),
1406 "minimal profile must include ctx_call gateway hint"
1407 );
1408 }
1409
1410 #[test]
1411 fn power_has_no_ctx_call_fallback() {
1412 use super::super::tool_profiles::ToolProfile;
1413 let rules = render(
1414 false,
1415 Wrapper::Dedicated,
1416 CompressionLevel::Off,
1417 &ToolProfile::Power,
1418 );
1419 assert!(
1420 !rules.contains("ctx_call(tool="),
1421 "power profile must not include ctx_call gateway hint"
1422 );
1423 }
1424}