1use std::collections::HashMap;
19use std::sync::{Arc, Mutex, PoisonError};
20
21use async_trait::async_trait;
22use rhema_core::{
23 Content, EventSink, Message, ModelOutput, ModelProvider, ProviderError, Role, ToolResult,
24 ToolSpec, Usage,
25};
26
27use crate::compact::{self, PendingSummary, Section, SectionOrigin, Summarizer};
28use crate::summary;
29use crate::tree::Range;
30
31const WORKER_CONCURRENCY: usize = 4;
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub struct TranscriptSettings {
39 pub max_view_bytes: usize,
44 pub step_bytes: usize,
48 pub max_section_messages: usize,
53 pub max_block_bytes: usize,
58}
59
60impl Default for TranscriptSettings {
61 fn default() -> Self {
62 Self {
63 max_view_bytes: 256_000,
68 step_bytes: 24_000,
69 max_section_messages: 128,
70 max_block_bytes: 32_000,
71 }
72 }
73}
74
75#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
83pub struct UsageBreakdown {
84 pub system_prompt_tokens: u64,
86 pub skills_tokens: u64,
89 pub tool_calls_input_tokens: u64,
92 pub tool_calls_output_tokens: u64,
94 pub user_messages_tokens: u64,
96 pub model_output_tokens: u64,
99}
100
101impl UsageBreakdown {
102 pub fn labeled(&self) -> [(&'static str, u64); 6] {
104 [
105 ("System Prompt", self.system_prompt_tokens),
106 ("Skills", self.skills_tokens),
107 ("Tool Calls Input", self.tool_calls_input_tokens),
108 ("Tool Calls Output", self.tool_calls_output_tokens),
109 ("User Messages", self.user_messages_tokens),
110 ("Model Output", self.model_output_tokens),
111 ]
112 }
113
114 pub fn total(&self) -> u64 {
116 self.system_prompt_tokens
117 + self.skills_tokens
118 + self.tool_calls_input_tokens
119 + self.tool_calls_output_tokens
120 + self.user_messages_tokens
121 + self.model_output_tokens
122 }
123}
124
125#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
132pub struct LogContent {
133 pub tool_calls: u64,
135 pub tool_results: u64,
137 pub user_text: u64,
139 pub assistant_text: u64,
141}
142
143impl LogContent {
144 pub fn total(&self) -> u64 {
147 self.tool_calls + self.tool_results + self.user_text + self.assistant_text
148 }
149}
150
151#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
158pub struct TranscriptStats {
159 pub requests: u64,
161 pub pass_through: u64,
164 pub viewed: u64,
166 pub flushes: u64,
169 pub consolidations: u64,
172 pub summarizer_calls: u64,
174 pub summarizer_failures: u64,
177 pub log_messages: usize,
179 pub sectioned_messages: usize,
181 pub sections: usize,
183 pub block_bytes: usize,
185 #[serde(default)]
187 pub block_tokens: u64,
188 pub band_bytes: usize,
191 #[serde(default)]
194 pub band_tokens: u64,
195 pub tail_bytes: usize,
197 #[serde(default)]
199 pub tail_tokens: u64,
200 #[serde(default)]
205 pub log_bytes: usize,
206 #[serde(default)]
209 pub log_content: LogContent,
210 pub input_tokens: u64,
213 pub cached_input_tokens: u64,
215 pub output_tokens: u64,
217 pub usage: UsageBreakdown,
219}
220
221impl TranscriptStats {
222 pub fn cache_hit_rate(&self) -> Option<f64> {
226 if self.input_tokens == 0 {
227 None
228 } else {
229 Some(self.cached_input_tokens as f64 / self.input_tokens as f64)
230 }
231 }
232
233 pub fn carry(&mut self, saved: &Self) {
243 self.requests += saved.requests;
244 self.pass_through += saved.pass_through;
245 self.viewed += saved.viewed;
246 self.flushes += saved.flushes;
247 self.consolidations += saved.consolidations;
248 self.summarizer_calls += saved.summarizer_calls;
249 self.summarizer_failures += saved.summarizer_failures;
250 self.input_tokens += saved.input_tokens;
251 self.cached_input_tokens += saved.cached_input_tokens;
252 self.output_tokens += saved.output_tokens;
253 let usage = &mut self.usage;
254 let saved_usage = &saved.usage;
255 usage.system_prompt_tokens += saved_usage.system_prompt_tokens;
256 usage.skills_tokens += saved_usage.skills_tokens;
257 usage.tool_calls_input_tokens += saved_usage.tool_calls_input_tokens;
258 usage.tool_calls_output_tokens += saved_usage.tool_calls_output_tokens;
259 usage.user_messages_tokens += saved_usage.user_messages_tokens;
260 usage.model_output_tokens += saved_usage.model_output_tokens;
261 if self.log_messages == 0 {
262 self.log_messages = saved.log_messages;
263 self.sectioned_messages = saved.sectioned_messages;
264 self.sections = saved.sections;
265 self.block_bytes = saved.block_bytes;
266 self.block_tokens = saved.block_tokens;
267 self.band_bytes = saved.band_bytes;
268 self.band_tokens = saved.band_tokens;
269 self.tail_bytes = saved.tail_bytes;
270 self.tail_tokens = saved.tail_tokens;
271 self.log_bytes = saved.log_bytes;
272 self.log_content = saved.log_content;
273 }
274 }
275}
276
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280pub enum WorkerOutcome {
281 Upgraded,
283 Dropped,
286 Failed,
288}
289
290#[derive(Debug)]
295pub struct Transcript {
296 settings: TranscriptSettings,
297 log: Vec<Message>,
298 sizes: Vec<usize>,
301 tokens: Vec<u64>,
304 total_bytes: usize,
308 total_tokens: u64,
310 content: LogContent,
313 cut: usize,
316 sections: Vec<Section>,
319 skills_bytes: usize,
322 skills: Vec<SkillText>,
325 min_skill_body: usize,
328 reads: Vec<Read>,
330 pinned: HashMap<String, Range>,
335 pending_shares: Shares,
339 stats: TranscriptStats,
340 saved: Option<Vec<Section>>,
345}
346
347#[derive(Debug, Clone, PartialEq, Eq)]
351pub struct SkillText {
352 pub name: String,
354 pub body: String,
356}
357
358#[derive(Debug, Clone, Copy)]
361struct Read {
362 call: usize,
364 result: usize,
366 skill: usize,
368}
369
370const NEEDLE_BYTES: usize = 64;
373
374fn needle(body: &str) -> &str {
377 let mut end = NEEDLE_BYTES.min(body.len());
378 while !body.is_char_boundary(end) {
379 end -= 1;
380 }
381 &body[..end]
382}
383
384#[derive(Debug, Clone, Copy, Default)]
387struct Shares {
388 system_prompt: usize,
389 skills: usize,
390 tool_defs: usize,
391 tool_calls: usize,
392 tool_results: usize,
393 user_text: usize,
394 assistant_text: usize,
395}
396
397fn add_message_content(content: &mut LogContent, message: &Message) {
402 for part in &message.content {
403 match part {
404 Content::Text(text) => match message.role {
405 Role::User => content.user_text += summary::text_tokens(text.len()),
406 Role::Assistant => content.assistant_text += summary::text_tokens(text.len()),
407 Role::System | Role::Tool => {}
408 },
409 Content::ToolCall(call) => {
410 content.tool_calls +=
411 summary::text_tokens(call.name.len() + call.args.to_string().len());
412 }
413 Content::ToolResult(result) => {
414 content.tool_results += summary::text_tokens(result.content.len());
415 content.tool_results += result.images.len() as u64 * summary::IMAGE_TOKENS;
419 }
420 Content::Image(_) => match message.role {
424 Role::User => content.user_text += summary::IMAGE_TOKENS,
425 Role::Assistant => content.assistant_text += summary::IMAGE_TOKENS,
426 Role::System | Role::Tool => {}
427 },
428 }
429 }
430}
431
432impl Shares {
433 fn total(&self) -> usize {
434 self.system_prompt
435 + self.skills
436 + self.tool_defs
437 + self.tool_calls
438 + self.tool_results
439 + self.user_text
440 + self.assistant_text
441 }
442}
443
444impl Transcript {
445 pub fn new(settings: TranscriptSettings) -> Self {
447 Self {
448 settings,
449 log: Vec::new(),
450 sizes: Vec::new(),
451 tokens: Vec::new(),
452 total_bytes: 0,
453 total_tokens: 0,
454 content: LogContent::default(),
455 cut: 0,
456 sections: Vec::new(),
457 skills_bytes: 0,
458 skills: Vec::new(),
459 min_skill_body: usize::MAX,
460 reads: Vec::new(),
461 pinned: HashMap::new(),
462 pending_shares: Shares::default(),
463 stats: TranscriptStats::default(),
464 saved: None,
465 }
466 }
467
468 pub fn observe(&mut self, messages: &[Message]) {
474 if messages.len() >= self.log.len() && messages[..self.log.len()] == self.log[..] {
475 let first = self.log.len();
476 for message in &messages[first..] {
477 let bytes = summary::message_bytes(message);
478 let tokens = summary::message_tokens(message);
479 self.sizes.push(bytes);
480 self.tokens.push(tokens);
481 self.total_bytes += bytes;
482 self.total_tokens += tokens;
483 add_message_content(&mut self.content, message);
484 }
485 self.log.extend_from_slice(&messages[first..]);
486 self.scan_reads(first);
487 } else {
488 self.log = messages.to_vec();
489 self.sizes = Vec::with_capacity(self.log.len());
490 self.tokens = Vec::with_capacity(self.log.len());
491 self.total_bytes = 0;
492 self.total_tokens = 0;
493 self.content = LogContent::default();
494 for index in 0..self.log.len() {
495 let bytes = summary::message_bytes(&self.log[index]);
496 let tokens = summary::message_tokens(&self.log[index]);
497 self.sizes.push(bytes);
498 self.tokens.push(tokens);
499 self.total_bytes += bytes;
500 self.total_tokens += tokens;
501 add_message_content(&mut self.content, &self.log[index]);
502 }
503 self.cut = 0;
504 self.sections.clear();
505 self.reads.clear();
506 self.scan_reads(0);
507 }
508 if let Some(saved) = self.saved.take() {
516 let mut end = 0usize;
517 let tiles = !saved.is_empty()
521 && saved.iter().all(|section| {
522 match section.range.id.checked_add(section.range.n) {
523 Some(next) if section.range.id == end => {
524 end = next;
525 end <= self.log.len()
526 }
527 _ => false,
528 }
529 })
530 && end <= self.log.len();
531 if tiles {
532 self.sections = saved;
533 self.cut = end;
534 }
535 }
536 self.pinned = self
542 .sections
543 .iter()
544 .flat_map(|section| {
545 section
546 .pinned
547 .iter()
548 .map(|name| (name.clone(), section.range))
549 })
550 .collect();
551 }
552
553 pub fn len(&self) -> usize {
555 self.log.len()
556 }
557
558 pub fn is_empty(&self) -> bool {
560 self.log.is_empty()
561 }
562
563 pub fn message(&self, id: usize) -> Option<&Message> {
565 self.log.get(id)
566 }
567
568 pub fn range(&self, range: Range) -> Option<&[Message]> {
573 let end = range.id.checked_add(range.n)?;
574 self.log.get(range.id..end)
575 }
576
577 pub fn stats(&self) -> TranscriptStats {
579 self.stats
580 }
581
582 pub fn carry(&mut self, saved: &TranscriptStats) {
586 self.stats.carry(saved);
587 }
588
589 pub fn saved_sections(&self) -> Vec<Section> {
592 self.sections.clone()
593 }
594
595 pub fn adopt_sections(&mut self, sections: Vec<Section>) {
599 self.saved = Some(sections);
600 }
601
602 pub fn reset_stats(&mut self) {
606 self.stats = TranscriptStats::default();
607 }
608
609 pub fn set_skills_bytes(&mut self, bytes: usize) {
614 self.skills_bytes = bytes;
615 }
616
617 pub fn set_skills(&mut self, skills: Vec<SkillText>) {
624 self.skills = skills;
625 self.min_skill_body = self
626 .skills
627 .iter()
628 .map(|skill| skill.body.len())
629 .min()
630 .unwrap_or(usize::MAX);
631 self.reads.clear();
632 self.scan_reads(0);
633 }
634
635 fn carried_skill(&self, result: &ToolResult) -> Option<usize> {
642 if result.content.len() < self.min_skill_body {
643 return None;
644 }
645 self.skills.iter().position(|skill| {
646 result.content.len() >= skill.body.len()
647 && result.content.contains(needle(&skill.body))
648 && result.content.contains(&skill.body)
649 })
650 }
651
652 fn scan_reads(&mut self, from: usize) {
659 for index in from..self.log.len() {
660 if self.log[index].role != Role::Tool {
661 continue;
662 }
663 for part in &self.log[index].content {
664 let Content::ToolResult(result) = part else {
665 continue;
666 };
667 let Some(skill) = self.carried_skill(result) else {
668 continue;
669 };
670 let calls = || {
675 self.log[index - 1]
676 .content
677 .iter()
678 .filter_map(|part| match part {
679 Content::ToolCall(call) => Some(call),
680 _ => None,
681 })
682 };
683 let paired = index > 0
684 && self.log[index - 1].role == Role::Assistant
685 && match (calls().next(), calls().nth(1)) {
686 (Some(call), None) => call.id == result.id,
687 _ => false,
688 };
689 if paired {
690 self.reads.push(Read {
691 call: index - 1,
692 result: index,
693 skill,
694 });
695 break;
696 }
697 }
698 }
699 }
700
701 fn read_starting(&self, index: usize) -> Option<Read> {
703 let at = self.reads.partition_point(|read| read.call < index);
704 self.reads
705 .get(at)
706 .copied()
707 .filter(|read| read.call == index)
708 }
709
710 pub fn stage_usage_shares(
715 &mut self,
716 system: Option<&str>,
717 tools: &[ToolSpec],
718 messages: &[Message],
719 ) {
720 let mut shares = Shares::default();
721 if let Some(system) = system {
722 let skills = self.skills_bytes.min(system.len());
723 shares.skills = skills;
724 shares.system_prompt = system.len() - skills;
725 }
726 for spec in tools {
729 shares.tool_defs +=
730 spec.name.len() + spec.description.len() + spec.parameters.to_string().len();
731 }
732 for message in messages {
733 for content in &message.content {
734 match content {
735 Content::Text(text) => match message.role {
736 Role::User => shares.user_text += text.len(),
737 Role::Assistant => shares.assistant_text += text.len(),
738 Role::System | Role::Tool => {}
739 },
740 Content::ToolCall(call) => {
741 shares.tool_calls += call.name.len() + call.args.to_string().len();
742 }
743 Content::ToolResult(result) => {
744 shares.tool_results += result.content.len();
745 shares.tool_results += result.images.len() * summary::IMAGE_BYTES;
748 }
749 Content::Image(_) => {}
752 }
753 }
754 }
755 self.pending_shares = shares;
756 }
757
758 pub fn record_usage(&mut self, usage: &Usage) {
763 self.stats.input_tokens += u64::from(usage.input_tokens);
764 self.stats.cached_input_tokens += u64::from(usage.cached_input_tokens);
765 self.stats.output_tokens += u64::from(usage.output_tokens);
766 let shares = std::mem::take(&mut self.pending_shares);
767 let total = shares.total();
768 let input = u64::from(usage.input_tokens);
769 if total > 0 && input > 0 {
770 let spread = |bytes: usize| input * bytes as u64 / total as u64;
771 let breakdown = &mut self.stats.usage;
772 breakdown.system_prompt_tokens += spread(shares.system_prompt);
773 breakdown.skills_tokens += spread(shares.skills);
774 breakdown.tool_calls_input_tokens += spread(shares.tool_defs + shares.tool_calls);
775 breakdown.tool_calls_output_tokens += spread(shares.tool_results);
776 breakdown.user_messages_tokens += spread(shares.user_text);
777 breakdown.model_output_tokens += spread(shares.assistant_text);
778 }
779 self.stats.usage.model_output_tokens += u64::from(usage.output_tokens);
780 }
781
782 pub fn record_worker_call(&mut self, outcome: WorkerOutcome) {
786 self.stats.summarizer_calls += 1;
787 if outcome == WorkerOutcome::Failed {
788 self.stats.summarizer_failures += 1;
789 }
790 }
791
792 pub fn commit_summary(&mut self, pending: &PendingSummary, text: String) -> bool {
797 let index = match self.sections.get(pending.section) {
807 Some(section) if section.range == pending.range => pending.section,
808 _ => match self
809 .sections
810 .iter()
811 .position(|section| section.range == pending.range)
812 {
813 Some(index) => index,
814 None => return false,
815 },
816 };
817 let section = &mut self.sections[index];
818 let mut text = compact::cap_summary(text);
819 for name in §ion.pinned {
822 if let Some(skill) = self.skills.iter().find(|skill| &skill.name == name) {
823 text.push_str("\n\n");
824 text.push_str(&compact::skill_section_text(name, &skill.body));
825 }
826 }
827 section.text = text;
828 section.origin = SectionOrigin::Model;
829 true
830 }
831
832 pub fn plan_flush(&mut self) -> Vec<PendingSummary> {
841 self.sync_sizes();
842 let len = self.log.len();
843 if self.total_bytes <= self.settings.max_view_bytes {
844 return Vec::new();
845 }
846 let tail_start = self.tail_index();
847 let tail_bytes = self.bytes(tail_start, len);
848 let allowance = self.settings.max_view_bytes.saturating_sub(tail_bytes);
849
850 let mut c_min = tail_start;
854 let mut budget = allowance;
855 while c_min > self.cut {
856 let cost = self.sizes[c_min - 1];
857 if cost > budget {
858 break;
859 }
860 budget -= cost;
861 c_min -= 1;
862 }
863 let mut pending = Vec::new();
864 if c_min > self.cut {
865 let half = allowance / 2;
870 let mut c_new = c_min;
871 let mut band = self.bytes(c_new, tail_start);
872 while c_new < tail_start && band > half {
877 band -= self.sizes[c_new];
878 c_new += 1;
879 }
880 while c_new < tail_start && self.log[c_new].role == Role::Tool {
884 c_new += 1;
885 }
886 if c_new > self.cut {
887 pending = self.extend_sections(self.cut, c_new);
888 self.cut = c_new;
889 self.stats.flushes += 1;
890 pending.extend(self.consolidate());
891 }
892 }
893 pending
894 }
895
896 pub fn view(&mut self, messages: &[Message]) -> Option<Vec<Message>> {
905 self.observe(messages);
906 self.plan_flush();
907 self.render()
908 }
909
910 pub fn render(&mut self) -> Option<Vec<Message>> {
914 self.stats.requests += 1;
915 self.stats.log_bytes = self.total_bytes;
916 self.stats.log_content = self.content;
917 if self.cut == 0 {
918 self.stats.pass_through += 1;
919 return None;
920 }
921 let len = self.log.len();
922 let tail_start = self.tail_index();
923 self.stats.log_messages = len;
924 self.stats.sectioned_messages = self.cut;
925 self.stats.sections = self.sections.len();
926 self.stats.block_bytes = self.block_bytes();
927 self.stats.block_tokens = summary::text_tokens(self.stats.block_bytes);
928 self.stats.band_bytes = self.bytes(self.cut, len);
929 self.stats.band_tokens = self.tokens_between(self.cut, len);
930 self.stats.tail_bytes = self.bytes(tail_start, len);
931 self.stats.tail_tokens = self.tokens_between(tail_start, len);
932 self.stats.viewed += 1;
933
934 let mut text = String::from(
935 "<transcript>\n\
936 The blocks below cover this conversation's older messages,\n\
937 oldest first. Each block is headed `id+n|`: the n messages\n\
938 from index id on, condensed. zoom(id, n) returns those n\n\
939 messages whole; long output is cut and the note names the\n\
940 `at` to resume at. The messages after the blocks are\n\
941 recent; they are whole.\n\n",
942 );
943 for section in &self.sections {
944 text.push_str(&format!(
945 "{}+{}|\n{}\n\n",
946 section.range.id, section.range.n, section.text
947 ));
948 }
949 text.push_str("</transcript>");
950 let mut out = Vec::with_capacity(len - self.cut + 1);
951 out.push(Message::text(Role::User, text));
952 out.extend(self.log[self.cut..].iter().cloned());
953 Some(out)
954 }
955
956 fn tail_index(&self) -> usize {
961 let user = self
962 .log
963 .iter()
964 .rposition(|message| message.role == Role::User)
965 .unwrap_or(self.log.len());
966 user.max(self.cut)
967 }
968
969 fn bytes(&self, from: usize, to: usize) -> usize {
971 self.sizes[from..to].iter().sum()
972 }
973
974 fn tokens_between(&self, from: usize, to: usize) -> u64 {
976 self.tokens[from..to].iter().sum()
977 }
978
979 fn block_bytes(&self) -> usize {
981 self.sections.iter().map(Section::view_bytes).sum()
982 }
983
984 fn sync_sizes(&mut self) {
988 self.sizes.truncate(self.log.len());
989 self.tokens.truncate(self.log.len());
990 let mut patched = false;
991 while self.sizes.len() < self.log.len() {
992 let id = self.sizes.len();
993 self.sizes.push(summary::message_bytes(&self.log[id]));
994 self.tokens.push(summary::message_tokens(&self.log[id]));
995 patched = true;
996 }
997 if patched {
998 self.total_bytes = self.sizes.iter().sum();
999 self.total_tokens = self.tokens.iter().sum();
1000 self.content = LogContent::default();
1001 for message in &self.log {
1002 add_message_content(&mut self.content, message);
1003 }
1004 }
1005 }
1006
1007 fn extend_sections(&mut self, start: usize, end: usize) -> Vec<PendingSummary> {
1012 let mut pending = Vec::new();
1013 let mut at = start;
1014 while at < end {
1015 if let Some(read) = self.read_starting(at) {
1021 let range = Range {
1022 id: at,
1023 n: read.result + 1 - at,
1024 };
1025 let name = self.skills[read.skill].name.clone();
1026 let section = match self.pinned.get(&name) {
1027 Some(carried) => Section {
1028 range,
1029 text: compact::skill_pointer_text(&name, *carried),
1030 origin: SectionOrigin::Extractive,
1031 pinned: Vec::new(),
1032 },
1033 None => {
1034 self.pinned.insert(name.clone(), range);
1035 let body = self.skills[read.skill].body.clone();
1036 Section {
1037 range,
1038 text: compact::skill_section_text(&name, &body),
1039 origin: SectionOrigin::Extractive,
1040 pinned: vec![name],
1041 }
1042 }
1043 };
1044 self.sections.push(section);
1045 at = read.result + 1;
1046 continue;
1047 }
1048 let mut stop = at;
1049 let mut bytes = 0usize;
1050 let mut count = 0usize;
1051 while stop < end {
1052 let cost = self.sizes[stop];
1053 if count > 0
1054 && (bytes + cost > self.settings.step_bytes
1055 || count >= self.settings.max_section_messages)
1056 {
1057 break;
1058 }
1059 if count > 0 && self.read_starting(stop).is_some() {
1062 break;
1063 }
1064 bytes += cost;
1065 count += 1;
1066 stop += 1;
1067 }
1068 while stop < end && self.log[stop].role == Role::Tool {
1069 stop += 1;
1070 }
1071 let range = Range {
1072 id: at,
1073 n: stop - at,
1074 };
1075 let messages = self.log[at..stop].to_vec();
1076 let text = compact::section_digest(&messages);
1077 let context = self.sections.last().map(|s| s.text.clone());
1081 self.sections.push(Section {
1082 range,
1083 text,
1084 origin: SectionOrigin::Extractive,
1085 pinned: Vec::new(),
1086 });
1087 pending.push(PendingSummary {
1088 section: self.sections.len() - 1,
1089 range,
1090 messages,
1091 context,
1092 });
1093 at = stop;
1094 }
1095 pending
1096 }
1097
1098 fn consolidate(&mut self) -> Vec<PendingSummary> {
1105 let mut pending = Vec::new();
1106 while self.sections.len() >= 2 && self.block_bytes() > self.settings.max_block_bytes {
1107 let range = Range {
1108 id: self.sections[0].range.id,
1109 n: self.sections[0].range.n + self.sections[1].range.n,
1110 };
1111 let messages = match range
1112 .id
1113 .checked_add(range.n)
1114 .and_then(|end| self.log.get(range.id..end))
1115 {
1116 Some(messages) => messages.to_vec(),
1117 None => return pending,
1121 };
1122 let mut text = compact::section_digest(&messages);
1123 let mut pinned: Vec<String> = Vec::new();
1128 for old in [&self.sections[0], &self.sections[1]] {
1129 for name in &old.pinned {
1130 if pinned.contains(name) {
1131 continue;
1132 }
1133 if let Some(skill) = self.skills.iter().find(|skill| &skill.name == name) {
1141 text.push_str("\n\n");
1142 text.push_str(&compact::skill_section_text(name, &skill.body));
1143 pinned.push(name.clone());
1144 }
1145 }
1146 }
1147 self.sections.drain(..2);
1148 self.sections.insert(
1149 0,
1150 Section {
1151 range,
1152 text,
1153 origin: SectionOrigin::Extractive,
1154 pinned,
1155 },
1156 );
1157 pending.push(PendingSummary {
1160 section: 0,
1161 range,
1162 messages,
1163 context: None,
1164 });
1165 self.stats.consolidations += 1;
1166 }
1167 pending
1168 }
1169}
1170
1171pub struct TranscriptView {
1178 inner: Arc<dyn ModelProvider>,
1179 transcript: Arc<Mutex<Transcript>>,
1180 summarizer: Option<Arc<dyn Summarizer>>,
1181}
1182
1183impl TranscriptView {
1184 pub fn new(inner: Arc<dyn ModelProvider>, transcript: Arc<Mutex<Transcript>>) -> Self {
1189 Self {
1190 inner,
1191 transcript,
1192 summarizer: None,
1193 }
1194 }
1195
1196 pub fn with_summarizer(
1200 inner: Arc<dyn ModelProvider>,
1201 transcript: Arc<Mutex<Transcript>>,
1202 summarizer: Arc<dyn Summarizer>,
1203 ) -> Self {
1204 Self {
1205 inner,
1206 transcript,
1207 summarizer: Some(summarizer),
1208 }
1209 }
1210}
1211
1212impl std::fmt::Debug for TranscriptView {
1213 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1214 f.debug_struct("TranscriptView").finish_non_exhaustive()
1216 }
1217}
1218
1219#[async_trait]
1220impl ModelProvider for TranscriptView {
1221 async fn complete(
1222 &self,
1223 mut req: rhema_core::ModelRequest,
1224 sink: &mut dyn EventSink,
1225 ) -> Result<ModelOutput, ProviderError> {
1226 let pending = {
1229 let mut transcript = self
1230 .transcript
1231 .lock()
1232 .unwrap_or_else(PoisonError::into_inner);
1233 transcript.observe(&req.messages);
1234 transcript.plan_flush()
1235 };
1236 if let Some(worker) = &self.summarizer
1242 && !pending.is_empty()
1243 {
1244 Self::spawn_worker_fill(Arc::clone(worker), Arc::clone(&self.transcript), pending);
1245 }
1246 let view = {
1247 let mut transcript = self
1248 .transcript
1249 .lock()
1250 .unwrap_or_else(PoisonError::into_inner);
1251 transcript.render()
1252 };
1253 if let Some(messages) = view {
1254 req.messages = messages;
1255 }
1256 {
1257 let mut transcript = self
1258 .transcript
1259 .lock()
1260 .unwrap_or_else(PoisonError::into_inner);
1261 transcript.stage_usage_shares(req.system.as_deref(), &req.tools, &req.messages);
1262 }
1263 let result = self.inner.complete(req, sink).await;
1264 if let Ok(output) = &result {
1265 let mut transcript = self
1266 .transcript
1267 .lock()
1268 .unwrap_or_else(PoisonError::into_inner);
1269 transcript.record_usage(&output.usage);
1270 }
1271 result
1272 }
1273}
1274
1275impl TranscriptView {
1276 fn spawn_worker_fill(
1284 worker: Arc<dyn Summarizer>,
1285 mirror: Arc<Mutex<Transcript>>,
1286 pending: Vec<PendingSummary>,
1287 ) {
1288 tokio::spawn(async move {
1289 for chunk in pending.chunks(WORKER_CONCURRENCY) {
1290 let mut fills = Vec::with_capacity(chunk.len());
1291 for item in chunk {
1292 let worker = Arc::clone(&worker);
1293 let messages = item.messages.clone();
1294 let context = item.context.clone();
1295 let section = item.section;
1296 let range = item.range;
1297 fills.push(tokio::spawn(async move {
1298 (
1299 worker.summarize(&messages, context.as_deref()).await,
1300 section,
1301 range,
1302 )
1303 }));
1304 }
1305 for fill in fills {
1306 let outcome = match fill.await {
1310 Ok((Ok(text), section, range)) => Some((text, section, range)),
1311 _ => None,
1312 };
1313 let mut transcript = mirror.lock().unwrap_or_else(PoisonError::into_inner);
1314 match outcome {
1315 Some((text, section, range)) => {
1316 let pending = PendingSummary {
1319 section,
1320 range,
1321 messages: Vec::new(),
1322 context: None,
1323 };
1324 let upgraded = transcript.commit_summary(&pending, text);
1325 transcript.record_worker_call(match upgraded {
1326 true => WorkerOutcome::Upgraded,
1327 false => WorkerOutcome::Dropped,
1328 });
1329 }
1330 None => transcript.record_worker_call(WorkerOutcome::Failed),
1331 }
1332 }
1333 }
1334 });
1335 }
1336}
1337
1338#[cfg(test)]
1339mod tests {
1340 use super::*;
1341 use rhema_core::{Content, ToolCall, ToolResult};
1342 use std::collections::HashSet;
1343 use std::sync::Mutex as StdMutex;
1344 use std::sync::atomic::{AtomicBool, Ordering};
1345
1346 async fn wait_for(done: impl Fn() -> bool) {
1349 for _ in 0..10_000 {
1350 if done() {
1351 return;
1352 }
1353 tokio::task::yield_now().await;
1354 }
1355 panic!("the background fill never finished");
1356 }
1357
1358 fn result_bytes(kb: usize) -> String {
1360 "x".repeat(kb * 1024)
1361 }
1362
1363 fn call_round(id: &str, result_kb: usize) -> Vec<Message> {
1364 vec![
1365 Message {
1366 annotations: Default::default(),
1367 role: Role::Assistant,
1368 content: vec![
1369 Content::Text("checking".into()),
1370 Content::ToolCall(ToolCall {
1371 id: id.into(),
1372 name: "bash".into(),
1373 args: serde_json::json!({ "command": "make test" }),
1374 provider_data: serde_json::Value::Null,
1375 }),
1376 ],
1377 },
1378 Message {
1379 annotations: Default::default(),
1380 role: Role::Tool,
1381 content: vec![Content::ToolResult(ToolResult::success(
1382 id,
1383 result_bytes(result_kb),
1384 ))],
1385 },
1386 ]
1387 }
1388
1389 fn long_history(rounds: usize) -> Vec<Message> {
1392 let mut messages = vec![Message::text(Role::User, "fix the build")];
1393 for i in 0..rounds {
1394 messages.extend(call_round(&format!("c{i}"), 8));
1395 }
1396 messages.push(Message::text(Role::User, "and now summarize"));
1397 messages
1398 }
1399
1400 fn settings(max_view_bytes: usize) -> TranscriptSettings {
1401 TranscriptSettings {
1402 max_view_bytes,
1403 ..TranscriptSettings::default()
1404 }
1405 }
1406
1407 #[test]
1408 fn below_the_budget_the_view_is_none() {
1409 let mut transcript = Transcript::new(settings(128_000));
1410 let messages = long_history(4); assert!(transcript.view(&messages).is_none());
1412 let stats = transcript.stats();
1413 assert_eq!(stats.requests, 1);
1414 assert_eq!(stats.pass_through, 1);
1415 assert_eq!(stats.viewed, 0);
1416 }
1417
1418 #[test]
1419 fn past_the_budget_the_aged_prefix_is_block_and_the_tail_whole() {
1420 let mut transcript = Transcript::new(settings(128_000));
1421 let messages = long_history(30); let view = transcript.view(&messages).unwrap();
1423
1424 assert_eq!(view[0].role, Role::User);
1427 let rhema_core::Content::Text(text) = &view[0].content[0] else {
1428 panic!("text view message");
1429 };
1430 assert!(text.starts_with("<transcript>"), "{text}");
1431 assert!(text.contains("zoom(id, n)"), "{text}");
1432 assert!(text.contains("0+"), "{text}");
1434
1435 let last = view.last().unwrap();
1437 assert_eq!(*last, Message::text(Role::User, "and now summarize"));
1438 assert!(view.len() < messages.len(), "the view is shorter");
1439
1440 let stats = transcript.stats();
1441 assert_eq!(stats.flushes, 1);
1442 assert_eq!(stats.sectioned_messages, transcript.cut);
1443 assert!(stats.block_bytes > 0);
1444 assert!(stats.band_bytes + stats.block_bytes < 245 * 1024);
1445 assert!(stats.block_tokens > 0);
1447 assert!(stats.band_tokens > 0);
1448 assert!(stats.tail_tokens <= stats.band_tokens);
1449 }
1450
1451 #[test]
1452 fn between_flushes_the_block_is_append_only() {
1453 let mut transcript = Transcript::new(settings(40_000));
1454 let first = long_history(5); let view = transcript.view(&first).unwrap();
1456 let first_block = match &view[0].content[..] {
1457 [rhema_core::Content::Text(text)] => text.clone(),
1458 _ => panic!("text view message"),
1459 };
1460 let sections_after_first = transcript.sections.clone();
1461
1462 let mut second = first.clone();
1465 second.extend(call_round("c5", 1));
1466 second.push(Message::text(Role::User, "next"));
1467 let view = transcript.view(&second).unwrap();
1468 let second_block = match &view[0].content[..] {
1469 [rhema_core::Content::Text(text)] => text.clone(),
1470 _ => panic!("text view message"),
1471 };
1472 assert_eq!(transcript.stats.flushes, 1, "no second flush");
1473 assert_eq!(transcript.sections, sections_after_first);
1474 assert_eq!(first_block, second_block, "the block is byte-identical");
1475 assert!(view.len() > 1);
1476 }
1477
1478 #[test]
1479 fn a_flush_overshoots_to_half_the_allowance_and_the_hysteresis_holds() {
1480 let mut transcript = Transcript::new(settings(128_000));
1481 let mut messages = vec![Message::text(Role::User, "fix the build")];
1482 for i in 0..20 {
1483 messages.extend(call_round(&format!("c{i}"), 8)); }
1485 messages.push(Message::text(Role::User, "go on"));
1486 assert!(transcript.view(&messages).is_some());
1487 let stats = transcript.stats();
1488 assert_eq!(stats.flushes, 1);
1489 let allowance = 128_000 - stats.tail_bytes;
1492 let band = stats.band_bytes - stats.tail_bytes;
1493 assert!(
1494 band <= allowance / 2,
1495 "band {band} over half the allowance {}",
1496 allowance / 2
1497 );
1498 let mut grown = messages.clone();
1501 for i in 20..26 {
1502 grown.extend(call_round(&format!("c{i}"), 8)); }
1504 grown.push(Message::text(Role::User, "still going"));
1505 transcript.view(&grown);
1506 assert_eq!(transcript.stats.flushes, 1, "flushed inside the hysteresis");
1507 }
1508
1509 #[test]
1510 fn a_flush_never_splits_a_tool_round_at_a_section_boundary() {
1511 let mut transcript = Transcript::new(settings(20_000));
1512 let messages = vec![Message::text(Role::User, "go")]
1514 .into_iter()
1515 .chain(call_round("c0", 16))
1516 .chain(call_round("c1", 16))
1517 .chain(std::iter::once(Message::text(Role::User, "done")))
1518 .collect::<Vec<_>>();
1519 let view = transcript.view(&messages).unwrap();
1520 let carried_calls: HashSet<String> = view
1523 .iter()
1524 .flat_map(|m| &m.content)
1525 .filter_map(|c| match c {
1526 rhema_core::Content::ToolCall(call) => Some(call.id.clone()),
1527 _ => None,
1528 })
1529 .collect();
1530 for message in &view {
1531 for content in &message.content {
1532 if let rhema_core::Content::ToolResult(result) = content {
1533 assert!(
1534 carried_calls.contains(&result.id),
1535 "orphan result {} in the view",
1536 result.id
1537 );
1538 }
1539 }
1540 }
1541 for section in &transcript.sections {
1545 let first = transcript
1546 .range(section.range)
1547 .expect("section in the log")
1548 .first()
1549 .unwrap();
1550 assert_ne!(first.role, Role::Tool, "section {:?}", section.range);
1551 }
1552 }
1553
1554 #[test]
1555 fn sections_respect_the_step_and_message_bounds() {
1556 let mut transcript = Transcript::new(TranscriptSettings {
1557 step_bytes: 20_000,
1558 max_section_messages: 3,
1559 ..settings(20_000)
1560 });
1561 let messages = long_history(8);
1562 transcript.observe(&messages);
1563 transcript.plan_flush();
1564 assert!(transcript.sections.len() > 1, "bounds force a split");
1565 for section in &transcript.sections {
1566 assert!(section.range.n <= 4, "{:?}", section.range);
1567 }
1568 let mut at = 0;
1570 for section in &transcript.sections {
1571 assert_eq!(section.range.id, at);
1572 at += section.range.n;
1573 }
1574 assert_eq!(at, transcript.cut);
1575 }
1576
1577 #[test]
1578 fn a_worker_upgrade_lands_and_a_wrong_one_is_rejected() {
1579 let mut transcript = Transcript::new(settings(20_000));
1580 let messages = long_history(30);
1581 transcript.observe(&messages);
1582 let pending = transcript.plan_flush();
1583 assert!(!pending.is_empty());
1584
1585 let good = pending[0].clone();
1586 assert!(transcript.commit_summary(&good, "## Goals Met\n- all".into()));
1587 assert_eq!(transcript.sections[0].text, "## Goals Met\n- all");
1588 assert_eq!(transcript.sections[0].origin, SectionOrigin::Model);
1589
1590 let stale = PendingSummary {
1593 section: pending[0].section,
1594 range: Range { id: 999, n: 1 },
1595 messages: Vec::new(),
1596 context: None,
1597 };
1598 assert!(!transcript.commit_summary(&stale, "ghost".into()));
1599 assert_eq!(transcript.sections[0].text, "## Goals Met\n- all");
1600 }
1601
1602 #[test]
1603 fn a_resume_adopts_the_saved_sections_and_skips_the_refill() {
1604 let log = long_history(30);
1605 let mut first = Transcript::new(settings(20_000));
1607 first.observe(&log);
1608 let pending = first.plan_flush();
1609 assert!(!pending.is_empty());
1610 for item in &pending {
1611 assert!(first.commit_summary(item, format!("## Goals Met\n- model {}", item.section)));
1612 }
1613 let saved = first.saved_sections();
1614 assert!(saved.iter().all(|s| s.origin == SectionOrigin::Model));
1615
1616 let mut second = Transcript::new(settings(20_000));
1619 second.adopt_sections(saved.clone());
1620 second.observe(&log);
1621 assert_eq!(second.cut, first.cut);
1622 assert_eq!(second.sections, saved);
1623 assert!(second.plan_flush().is_empty());
1625
1626 let mut extended = log.clone();
1628 extended.push(Message::text(Role::User, "one more"));
1629 second.observe(&extended);
1630 let view = second.render().unwrap();
1631 assert_eq!(view.last(), Some(&Message::text(Role::User, "one more")));
1632 }
1633
1634 fn skill_body(name: &str, rules: usize) -> String {
1638 let mut body = format!("---\nname: {name}\ndescription: the {name} trigger\n---\n\n");
1639 for i in 0..rules {
1640 body.push_str(&format!("Rule {i}: do the {name} thing.\n"));
1641 }
1642 body
1643 }
1644
1645 fn cat_result(id: &str, stdout: &str) -> Message {
1649 Message {
1650 annotations: Default::default(),
1651 role: Role::Tool,
1652 content: vec![Content::ToolResult(ToolResult::success(
1653 id,
1654 format!("exit code 0\n--- stdout ---\n{stdout}\n--- stderr ---\n"),
1655 ))],
1656 }
1657 }
1658
1659 fn skill_round(id: &str, name: &str, rules: usize) -> Vec<Message> {
1661 let body = skill_body(name, rules);
1662 vec![
1663 Message {
1664 annotations: Default::default(),
1665 role: Role::Assistant,
1666 content: vec![
1667 Content::Text("loading the skill".into()),
1668 Content::ToolCall(ToolCall {
1669 id: id.into(),
1670 name: "bash".into(),
1671 args: serde_json::json!({
1672 "command": format!("cat .rhema/skills/{name}/SKILL.md")
1673 }),
1674 provider_data: serde_json::Value::Null,
1675 }),
1676 ],
1677 },
1678 cat_result(id, &body),
1679 ]
1680 }
1681
1682 #[test]
1683 fn a_flushed_skill_read_rides_the_block_whole_and_unsummarized() {
1684 let mut transcript = Transcript::new(settings(40_000));
1685 transcript.set_skills(vec![SkillText {
1686 name: "unslop".into(),
1687 body: skill_body("unslop", 40),
1688 }]);
1689 let mut messages = vec![Message::text(Role::User, "fix the build")];
1690 messages.extend(skill_round("s1", "unslop", 40));
1691 messages.extend(long_history(6));
1692 messages.push(Message::text(Role::User, "and now summarize"));
1693
1694 transcript.observe(&messages);
1695 let pending = transcript.plan_flush();
1696 let body = skill_body("unslop", 40);
1697
1698 let pinned = transcript
1702 .sections
1703 .iter()
1704 .find(|section| !section.pinned.is_empty())
1705 .expect("one pinned section");
1706 assert_eq!(pinned.pinned, ["unslop"]);
1707 assert_eq!(pinned.range.n, 2);
1708 assert!(pinned.text.contains(&body), "{}", pinned.text);
1709 assert!(!pending.iter().any(|summary| summary.range == pinned.range));
1710
1711 let view = transcript.render().unwrap();
1714 let rhema_core::Content::Text(text) = &view[0].content[0] else {
1715 panic!("text view message");
1716 };
1717 assert!(text.contains(&body), "{text}");
1718 }
1719
1720 #[test]
1721 fn a_reread_compacts_to_a_pointer_at_the_first_copy() {
1722 let mut transcript = Transcript::new(settings(40_000));
1723 transcript.set_skills(vec![SkillText {
1724 name: "unslop".into(),
1725 body: skill_body("unslop", 40),
1726 }]);
1727 let mut messages = vec![Message::text(Role::User, "fix the build")];
1728 messages.extend(skill_round("s1", "unslop", 40));
1729 messages.extend(skill_round("s2", "unslop", 40));
1730 messages.extend(long_history(6));
1731 messages.push(Message::text(Role::User, "and now summarize"));
1732
1733 transcript.observe(&messages);
1734 transcript.plan_flush();
1735
1736 let pinned: Vec<_> = transcript
1737 .sections
1738 .iter()
1739 .filter(|section| !section.pinned.is_empty())
1740 .collect();
1741 assert_eq!(pinned.len(), 1, "one carrier");
1742 let carried = pinned[0].range;
1743 let body = skill_body("unslop", 40);
1744 let view = transcript.render().unwrap();
1745 let rhema_core::Content::Text(text) = &view[0].content[0] else {
1746 panic!("text view message");
1747 };
1748 assert_eq!(text.matches(&body).count(), 1, "one copy of the body");
1749 assert!(
1750 text.contains(&format!(
1751 "skill unslop read again; its whole text is carried at {}+{}|",
1752 carried.id, carried.n
1753 )),
1754 "{text}"
1755 );
1756 }
1757
1758 #[test]
1759 fn a_multicall_turn_digests_normally_without_a_pin() {
1760 let mut transcript = Transcript::new(settings(40_000));
1761 transcript.set_skills(vec![SkillText {
1762 name: "unslop".into(),
1763 body: skill_body("unslop", 40),
1764 }]);
1765 let mut messages = vec![Message::text(Role::User, "fix the build")];
1766 messages.push(Message {
1769 annotations: Default::default(),
1770 role: Role::Assistant,
1771 content: vec![
1772 Content::ToolCall(ToolCall {
1773 id: "a".into(),
1774 name: "bash".into(),
1775 args: serde_json::json!({ "command": "cat the skill" }),
1776 provider_data: serde_json::Value::Null,
1777 }),
1778 Content::ToolCall(ToolCall {
1779 id: "b".into(),
1780 name: "bash".into(),
1781 args: serde_json::json!({ "command": "make test" }),
1782 provider_data: serde_json::Value::Null,
1783 }),
1784 ],
1785 });
1786 messages.push(cat_result("a", &skill_body("unslop", 40)));
1787 messages.push(cat_result("b", "ok"));
1788 messages.extend(long_history(6));
1789 messages.push(Message::text(Role::User, "and now summarize"));
1790
1791 transcript.observe(&messages);
1792 transcript.plan_flush();
1793 assert!(
1794 transcript.sections.iter().all(|s| s.pinned.is_empty()),
1795 "{:?}",
1796 transcript.sections
1797 );
1798 }
1799
1800 #[test]
1801 fn consolidation_keeps_the_pinned_body_in_the_block() {
1802 let mut transcript = Transcript::new(TranscriptSettings {
1803 max_view_bytes: 40_000,
1804 step_bytes: 4_000,
1805 max_block_bytes: 1_000,
1806 ..TranscriptSettings::default()
1807 });
1808 transcript.set_skills(vec![SkillText {
1809 name: "unslop".into(),
1810 body: skill_body("unslop", 40),
1811 }]);
1812 let mut messages = vec![Message::text(Role::User, "fix the build")];
1813 messages.extend(skill_round("s1", "unslop", 40));
1814 messages.extend(long_history(30));
1815 messages.push(Message::text(Role::User, "and now summarize"));
1816
1817 transcript.observe(&messages);
1818 transcript.plan_flush();
1819 let body = skill_body("unslop", 40);
1820 assert!(
1821 transcript.stats.consolidations > 0,
1822 "the fixture must consolidate"
1823 );
1824 let view = transcript.render().unwrap();
1825 let rhema_core::Content::Text(text) = &view[0].content[0] else {
1826 panic!("text view message");
1827 };
1828 assert!(text.contains(&body), "{text}");
1829 }
1830
1831 #[test]
1832 fn the_model_fill_leaves_the_pinned_body_beneath_it() {
1833 let mut transcript = Transcript::new(TranscriptSettings {
1834 max_view_bytes: 40_000,
1835 step_bytes: 4_000,
1836 max_block_bytes: 1_000,
1837 ..TranscriptSettings::default()
1838 });
1839 transcript.set_skills(vec![SkillText {
1840 name: "unslop".into(),
1841 body: skill_body("unslop", 40),
1842 }]);
1843 let mut messages = vec![Message::text(Role::User, "fix the build")];
1844 messages.extend(skill_round("s1", "unslop", 40));
1845 messages.extend(long_history(30));
1846 messages.push(Message::text(Role::User, "and now summarize"));
1847
1848 transcript.observe(&messages);
1849 let pending = transcript.plan_flush();
1850 let body = skill_body("unslop", 40);
1851
1852 let summary = pending
1855 .iter()
1856 .rev()
1857 .find(|summary| {
1858 transcript
1859 .sections
1860 .get(summary.section)
1861 .is_some_and(|section| {
1862 section.range == summary.range && !section.pinned.is_empty()
1863 })
1864 })
1865 .expect("a live union pending over a pinned section")
1866 .clone();
1867 assert!(transcript.commit_summary(&summary, "## Goals Met\n- dense fill".into()));
1868 let text = &transcript.sections[summary.section].text;
1869 assert!(text.starts_with("## Goals Met\n- dense fill"), "{text}");
1870 assert!(text.contains(&body), "{text}");
1871 }
1872
1873 #[test]
1874 fn a_fill_lands_after_the_flushs_own_consolidation_moves_it() {
1875 let mut transcript = Transcript::new(TranscriptSettings {
1882 max_view_bytes: 40_000,
1883 step_bytes: 4_000,
1884 max_block_bytes: 1_000,
1885 ..TranscriptSettings::default()
1886 });
1887 let mut messages = vec![Message::text(Role::User, "fix the build")];
1888 messages.extend(long_history(30));
1889 messages.push(Message::text(Role::User, "and now summarize"));
1890 transcript.observe(&messages);
1891 let pending = transcript.plan_flush();
1892 assert!(
1893 transcript.stats.consolidations > 0,
1894 "the fixture must consolidate"
1895 );
1896
1897 let moved = pending.iter().filter(|summary| {
1898 transcript
1899 .sections
1900 .get(summary.section)
1901 .is_none_or(|section| section.range != summary.range)
1902 });
1903 assert!(
1904 moved.count() > 0,
1905 "the fixture must move a commissioned section"
1906 );
1907
1908 for summary in &pending {
1909 let index = transcript
1910 .sections
1911 .iter()
1912 .position(|section| section.range == summary.range);
1913 let committed = transcript.commit_summary(summary, "## dense fill".into());
1914 assert_eq!(
1915 index.is_some(),
1916 committed,
1917 "the range decides, not the index"
1918 );
1919 if let Some(index) = index {
1920 assert_eq!(transcript.sections[index].text, "## dense fill");
1921 assert!(matches!(
1922 transcript.sections[index].origin,
1923 SectionOrigin::Model
1924 ));
1925 }
1926 }
1927 }
1928
1929 #[test]
1930 fn a_merge_drops_a_pin_the_discovery_no_longer_holds() {
1931 let mut transcript = Transcript::new(TranscriptSettings {
1936 max_view_bytes: 40_000,
1937 step_bytes: 4_000,
1938 max_block_bytes: 1_000,
1939 ..TranscriptSettings::default()
1940 });
1941 transcript.set_skills(vec![SkillText {
1942 name: "unslop".into(),
1943 body: skill_body("unslop", 40),
1944 }]);
1945 let mut messages = vec![Message::text(Role::User, "fix the build")];
1946 messages.extend(skill_round("s1", "unslop", 40));
1947 messages.extend(long_history(6));
1948 messages.push(Message::text(Role::User, "and now summarize"));
1949 transcript.observe(&messages);
1950 let pending = transcript.plan_flush();
1951 drop(pending);
1952 assert!(
1953 transcript
1954 .sections
1955 .iter()
1956 .any(|section| section.pinned.iter().any(|name| name == "unslop")),
1957 "the fixture must pin the skill first"
1958 );
1959
1960 transcript.set_skills(Vec::new());
1964 let mut messages2 = messages;
1965 messages2.extend(long_history(6));
1966 messages2.push(Message::text(Role::User, "carry on"));
1967 transcript.observe(&messages2);
1968 let pending = transcript.plan_flush();
1969 drop(pending);
1970 assert!(
1971 transcript.stats.consolidations > 0,
1972 "the fixture must consolidate the merge"
1973 );
1974 assert!(
1975 transcript
1976 .sections
1977 .iter()
1978 .all(|section| !section.pinned.iter().any(|name| name == "unslop")),
1979 "a claim without its body is a lie"
1980 );
1981 transcript.observe(&messages2);
1984 assert!(!transcript.pinned.contains_key("unslop"));
1985 }
1986
1987 #[test]
1988 fn a_resume_keeps_deduplicating_rereads() {
1989 let mut first = Transcript::new(settings(40_000));
1990 first.set_skills(vec![SkillText {
1991 name: "unslop".into(),
1992 body: skill_body("unslop", 40),
1993 }]);
1994 let mut messages = vec![Message::text(Role::User, "fix the build")];
1995 messages.extend(skill_round("s1", "unslop", 40));
1996 messages.extend(long_history(8));
1997 messages.push(Message::text(Role::User, "and now summarize"));
1998 first.observe(&messages);
1999 first.plan_flush();
2000 let saved = first.saved_sections();
2001 assert!(!saved.is_empty(), "the first session must have flushed");
2002
2003 let mut second = Transcript::new(settings(40_000));
2006 second.adopt_sections(saved);
2007 let mut resumed = messages.clone();
2008 resumed.extend(skill_round("s2", "unslop", 40));
2009 resumed.extend(long_history(2));
2010 resumed.push(Message::text(Role::User, "one more"));
2011 second.observe(&resumed);
2012 second.plan_flush();
2013 let body = skill_body("unslop", 40);
2014 let view = second.render().unwrap();
2015 let rhema_core::Content::Text(text) = &view[0].content[0] else {
2016 panic!("text view message");
2017 };
2018 assert_eq!(text.matches(&body).count(), 1, "one copy after resume");
2019 }
2020
2021 #[test]
2022 fn tampered_saved_sections_fall_back_to_the_rebuild() {
2023 let mut transcript = Transcript::new(settings(20_000));
2024 transcript.adopt_sections(vec![Section {
2025 range: Range { id: 5, n: 9 },
2026 text: "## Goals Met\n- orphan".into(),
2027 origin: SectionOrigin::Model,
2028 pinned: Vec::new(),
2029 }]);
2030 transcript.observe(&long_history(30));
2031 assert_eq!(transcript.cut, 0);
2033 assert!(transcript.sections.is_empty());
2034 assert!(!transcript.plan_flush().is_empty());
2036 }
2037
2038 #[test]
2039 fn a_pending_summary_carries_the_adjacent_digest_as_context() {
2040 let mut transcript = Transcript::new(settings(20_000));
2041 transcript.observe(&long_history(30));
2042 let pending = transcript.plan_flush();
2043 assert!(pending.len() >= 2);
2044 assert_eq!(pending[0].context, None);
2047 for (prev, item) in pending.iter().zip(pending.iter().skip(1)) {
2048 let expected = transcript.sections[prev.section].text.clone();
2049 assert_eq!(item.context.as_deref(), Some(expected.as_str()));
2050 }
2051
2052 let first = pending[0].clone();
2055 assert!(transcript.commit_summary(&first, "## Goals Met\n- model".into()));
2056 let mut extended = long_history(30);
2057 for i in 0..12 {
2058 extended.push(Message::text(
2059 Role::User,
2060 format!("extra filler {i}: {}", "y".repeat(1024)),
2061 ));
2062 }
2063 transcript.observe(&extended);
2064 let expected = transcript.sections.last().unwrap().text.clone();
2067 let pending = transcript.plan_flush();
2068 assert!(!pending.is_empty());
2069 assert_eq!(pending[0].context.as_deref(), Some(expected.as_str()));
2070 }
2071
2072 #[test]
2073 fn the_block_consolidates_past_its_cap() {
2074 let mut transcript = Transcript::new(TranscriptSettings {
2075 max_block_bytes: 500,
2076 ..settings(20_000)
2077 });
2078 let messages = long_history(30);
2079 transcript.observe(&messages);
2080 transcript.plan_flush();
2081 assert!(transcript.block_bytes() <= 500);
2082 assert!(transcript.stats.consolidations > 0);
2083 let mut at = 0;
2085 for section in &transcript.sections {
2086 assert_eq!(section.range.id, at);
2087 at += section.range.n;
2088 }
2089 assert_eq!(at, transcript.cut);
2090 }
2091
2092 #[test]
2093 fn a_resumed_session_rebuilds_the_compaction_from_nothing() {
2094 let mut transcript = Transcript::new(settings(20_000));
2095 transcript.observe(&long_history(30));
2096 transcript.plan_flush();
2097 assert!(transcript.cut > 0);
2098 transcript.observe(&long_history(2));
2100 assert_eq!(transcript.cut, 0);
2101 assert!(transcript.sections.is_empty());
2102 }
2103
2104 #[test]
2105 fn the_breakdown_spreads_reported_input_by_wire_share() {
2106 let mut transcript = Transcript::new(TranscriptSettings::default());
2107 transcript.set_skills_bytes(500);
2108 let system = format!("{}{}", "b".repeat(1_500), "s".repeat(500));
2111 let call_args = serde_json::json!({ "c": "x".repeat(100) });
2112 let messages = vec![
2113 Message::text(Role::User, "u".repeat(1_000)),
2114 Message {
2115 annotations: Default::default(),
2116 role: Role::Assistant,
2117 content: vec![
2118 Content::Text("a".repeat(400)),
2119 Content::ToolCall(ToolCall {
2120 id: "c1".into(),
2121 name: "bash".into(),
2122 args: call_args.clone(),
2123 provider_data: serde_json::Value::Null,
2124 }),
2125 ],
2126 },
2127 Message {
2128 annotations: Default::default(),
2129 role: Role::Tool,
2130 content: vec![Content::ToolResult(ToolResult::success(
2131 "c1",
2132 "r".repeat(1_000),
2133 ))],
2134 },
2135 ];
2136 transcript.stage_usage_shares(Some(&system), &[], &messages);
2137 transcript.record_usage(&Usage {
2138 input_tokens: 10_000,
2139 output_tokens: 100,
2140 cached_input_tokens: 0,
2141 });
2142
2143 let total = 2_000 + 1_000 + 400 + ("bash".len() + call_args.to_string().len()) + 1_000;
2144 let spread = |bytes: usize| 10_000 * bytes as u64 / total as u64;
2145 let b = transcript.stats().usage;
2146 assert_eq!(b.system_prompt_tokens, spread(1_500));
2147 assert_eq!(b.skills_tokens, spread(500));
2148 assert_eq!(
2149 b.tool_calls_input_tokens,
2150 spread("bash".len() + call_args.to_string().len())
2151 );
2152 assert_eq!(b.tool_calls_output_tokens, spread(1_000));
2153 assert_eq!(b.user_messages_tokens, spread(1_000));
2154 assert_eq!(b.model_output_tokens, spread(400) + 100);
2157 transcript.record_usage(&Usage {
2160 input_tokens: 1_000,
2161 output_tokens: 0,
2162 cached_input_tokens: 0,
2163 });
2164 assert_eq!(transcript.stats().usage.user_messages_tokens, spread(1_000));
2165 }
2166
2167 #[test]
2168 fn a_skills_share_past_the_system_clamps() {
2169 let mut transcript = Transcript::new(TranscriptSettings::default());
2170 transcript.set_skills_bytes(9_999);
2171 transcript.stage_usage_shares(Some("short"), &[], &[]);
2172 transcript.record_usage(&Usage {
2173 input_tokens: 100,
2174 output_tokens: 0,
2175 cached_input_tokens: 0,
2176 });
2177 let b = transcript.stats().usage;
2178 assert_eq!(b.skills_tokens, 100);
2179 assert_eq!(b.system_prompt_tokens, 0);
2180 }
2181
2182 #[test]
2183 fn a_carry_continues_the_saved_run() {
2184 let saved = TranscriptStats {
2185 requests: 10,
2186 pass_through: 6,
2187 viewed: 4,
2188 flushes: 1,
2189 consolidations: 1,
2190 summarizer_calls: 2,
2191 summarizer_failures: 1,
2192 input_tokens: 90_000,
2193 cached_input_tokens: 70_000,
2194 output_tokens: 10_000,
2195 usage: UsageBreakdown {
2196 system_prompt_tokens: 20_000,
2197 skills_tokens: 2_000,
2198 tool_calls_input_tokens: 30_000,
2199 tool_calls_output_tokens: 30_000,
2200 user_messages_tokens: 8_000,
2201 model_output_tokens: 10_000,
2202 },
2203 log_messages: 12,
2205 sectioned_messages: 4,
2206 sections: 2,
2207 block_bytes: 900,
2208 block_tokens: 225,
2209 band_bytes: 3_000,
2210 band_tokens: 820,
2211 tail_bytes: 1_200,
2212 tail_tokens: 340,
2213 log_bytes: 5_400,
2214 log_content: LogContent {
2215 tool_calls: 100,
2216 tool_results: 4_000,
2217 user_text: 300,
2218 assistant_text: 1_000,
2219 },
2220 };
2221
2222 let mut fresh = TranscriptStats::default();
2226 fresh.carry(&saved);
2227 assert_eq!(fresh, saved);
2228
2229 let mut live = TranscriptStats {
2233 requests: 2,
2234 input_tokens: 5_000,
2235 output_tokens: 300,
2236 usage: UsageBreakdown {
2237 user_messages_tokens: 5_000,
2238 model_output_tokens: 300,
2239 ..UsageBreakdown::default()
2240 },
2241 log_messages: 4,
2242 block_bytes: 100,
2243 ..TranscriptStats::default()
2244 };
2245 live.carry(&saved);
2246 assert_eq!(live.requests, 12);
2247 assert_eq!(live.input_tokens, 95_000);
2248 assert_eq!(live.output_tokens, 10_300);
2249 assert_eq!(live.usage.user_messages_tokens, 13_000);
2250 assert_eq!(live.usage.model_output_tokens, 10_300);
2251 assert_eq!(live.usage.system_prompt_tokens, 20_000);
2252 assert_eq!(live.block_bytes, 100, "the live mirror's snapshot");
2253 assert_eq!(live.log_messages, 4);
2254
2255 let mut later = TranscriptStats {
2258 requests: 3,
2259 input_tokens: 8_000,
2260 ..TranscriptStats::default()
2261 };
2262 later.carry(&saved);
2263 assert_eq!(later.requests, 13);
2264 assert_eq!(later.input_tokens, 98_000);
2265 }
2266
2267 #[test]
2271 fn the_log_bytes_snapshot_counts_the_log_once() {
2272 let mut transcript = Transcript::new(settings(128_000));
2273 let messages = long_history(4); transcript.observe(&messages);
2275 transcript.render();
2276 let expected: usize = messages.iter().map(summary::message_bytes).sum();
2277 assert_eq!(transcript.stats().log_bytes, expected);
2278
2279 let grown = long_history(5);
2281 transcript.observe(&grown);
2282 transcript.render();
2283 let expected: usize = grown.iter().map(summary::message_bytes).sum();
2284 assert_eq!(transcript.stats().log_bytes, expected);
2285 }
2286
2287 #[test]
2292 fn the_content_split_counts_each_message_once() {
2293 let mut transcript = Transcript::new(settings(128_000));
2294 let messages = long_history(4);
2295 transcript.observe(&messages);
2296 transcript.render();
2297 let content = transcript.stats().log_content;
2298 assert_eq!(
2299 content.tool_results,
2300 4 * summary::text_tokens(result_bytes(8).len())
2301 );
2302 assert_eq!(
2303 content.assistant_text,
2304 4 * summary::text_tokens("checking".len())
2305 );
2306 assert_eq!(
2307 content.user_text,
2308 summary::text_tokens("fix the build".len())
2309 + summary::text_tokens("and now summarize".len())
2310 );
2311 let args = serde_json::json!({ "command": "make test" }).to_string();
2312 assert_eq!(
2313 content.tool_calls,
2314 4 * summary::text_tokens("bash".len() + args.len())
2315 );
2316 let expected: u64 = messages.iter().map(summary::message_tokens).sum();
2319 assert_eq!(content.total(), expected);
2320 }
2321
2322 #[test]
2323 fn an_image_costs_one_message_in_the_split_and_the_budget() {
2324 let mut transcript = Transcript::new(settings(128_000));
2325 transcript.observe(&[Message {
2326 annotations: Default::default(),
2327 role: Role::Tool,
2328 content: vec![Content::ToolResult(
2329 ToolResult::success("c1", "ok").with_images(vec![rhema_core::Image::new(
2330 rhema_core::ImageMediaType::Png,
2331 "A".repeat(2_000_000),
2332 )]),
2333 )],
2334 }]);
2335 transcript.render();
2336 let stats = transcript.stats();
2337 assert_eq!(stats.log_bytes, 2 + summary::IMAGE_BYTES);
2340 assert_eq!(stats.log_content.tool_results, summary::IMAGE_TOKENS);
2342 }
2343
2344 #[test]
2345 fn reset_stats_zeroes_the_accounting_and_keeps_the_log() {
2346 let mut transcript = Transcript::new(TranscriptSettings::default());
2347 transcript.observe(&[Message::text(Role::User, "kept")]);
2348 transcript.record_usage(&Usage {
2349 input_tokens: 1_000,
2350 output_tokens: 100,
2351 cached_input_tokens: 0,
2352 });
2353 assert_eq!(transcript.len(), 1);
2354 transcript.reset_stats();
2355 assert_eq!(transcript.stats(), TranscriptStats::default());
2356 assert_eq!(transcript.len(), 1);
2357 }
2358
2359 #[test]
2360 fn usage_records_and_the_hit_rate_reads() {
2361 let mut transcript = Transcript::new(TranscriptSettings::default());
2362 assert!(transcript.stats().cache_hit_rate().is_none());
2363 transcript.record_usage(&Usage {
2364 input_tokens: 1_000,
2365 output_tokens: 100,
2366 cached_input_tokens: 800,
2367 });
2368 let stats = transcript.stats();
2369 assert_eq!(stats.input_tokens, 1_000);
2370 assert_eq!(stats.cached_input_tokens, 800);
2371 let rate = stats.cache_hit_rate().unwrap();
2372 assert!((rate - 0.8).abs() < 1e-9);
2373 }
2374
2375 struct Recording(StdMutex<Vec<Vec<Message>>>);
2377 #[async_trait]
2378 impl ModelProvider for Recording {
2379 async fn complete(
2380 &self,
2381 req: rhema_core::ModelRequest,
2382 _sink: &mut dyn EventSink,
2383 ) -> Result<ModelOutput, ProviderError> {
2384 self.0.lock().unwrap().push(req.messages);
2385 Ok(ModelOutput {
2386 message: Message::text(Role::Assistant, "done"),
2387 stop_reason: rhema_core::StopReason::EndTurn,
2388 usage: Usage {
2389 input_tokens: 500,
2390 output_tokens: 10,
2391 cached_input_tokens: 400,
2392 },
2393 })
2394 }
2395 }
2396
2397 #[tokio::test]
2398 async fn the_decorator_rewrites_the_request_and_the_mirror_stays_whole() {
2399 let recording = Arc::new(Recording(StdMutex::new(Vec::new())));
2400 let transcript = Arc::new(Mutex::new(Transcript::new(settings(20_000))));
2401 let view = TranscriptView::new(recording.clone(), transcript.clone());
2402 let messages = long_history(30);
2403 let req = rhema_core::ModelRequest {
2404 system: None,
2405 messages: messages.clone(),
2406 tools: Vec::new(),
2407 params: rhema_core::ChatParams::new("m"),
2408 };
2409 let mut sink = NoopSink;
2410 view.complete(req, &mut sink).await.unwrap();
2411
2412 let seen = recording.0.lock().unwrap();
2413 let sent = &seen[0];
2414 assert!(sent.len() < messages.len());
2415 assert_eq!(sent.last().unwrap().role, Role::User);
2416 let mirror = transcript.lock().unwrap();
2418 assert_eq!(mirror.len(), messages.len());
2419 assert_eq!(mirror.message(0), Some(&messages[0]));
2420 assert_eq!(mirror.stats().cache_hit_rate(), Some(0.8));
2422 }
2423
2424 #[tokio::test]
2425 async fn the_decorator_upgrades_sections_with_its_summarizer() {
2426 struct Worker;
2428 #[async_trait]
2429 impl ModelProvider for Worker {
2430 async fn complete(
2431 &self,
2432 _req: rhema_core::ModelRequest,
2433 _sink: &mut dyn EventSink,
2434 ) -> Result<ModelOutput, ProviderError> {
2435 Ok(ModelOutput {
2436 message: Message::text(Role::Assistant, "## Goals Met\n- worker wrote this"),
2437 stop_reason: rhema_core::StopReason::EndTurn,
2438 usage: Usage::default(),
2439 })
2440 }
2441 }
2442
2443 let recording = Arc::new(Recording(StdMutex::new(Vec::new())));
2444 let transcript = Arc::new(Mutex::new(Transcript::new(settings(20_000))));
2445 let view = TranscriptView::with_summarizer(
2446 recording.clone(),
2447 transcript.clone(),
2448 Arc::new(compact::ModelSummarizer::new(Arc::new(Worker), "cheap")),
2449 );
2450 let req = rhema_core::ModelRequest {
2451 system: None,
2452 messages: long_history(30),
2453 tools: Vec::new(),
2454 params: rhema_core::ChatParams::new("m"),
2455 };
2456 let mut sink = NoopSink;
2457 view.complete(req, &mut sink).await.unwrap();
2458
2459 {
2462 let sent = recording.0.lock().unwrap();
2463 let rhema_core::Content::Text(text) = &sent[0][0].content[0] else {
2464 panic!("text view message");
2465 };
2466 assert!(!text.contains("worker wrote this"), "{text}");
2467 }
2468
2469 wait_for(|| {
2471 transcript
2472 .lock()
2473 .unwrap()
2474 .sections
2475 .iter()
2476 .all(|s| s.origin == SectionOrigin::Model)
2477 })
2478 .await;
2479
2480 {
2483 let mirror = transcript.lock().unwrap();
2484 let stats = mirror.stats();
2485 assert!(stats.summarizer_calls > 0);
2486 assert_eq!(stats.summarizer_failures, 0);
2487 assert!(
2488 mirror
2489 .sections
2490 .iter()
2491 .all(|s| s.text.contains("worker wrote this"))
2492 );
2493 }
2494
2495 let req = rhema_core::ModelRequest {
2497 system: None,
2498 messages: long_history(30),
2499 tools: Vec::new(),
2500 params: rhema_core::ChatParams::new("m"),
2501 };
2502 let mut sink = NoopSink;
2503 view.complete(req, &mut sink).await.unwrap();
2504 let sent = recording.0.lock().unwrap();
2505 let rhema_core::Content::Text(text) = &sent[1][0].content[0] else {
2506 panic!("text view message");
2507 };
2508 assert!(text.contains("worker wrote this"), "{text}");
2509 }
2510
2511 #[tokio::test]
2512 async fn a_failing_summarizer_never_blocks_the_request() {
2513 struct Failing;
2514 #[async_trait]
2515 impl ModelProvider for Failing {
2516 async fn complete(
2517 &self,
2518 _req: rhema_core::ModelRequest,
2519 _sink: &mut dyn EventSink,
2520 ) -> Result<ModelOutput, ProviderError> {
2521 Err(ProviderError::Timeout)
2522 }
2523 }
2524
2525 let recording = Arc::new(Recording(StdMutex::new(Vec::new())));
2526 let transcript = Arc::new(Mutex::new(Transcript::new(settings(20_000))));
2527 let view = TranscriptView::with_summarizer(
2528 recording.clone(),
2529 transcript.clone(),
2530 Arc::new(compact::ModelSummarizer::new(Arc::new(Failing), "cheap")),
2531 );
2532 let req = rhema_core::ModelRequest {
2533 system: None,
2534 messages: long_history(30),
2535 tools: Vec::new(),
2536 params: rhema_core::ChatParams::new("m"),
2537 };
2538 let mut sink = NoopSink;
2539 view.complete(req, &mut sink).await.unwrap();
2543 {
2544 let sent = recording.0.lock().unwrap();
2547 assert_eq!(sent.len(), 1);
2548 }
2549 wait_for(|| transcript.lock().unwrap().stats().summarizer_calls > 0).await;
2550 let mirror = transcript.lock().unwrap();
2551 assert_eq!(
2552 mirror.stats().summarizer_failures,
2553 mirror.stats().summarizer_calls
2554 );
2555 assert!(
2556 mirror
2557 .sections
2558 .iter()
2559 .all(|s| s.origin == SectionOrigin::Extractive)
2560 );
2561 }
2562
2563 struct Gated(Arc<AtomicBool>);
2567
2568 #[async_trait]
2569 impl ModelProvider for Gated {
2570 async fn complete(
2571 &self,
2572 _req: rhema_core::ModelRequest,
2573 _sink: &mut dyn EventSink,
2574 ) -> Result<ModelOutput, ProviderError> {
2575 while !self.0.load(Ordering::SeqCst) {
2576 tokio::task::yield_now().await;
2577 }
2578 Ok(ModelOutput {
2579 message: Message::text(Role::Assistant, "## Goals Met\n- late but dense"),
2580 stop_reason: rhema_core::StopReason::EndTurn,
2581 usage: Usage::default(),
2582 })
2583 }
2584 }
2585
2586 #[tokio::test]
2587 async fn a_slow_summarizer_never_delays_the_request() {
2588 let gate = Arc::new(AtomicBool::new(false));
2589 let recording = Arc::new(Recording(StdMutex::new(Vec::new())));
2590 let transcript = Arc::new(Mutex::new(Transcript::new(settings(20_000))));
2591 let view = TranscriptView::with_summarizer(
2592 recording.clone(),
2593 transcript.clone(),
2594 Arc::new(compact::ModelSummarizer::new(
2595 Arc::new(Gated(Arc::clone(&gate))),
2596 "cheap",
2597 )),
2598 );
2599 let req = rhema_core::ModelRequest {
2600 system: None,
2601 messages: long_history(30),
2602 tools: Vec::new(),
2603 params: rhema_core::ChatParams::new("m"),
2604 };
2605 let turn = tokio::spawn(async move {
2606 let mut sink = NoopSink;
2607 view.complete(req, &mut sink).await.unwrap();
2608 });
2609
2610 wait_for(|| !recording.0.lock().unwrap().is_empty()).await;
2613 wait_for(|| turn.is_finished()).await;
2614 assert!(
2615 !gate.load(Ordering::SeqCst),
2616 "the request waited on the gated worker"
2617 );
2618
2619 gate.store(true, Ordering::SeqCst);
2621 wait_for(|| {
2622 transcript
2623 .lock()
2624 .unwrap()
2625 .sections
2626 .iter()
2627 .all(|s| s.origin == SectionOrigin::Model)
2628 })
2629 .await;
2630 let mirror = transcript.lock().unwrap();
2631 assert!(
2632 mirror
2633 .sections
2634 .iter()
2635 .all(|s| s.text.contains("late but dense")),
2636 "{:?}",
2637 mirror.sections
2638 );
2639 }
2640
2641 struct NoopSink;
2642
2643 impl EventSink for NoopSink {
2644 fn emit(&mut self, _event: rhema_core::Event<'_>) {}
2645 }
2646}