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