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 use super::rules_sections as rs;
499
500 let sections: Vec<String> = match (wrapper, shadow) {
501 (Wrapper::Longform, false) => longform_non_shadow_sections(tool_profile),
502 (Wrapper::Longform | Wrapper::Dedicated | Wrapper::HookCovered, true) => {
503 full_shadow_sections(tool_profile)
504 }
505 (Wrapper::Dedicated, false) => full_non_shadow_sections(tool_profile),
506 (Wrapper::HookCovered, false) => hook_covered_non_shadow_sections(tool_profile),
507 (_, false) => compact_non_shadow_sections(tool_profile),
508 (_, true) => compact_shadow_sections(tool_profile),
509 };
510
511 let mut body: String = sections
514 .into_iter()
515 .filter(|s| !s.is_empty())
516 .collect::<Vec<_>>()
517 .join("\n\n");
518 let _ = rs::intent_section; let compression = compression_text(level);
525 if !compression.is_empty() {
526 body.push('\n');
527 if matches!(wrapper, Wrapper::Bare) {
528 body.push_str(compression);
529 } else {
530 body.push_str(COMPRESSION_BLOCK_START);
531 body.push('\n');
532 body.push_str(compression);
533 body.push('\n');
534 body.push_str(COMPRESSION_BLOCK_END);
535 }
536 }
537
538 {
540 let cfg = crate::core::config::Config::load();
541 if cfg.solution.enabled {
542 let ladder = cfg.solution.ladder_text();
543 if !ladder.is_empty() {
544 body.push('\n');
545 if matches!(wrapper, Wrapper::Bare) {
546 body.push_str(ladder);
547 } else {
548 body.push_str(SOLUTION_BLOCK_START);
549 body.push('\n');
550 body.push_str("SOLUTION EFFICIENCY: stop at first level that applies:\n");
551 body.push_str("skip (YAGNI) → reuse codebase → stdlib → native platform → installed dep → one-line → minimum code.\n");
552 body.push_str("Never skip: validation, security, error handling.\n");
553 body.push_str(SOLUTION_BLOCK_END);
554 }
555 }
556 }
557 }
558
559 if matches!(wrapper, Wrapper::Bare) {
560 return body;
561 }
562
563 let version_line = format!("<!-- version: {RULES_VERSION} -->");
564
565 format!("{START_MARK}\n{version_line}\n\n{body}\n{END_MARK}")
566}
567
568pub fn render_hook_covered_bare(
575 shadow: bool,
576 level: CompressionLevel,
577 tool_profile: &super::tool_profiles::ToolProfile,
578) -> String {
579 if shadow {
580 return render(true, Wrapper::Bare, level, tool_profile);
581 }
582 let sections = hook_covered_non_shadow_sections(tool_profile);
583 let mut body: String = sections
584 .into_iter()
585 .filter(|s| !s.is_empty())
586 .collect::<Vec<_>>()
587 .join("\n\n");
588 let compression = compression_text(level);
589 if !compression.is_empty() {
590 body.push('\n');
591 body.push_str(compression);
592 }
593 body
594}
595pub use super::rules_validation::RulesFile;
597
598#[cfg(test)]
599mod tests {
600 use super::*;
601
602 fn tp() -> super::super::tool_profiles::ToolProfile {
603 super::super::tool_profiles::ToolProfile::Power
604 }
605
606 #[test]
609 fn bullets_uses_ctx_shell() {
610 assert!(BULLETS.contains("ctx_shell"));
611 assert!(!BULLETS.contains("lean-ctx -c"));
612 assert!(!BULLETS.contains("ctx_edit"));
613 }
614
615 #[test]
616 fn sections_not_empty() {
617 assert!(!BULLETS.is_empty());
618 assert!(!NEVER.is_empty());
619 assert!(!INTENT.is_empty());
620 assert!(!ANTI.is_empty());
621 assert!(!PARALLEL.is_empty());
622 assert!(!AUTO.is_empty());
623 assert!(!CEP.is_empty());
624 assert!(!LITM_END.is_empty());
625 assert!(!CRITICAL.is_empty());
626 }
627
628 #[test]
629 fn intent_contains_ctx_compose() {
630 assert!(INTENT.contains("ctx_compose"));
631 }
632
633 #[test]
634 fn anti_contains_do_not() {
635 assert!(ANTI.contains("do NOT"));
636 }
637
638 #[test]
639 fn parallel_contains_parallel() {
640 assert!(PARALLEL.contains("PARALLEL"));
641 }
642
643 #[test]
646 fn agent_loop_names_every_phase() {
647 for phase in ["Orient", "Find", "Read", "Locate", "Trace", "Verify"] {
648 assert!(AGENT_LOOP.contains(phase), "AGENT_LOOP must name {phase}");
649 }
650 assert!(AGENT_LOOP.contains("ctx_compose") && AGENT_LOOP.contains("ctx_callgraph"));
651 }
652
653 #[test]
654 fn nav_paradox_steers_semantic_vs_graph() {
655 assert!(
656 NAV_PARADOX.contains("ctx_search(action=semantic)"),
657 "semantic route must use folded action (#509)"
658 );
659 assert!(NAV_PARADOX.contains("ctx_callgraph"), "graph route");
660 assert!(
661 NAV_PARADOX.contains("≠"),
662 "must carry the reading≠understanding thesis"
663 );
664 }
665
666 #[test]
667 fn longform_carries_loop_and_paradox_injected_full_does_not() {
668 let long = render(false, Wrapper::Longform, CompressionLevel::Off, &tp());
672 assert!(
673 long.contains("AGENT LOOP"),
674 "LONGFORM must carry AGENT_LOOP"
675 );
676 assert!(
677 long.contains("NAVIGATION PARADOX"),
678 "LONGFORM must carry NAV_PARADOX"
679 );
680 assert!(long.contains(CEP), "LONGFORM must carry CEP");
681
682 let full = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
683 assert!(
684 !full.contains("AGENT LOOP (phase -> tool):"),
685 "injected FULL must not inline the multi-line AGENT_LOOP block"
686 );
687 assert!(
688 !full.contains("NAVIGATION PARADOX: reading"),
689 "injected FULL must not inline the multi-line NAV_PARADOX block"
690 );
691 assert!(
692 full.contains('≠'),
693 "INTENT must keep the reading≠understanding thesis in FULL"
694 );
695 for phase_tool in [
697 "ctx_compose",
698 "ctx_search(action=symbol)",
699 "ctx_search",
700 "ctx_callgraph",
701 ] {
702 assert!(
703 full.contains(phase_tool),
704 "FULL keeps the loop tools via INTENT: {phase_tool}"
705 );
706 }
707 }
708
709 #[test]
710 fn injected_profiles_stay_lean() {
711 let full = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
715 eprintln!(
716 "rules footprint: dedicated={} chars (~{} tok), longform={} chars, bare={} chars",
717 full.len(),
718 full.len() / 4,
719 render(false, Wrapper::Longform, CompressionLevel::Off, &tp()).len(),
720 render(false, Wrapper::Bare, CompressionLevel::Off, &tp()).len(),
721 );
722 assert!(
723 full.len() <= 2400,
724 "injected dedicated rules must stay ≤2400 chars (~600 tok), got {} chars (~{} tok)",
725 full.len(),
726 full.len() / 4
727 );
728 let long = render(false, Wrapper::Longform, CompressionLevel::Off, &tp());
729 assert!(
730 long.len() > full.len(),
731 "Longform ({}) must carry more than the injected profile ({})",
732 long.len(),
733 full.len()
734 );
735 let compact = render(false, Wrapper::Bare, CompressionLevel::Off, &tp());
736 assert!(
737 compact.len() < full.len(),
738 "COMPACT/Bare ({}) must stay below the dedicated profile ({})",
739 compact.len(),
740 full.len()
741 );
742 }
743
744 #[test]
745 fn compact_profile_has_no_multiline_teaching_sections() {
746 let out = render(false, Wrapper::Shared, CompressionLevel::Off, &tp());
749 assert!(
750 !out.contains("AGENT LOOP (phase -> tool):"),
751 "COMPACT must not inline the multi-line AGENT_LOOP block"
752 );
753 assert!(
754 !out.contains("NAVIGATION PARADOX: reading"),
755 "COMPACT must not inline the multi-line NAV_PARADOX block"
756 );
757 assert!(
758 out.contains('≠'),
759 "COMPACT keeps the reading≠understanding thesis via INTENT"
760 );
761 }
762
763 #[test]
764 fn shadow_omits_loop_and_paradox() {
765 for wrapper in [Wrapper::Longform, Wrapper::Dedicated, Wrapper::Shared] {
768 let out = render(true, wrapper, CompressionLevel::Off, &tp());
769 assert!(!out.contains("AGENT LOOP"), "{wrapper:?} shadow drops loop");
770 assert!(
771 !out.contains("NAVIGATION PARADOX"),
772 "{wrapper:?} shadow drops paradox"
773 );
774 }
775 }
776
777 #[test]
778 fn recover_reaches_every_non_shadow_carrier() {
779 let long = render(false, Wrapper::Longform, CompressionLevel::Off, &tp());
786 assert!(
787 long.contains(RECOVER),
788 "Longform must carry the verbose RECOVER verbatim"
789 );
790 for wrapper in [Wrapper::Dedicated, Wrapper::Shared, Wrapper::Bare] {
791 let out = render(false, wrapper, CompressionLevel::Off, &tp());
792 assert!(
793 out.contains(RECOVER_COMPACT),
794 "{wrapper:?} must carry RECOVER_COMPACT verbatim"
795 );
796 assert!(
797 !out.contains(RECOVER),
798 "{wrapper:?} must not inline the verbose RECOVER block"
799 );
800 }
801 for wrapper in [
802 Wrapper::Longform,
803 Wrapper::Dedicated,
804 Wrapper::Shared,
805 Wrapper::Bare,
806 ] {
807 assert!(
808 render(false, wrapper, CompressionLevel::Off, &tp()).contains("(no MCP)"),
809 "{wrapper:?} recovery line must keep the MCP-free path"
810 );
811 }
812 for wrapper in [Wrapper::Dedicated, Wrapper::Shared] {
813 let out = render(true, wrapper, CompressionLevel::Off, &tp());
814 assert!(
815 !out.contains(RECOVER) && !out.contains(RECOVER_COMPACT),
816 "{wrapper:?} shadow drops all RECOVER guidance"
817 );
818 }
819 }
820
821 #[test]
824 fn dedicated_has_markers_and_version() {
825 let out = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
826 assert!(out.contains(START_MARK));
827 assert!(out.contains(&format!("<!-- version: {RULES_VERSION} -->")));
828 assert!(out.contains(END_MARK));
829 assert!(out.contains(BULLETS));
830 assert!(out.contains(NEVER));
831 assert!(out.contains("CRITICAL"));
832 }
833
834 #[test]
835 fn dedicated_shadow_is_minimal() {
836 let out = render(true, Wrapper::Dedicated, CompressionLevel::Off, &tp());
839 assert!(out.contains(START_MARK));
840 assert!(!out.contains("MANDATORY MAPPING"), "no BULLETS in shadow");
841 assert!(!out.contains(NEVER), "no NEVER in shadow");
842 assert!(!out.contains("CRITICAL"), "no CRITICAL banner in shadow");
843 assert!(
844 !out.contains("Tool selection by intent"),
845 "routing INTENT block is redundant under interception"
846 );
847 assert!(
848 !out.contains("Anti-patterns") && !out.contains("PARALLEL tool calls"),
849 "ANTI/PARALLEL routing guidance is dropped in shadow"
850 );
851 assert!(
852 out.contains("shadow mode") && out.contains("ctx_compose"),
853 "shadow keeps the exclusive-tool advert"
854 );
855 }
856
857 #[test]
858 fn shadow_is_smaller_than_non_shadow() {
859 let shadow = render(true, Wrapper::Dedicated, CompressionLevel::Off, &tp());
861 let full = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
862 assert!(
863 shadow.len() < full.len(),
864 "shadow ({}) must be smaller than non-shadow ({})",
865 shadow.len(),
866 full.len()
867 );
868 }
869
870 #[test]
871 fn dedicated_litm_structure() {
872 let out = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
873 let lines: Vec<&str> = out.lines().collect();
874 let first_5 = lines[..5.min(lines.len())].join("\n");
875 assert!(
876 first_5.contains("CRITICAL") || first_5.contains("MUST"),
877 "LITM: MUST/CRITICAL instruction near start"
878 );
879 let tail = lines[lines.len().saturating_sub(8)..].join("\n");
881 assert!(
882 tail.contains("PREFERENCE") || tail.contains("NEVER"),
883 "LITM: reinforcement near end, tail={tail:?}"
884 );
885 }
886
887 #[test]
888 fn dedicated_carries_weak_model_invoke_nudge() {
889 let dedicated = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
894 assert!(
895 dedicated.contains(MUST_INVOKE),
896 "dedicated non-shadow rules must carry the MUST_INVOKE nudge"
897 );
898 assert!(
899 !render(true, Wrapper::Dedicated, CompressionLevel::Off, &tp()).contains(MUST_INVOKE),
900 "shadow mode must not carry the nudge (routing is enforced at the call layer)"
901 );
902 assert!(
903 !render(false, Wrapper::Bare, CompressionLevel::Off, &tp()).contains(MUST_INVOKE),
904 "Bare/instructions channel is capped separately and carries no copy"
905 );
906 }
907
908 #[test]
911 fn shared_has_markers_and_header() {
912 let out = render(false, Wrapper::Shared, CompressionLevel::Off, &tp());
913 assert!(out.contains(START_MARK));
914 assert!(out.contains(END_MARK));
915 assert!(out.contains("MANDATORY MAPPING"));
916 assert!(out.contains(BULLETS));
917 }
918
919 #[test]
920 fn shared_shadow_omits_mapping() {
921 let out = render(true, Wrapper::Shared, CompressionLevel::Off, &tp());
922 assert!(out.contains(START_MARK));
923 assert!(
924 !out.contains("MANDATORY MAPPING"),
925 "shadow must not have header"
926 );
927 assert!(
928 !out.contains("MANDATORY MAPPING"),
929 "shadow must not contain BULLETS"
930 );
931 }
932
933 #[test]
936 fn bare_has_no_markers() {
937 let out = render(false, Wrapper::Bare, CompressionLevel::Off, &tp());
938 assert!(!out.contains(START_MARK), "Bare must not have START_MARK");
939 assert!(!out.contains(END_MARK), "Bare must not have END_MARK");
940 assert!(!out.contains("<!-- version:"), "Bare must not have version");
941 assert!(out.contains(BULLETS));
942 assert!(out.contains(NEVER));
943 }
944
945 #[test]
946 fn bare_shadow_only_read_modes() {
947 let out = render(true, Wrapper::Bare, CompressionLevel::Off, &tp());
948 assert!(!out.contains(NEVER), "shadow Bare must not have NEVER");
949 assert!(
950 !out.contains("MANDATORY MAPPING"),
951 "shadow Bare must not have BULLETS"
952 );
953 }
954
955 #[test]
958 fn render_includes_lite_prompt() {
959 let out = render(false, Wrapper::Bare, CompressionLevel::Lite, &tp());
960 assert!(out.contains("OUTPUT STYLE: concise"));
961 assert!(out.contains("Bullet points"));
962 }
963
964 #[test]
965 fn render_includes_standard_prompt() {
966 let out = render(false, Wrapper::Bare, CompressionLevel::Standard, &tp());
967 assert!(out.contains("OUTPUT STYLE: dense"));
968 assert!(out.contains("atomic fact"));
969 }
970
971 #[test]
972 fn render_includes_max_prompt() {
973 let out = render(false, Wrapper::Bare, CompressionLevel::Max, &tp());
974 assert!(out.contains("OUTPUT STYLE: expert-terse"));
975 assert!(out.contains("Telegraph"));
976 }
977
978 #[test]
979 fn render_off_excludes_compression() {
980 let out = render(false, Wrapper::Bare, CompressionLevel::Off, &tp());
981 assert!(!out.contains("OUTPUT STYLE:"));
982 }
983
984 #[test]
985 fn compression_text_matches_level() {
986 assert!(compression_text(CompressionLevel::Off).is_empty());
987 assert!(compression_text(CompressionLevel::Lite).contains("Bullet"));
988 assert!(compression_text(CompressionLevel::Standard).contains("fn, cfg"));
989 assert!(compression_text(CompressionLevel::Max).contains("Telegraph"));
990 }
991
992 #[test]
995 fn carrier_wrappers_wrap_compression_in_markers() {
996 for wrapper in [Wrapper::Longform, Wrapper::Dedicated, Wrapper::Shared] {
999 let out = render(false, wrapper, CompressionLevel::Standard, &tp());
1000 assert!(
1001 out.contains(COMPRESSION_BLOCK_START) && out.contains(COMPRESSION_BLOCK_END),
1002 "{wrapper:?} must wrap compression in COMPRESSION_BLOCK markers"
1003 );
1004 let start = out.find(COMPRESSION_BLOCK_START).unwrap();
1006 let end = out.find(COMPRESSION_BLOCK_END).unwrap();
1007 assert!(start < end, "{wrapper:?}: start marker precedes end marker");
1008 assert!(out[start..end].contains("OUTPUT STYLE: dense"));
1009 }
1010 }
1011
1012 #[test]
1013 fn bare_wrapper_emits_compression_without_markers() {
1014 let out = render(false, Wrapper::Bare, CompressionLevel::Standard, &tp());
1017 assert!(out.contains("OUTPUT STYLE: dense"));
1018 assert!(!out.contains(COMPRESSION_BLOCK_START));
1019 assert!(!out.contains(COMPRESSION_BLOCK_END));
1020 }
1021
1022 #[test]
1023 fn compression_off_emits_no_markers_in_any_wrapper() {
1024 for wrapper in [
1025 Wrapper::Longform,
1026 Wrapper::Dedicated,
1027 Wrapper::Shared,
1028 Wrapper::Bare,
1029 ] {
1030 let out = render(false, wrapper, CompressionLevel::Off, &tp());
1031 assert!(
1032 !out.contains(COMPRESSION_BLOCK_START) && !out.contains(COMPRESSION_BLOCK_END),
1033 "{wrapper:?}: Off must emit no compression markers"
1034 );
1035 }
1036 }
1037
1038 #[test]
1039 fn rendered_carrier_block_is_seen_as_carrying_compression() {
1040 let dedicated = render(false, Wrapper::Dedicated, CompressionLevel::Lite, &tp());
1043 assert!(crate::core::rules_channel::carries_full_rules(&dedicated));
1044 assert!(dedicated.contains(COMPRESSION_BLOCK_START));
1045 }
1046
1047 #[test]
1050 fn all_wrappers_produce_output() {
1051 for shadow in [false, true] {
1052 for wrapper in [
1053 Wrapper::Longform,
1054 Wrapper::Dedicated,
1055 Wrapper::Shared,
1056 Wrapper::Bare,
1057 ] {
1058 let out = render(shadow, wrapper, CompressionLevel::Off, &tp());
1059 assert!(!out.is_empty(), "{wrapper:?} shadow={shadow} is empty");
1060 }
1061 }
1062 }
1063
1064 #[test]
1067 fn rules_file_parses_version() {
1068 let content = format!(
1069 "stuff before\n{START_MARK}\n<!-- version: {RULES_VERSION} -->\n\nbody\n{END_MARK}\nstuff after"
1070 );
1071 let f = RulesFile::parse(&content);
1072 assert!(f.has_content());
1073 assert_eq!(f.version(), RULES_VERSION);
1074 assert!(f.is_current());
1075 assert!(f.prefix().contains("stuff before"));
1076 assert!(f.suffix().contains("stuff after"));
1077 }
1078
1079 #[test]
1080 fn rules_file_no_version_defaults_to_zero() {
1081 let content = format!("{START_MARK}\nbody\n{END_MARK}");
1082 let f = RulesFile::parse(&content);
1083 assert!(f.has_content());
1084 assert_eq!(f.version(), 0);
1085 assert!(!f.is_current());
1086 }
1087
1088 #[test]
1089 fn rules_file_no_start_marker_no_content() {
1090 let f = RulesFile::parse("just user stuff");
1091 assert!(!f.has_content());
1092 assert_eq!(f.version(), 0);
1093 }
1094
1095 #[test]
1096 fn block_matches_render_true_for_fresh_render() {
1097 let fresh = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
1098 let content = format!("user before\n{fresh}\nuser after");
1099 let f = RulesFile::parse(&content);
1100 assert!(f.is_current(), "fresh render carries the current version");
1101 assert!(
1102 f.block_matches_render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp()),
1103 "an unchanged block must compare equal to a fresh render"
1104 );
1105 }
1106
1107 #[test]
1108 fn block_matches_render_false_on_compression_change() {
1109 let content = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
1112 let f = RulesFile::parse(&content);
1113 assert!(f.is_current());
1114 assert!(
1115 !f.block_matches_render(false, Wrapper::Dedicated, CompressionLevel::Max, &tp()),
1116 "a compression-level change must be detected as drift"
1117 );
1118 }
1119
1120 #[test]
1121 fn block_matches_render_false_on_shadow_change() {
1122 let content = render(false, Wrapper::Dedicated, CompressionLevel::Lite, &tp());
1123 let f = RulesFile::parse(&content);
1124 assert!(
1125 !f.block_matches_render(true, Wrapper::Dedicated, CompressionLevel::Lite, &tp()),
1126 "a shadow-mode toggle must be detected as drift"
1127 );
1128 }
1129
1130 #[test]
1131 fn block_matches_render_false_without_block() {
1132 let f = RulesFile::parse("plain user content, no markers");
1133 assert!(!f.block_matches_render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp()));
1134 }
1135
1136 #[test]
1137 fn rules_file_merged_replaces_section() {
1138 let content =
1139 format!("before\n{START_MARK}\n<!-- version: 1 -->\n\nold\n{END_MARK}\nafter");
1140 let f = RulesFile::parse(&content);
1141 let merged = f.merged(false, Wrapper::Shared, CompressionLevel::Off, &tp());
1142 assert!(merged.contains("before"), "prefix preserved");
1143 assert!(merged.contains("after"), "suffix preserved");
1144 assert!(!merged.contains("old"), "old content replaced");
1145 assert!(merged.contains(&format!("<!-- version: {RULES_VERSION} -->")));
1146 }
1147
1148 #[test]
1149 fn rules_file_merged_appends_when_no_section() {
1150 let content = "user content";
1151 let f = RulesFile::parse(content);
1152 assert!(!f.has_content());
1153 let merged = f.merged(false, Wrapper::Bare, CompressionLevel::Off, &tp());
1154 assert!(merged.contains("user content"));
1155 assert!(merged.contains(BULLETS));
1156 }
1157
1158 #[test]
1159 fn rules_file_without_section_strips_content() {
1160 let content =
1161 format!("header\n{START_MARK}\n<!-- version: 1 -->\n\nbody\n{END_MARK}\nfooter");
1162 let f = RulesFile::parse(&content);
1163 let stripped = f.without_section();
1164 assert!(stripped.contains("header"));
1165 assert!(stripped.contains("footer"));
1166 assert!(!stripped.contains("body"));
1167 assert!(!stripped.contains(START_MARK));
1168 }
1169
1170 #[test]
1171 fn rules_file_without_section_noop_when_no_content() {
1172 let content = "just user text";
1173 let f = RulesFile::parse(content);
1174 assert_eq!(f.without_section(), content);
1175 }
1176
1177 #[test]
1178 fn bullets_lead_with_four_core_redirects() {
1179 let read = BULLETS.find("ctx_read").expect("ctx_read mapping present");
1181 let search = BULLETS
1182 .find("ctx_search")
1183 .expect("ctx_search mapping present");
1184 let shell = BULLETS
1185 .find("ctx_shell")
1186 .expect("ctx_shell mapping present");
1187 let glob = BULLETS.find("ctx_glob").expect("ctx_glob mapping present");
1188 let tree = BULLETS.find("ctx_tree").expect("ctx_tree mapping present");
1189 assert!(
1190 read < search && search < shell && shell < glob && glob < tree,
1191 "core redirects (read<search<shell<glob) must precede ctx_tree"
1192 );
1193 }
1194
1195 #[test]
1196 fn never_carries_self_correction() {
1197 assert!(
1199 NEVER.contains("SELF-CORRECT"),
1200 "NEVER must teach self-correction"
1201 );
1202 assert!(
1203 NEVER.contains("call"),
1204 "NEVER must spell out the corrective action"
1205 );
1206 }
1207
1208 #[test]
1209 fn critical_names_ctx_family() {
1210 assert!(
1211 CRITICAL.contains("ctx_*"),
1212 "CRITICAL must name the ctx_* family"
1213 );
1214 }
1215
1216 #[test]
1219 fn hook_covered_carries_strict_mapping() {
1220 let out = render(false, Wrapper::HookCovered, CompressionLevel::Off, &tp());
1223 assert!(
1224 !out.contains(NEVER),
1225 "HookCovered uses its own strict header, not the NEVER constant"
1226 );
1227 assert!(
1228 out.contains(HOOK_COVERED_HEADER),
1229 "must carry the strict preference header"
1230 );
1231 assert!(
1232 out.contains("MANDATORY MAPPING")
1233 && out.contains("ctx_read")
1234 && out.contains("ctx_search"),
1235 "must carry the full mandatory mapping"
1236 );
1237 assert!(
1238 out.contains("ctx_compose") && out.contains("action=symbol|semantic"),
1239 "must advertise the search capabilities"
1240 );
1241 }
1242
1243 #[test]
1244 fn hook_covered_keeps_markers_version_and_recovery() {
1245 let out = render(false, Wrapper::HookCovered, CompressionLevel::Off, &tp());
1249 assert!(out.contains(START_MARK) && out.contains(END_MARK));
1250 assert!(out.contains(&format!("<!-- version: {RULES_VERSION} -->")));
1251 assert!(out.contains(RECOVER_COMPACT), "recovery line must survive");
1252 assert!(out.contains("(no MCP)"), "MCP-free recovery path stays");
1253 }
1254
1255 #[test]
1256 fn hook_covered_is_leaner_than_full() {
1257 let covered = render(false, Wrapper::HookCovered, CompressionLevel::Off, &tp());
1258 let full = render(false, Wrapper::Dedicated, CompressionLevel::Off, &tp());
1259 assert!(
1260 covered.len() < full.len(),
1261 "HookCovered ({}) must be a strict reduction of FULL ({})",
1262 covered.len(),
1263 full.len()
1264 );
1265 }
1266
1267 #[test]
1268 fn hook_covered_shadow_collapses_to_minimal() {
1269 let covered_shadow = render(true, Wrapper::HookCovered, CompressionLevel::Off, &tp());
1272 let dedicated_shadow = render(true, Wrapper::Dedicated, CompressionLevel::Off, &tp());
1273 assert_eq!(covered_shadow, dedicated_shadow);
1274 }
1275
1276 #[test]
1277 fn hook_covered_wraps_compression_in_markers() {
1278 let out = render(
1279 false,
1280 Wrapper::HookCovered,
1281 CompressionLevel::Standard,
1282 &tp(),
1283 );
1284 assert!(out.contains(COMPRESSION_BLOCK_START) && out.contains(COMPRESSION_BLOCK_END));
1285 assert!(out.contains("OUTPUT STYLE: dense"));
1286 }
1287
1288 #[test]
1291 fn rules_only_mention_enabled_tools() {
1292 use super::super::rules_sections;
1293 use super::super::tool_profiles::ToolProfile;
1294 let exclusive_tools = ["ctx_compose", "ctx_callgraph", "ctx_patch"];
1295 for profile in [ToolProfile::Minimal, ToolProfile::Standard] {
1296 let mut sections = vec![
1297 rules_sections::intent_section(&profile),
1298 rules_sections::hook_covered_tools_section(&profile),
1299 rules_sections::shadow_minimal_section(&profile),
1300 rules_sections::anti_section(&profile),
1301 rules_sections::litm_end_section(&profile),
1302 ];
1303 if let Some(fb) = rules_sections::ctx_call_fallback(&profile) {
1304 sections.push(fb);
1305 }
1306 for tool in &exclusive_tools {
1307 if !profile.is_tool_enabled(tool) {
1308 for section in §ions {
1309 assert!(
1310 !section.contains(tool),
1311 "profile {:?} dynamic section must not mention disabled tool {tool}",
1312 profile.as_str()
1313 );
1314 }
1315 }
1316 }
1317 }
1318 }
1319
1320 #[test]
1321 fn minimal_rules_shorter_than_standard() {
1322 use super::super::tool_profiles::ToolProfile;
1323 let min = render(
1324 false,
1325 Wrapper::Dedicated,
1326 CompressionLevel::Off,
1327 &ToolProfile::Minimal,
1328 );
1329 let std = render(
1330 false,
1331 Wrapper::Dedicated,
1332 CompressionLevel::Off,
1333 &ToolProfile::Standard,
1334 );
1335 assert!(
1336 min.len() < std.len(),
1337 "minimal ({}) must be shorter than standard ({})",
1338 min.len(),
1339 std.len()
1340 );
1341 }
1342
1343 #[test]
1344 fn power_profile_output_identical_to_default() {
1345 use super::super::tool_profiles::ToolProfile;
1346 let power = render(
1347 false,
1348 Wrapper::Dedicated,
1349 CompressionLevel::Off,
1350 &ToolProfile::Power,
1351 );
1352 assert!(
1353 power.contains("ctx_compose"),
1354 "Power must include all tools"
1355 );
1356 assert!(
1357 power.contains("ctx_callgraph"),
1358 "Power must include all tools"
1359 );
1360 assert!(
1361 power.contains("ctx_session"),
1362 "Power must include all tools"
1363 );
1364 }
1365
1366 #[test]
1367 fn render_is_deterministic_across_profiles() {
1368 use super::super::tool_profiles::ToolProfile;
1369 for profile in [
1370 ToolProfile::Minimal,
1371 ToolProfile::Standard,
1372 ToolProfile::Power,
1373 ] {
1374 let a = render(false, Wrapper::Dedicated, CompressionLevel::Off, &profile);
1375 let b = render(false, Wrapper::Dedicated, CompressionLevel::Off, &profile);
1376 assert_eq!(
1377 a,
1378 b,
1379 "render must be deterministic for {:?}",
1380 profile.as_str()
1381 );
1382 }
1383 }
1384
1385 #[test]
1386 fn minimal_has_ctx_call_fallback() {
1387 use super::super::tool_profiles::ToolProfile;
1388 let rules = render(
1389 false,
1390 Wrapper::Dedicated,
1391 CompressionLevel::Off,
1392 &ToolProfile::Minimal,
1393 );
1394 assert!(
1395 rules.contains("ctx_call"),
1396 "minimal profile must include ctx_call gateway hint"
1397 );
1398 }
1399
1400 #[test]
1401 fn power_has_no_ctx_call_fallback() {
1402 use super::super::tool_profiles::ToolProfile;
1403 let rules = render(
1404 false,
1405 Wrapper::Dedicated,
1406 CompressionLevel::Off,
1407 &ToolProfile::Power,
1408 );
1409 assert!(
1410 !rules.contains("ctx_call(tool="),
1411 "power profile must not include ctx_call gateway hint"
1412 );
1413 }
1414}