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