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