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