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 pub max_view_images: usize,
66}
67
68impl Default for TranscriptSettings {
69 fn default() -> Self {
70 Self {
71 max_view_bytes: 256_000,
76 step_bytes: 24_000,
77 max_section_messages: 128,
78 max_block_bytes: 32_000,
79 max_view_images: 10,
82 }
83 }
84}
85
86#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
94pub struct UsageBreakdown {
95 pub system_prompt_tokens: u64,
97 pub skills_tokens: u64,
100 pub tool_calls_input_tokens: u64,
103 pub tool_calls_output_tokens: u64,
105 pub user_messages_tokens: u64,
107 pub model_output_tokens: u64,
110}
111
112impl UsageBreakdown {
113 pub fn labeled(&self) -> [(&'static str, u64); 6] {
115 [
116 ("System Prompt", self.system_prompt_tokens),
117 ("Skills", self.skills_tokens),
118 ("Tool Calls Input", self.tool_calls_input_tokens),
119 ("Tool Calls Output", self.tool_calls_output_tokens),
120 ("User Messages", self.user_messages_tokens),
121 ("Model Output", self.model_output_tokens),
122 ]
123 }
124
125 pub fn total(&self) -> u64 {
127 self.system_prompt_tokens
128 + self.skills_tokens
129 + self.tool_calls_input_tokens
130 + self.tool_calls_output_tokens
131 + self.user_messages_tokens
132 + self.model_output_tokens
133 }
134}
135
136#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
143pub struct LogContent {
144 pub tool_calls: u64,
146 pub tool_results: u64,
148 pub user_text: u64,
150 pub assistant_text: u64,
152}
153
154impl LogContent {
155 pub fn total(&self) -> u64 {
158 self.tool_calls + self.tool_results + self.user_text + self.assistant_text
159 }
160}
161
162#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
169pub struct TranscriptStats {
170 pub requests: u64,
172 pub pass_through: u64,
175 pub viewed: u64,
177 pub flushes: u64,
180 pub consolidations: u64,
183 pub summarizer_calls: u64,
185 pub summarizer_failures: u64,
188 pub log_messages: usize,
190 pub sectioned_messages: usize,
192 pub sections: usize,
194 pub block_bytes: usize,
196 #[serde(default)]
198 pub block_tokens: u64,
199 pub band_bytes: usize,
202 #[serde(default)]
205 pub band_tokens: u64,
206 #[serde(default)]
210 pub view_images: usize,
211 pub tail_bytes: usize,
213 #[serde(default)]
215 pub tail_tokens: u64,
216 #[serde(default)]
221 pub log_bytes: usize,
222 #[serde(default)]
225 pub log_content: LogContent,
226 pub input_tokens: u64,
229 pub cached_input_tokens: u64,
231 pub output_tokens: u64,
233 pub usage: UsageBreakdown,
235}
236
237impl TranscriptStats {
238 pub fn cache_hit_rate(&self) -> Option<f64> {
242 if self.input_tokens == 0 {
243 None
244 } else {
245 Some(self.cached_input_tokens as f64 / self.input_tokens as f64)
246 }
247 }
248
249 pub fn carry(&mut self, saved: &Self) {
259 self.requests += saved.requests;
260 self.pass_through += saved.pass_through;
261 self.viewed += saved.viewed;
262 self.flushes += saved.flushes;
263 self.consolidations += saved.consolidations;
264 self.summarizer_calls += saved.summarizer_calls;
265 self.summarizer_failures += saved.summarizer_failures;
266 self.input_tokens += saved.input_tokens;
267 self.cached_input_tokens += saved.cached_input_tokens;
268 self.output_tokens += saved.output_tokens;
269 let usage = &mut self.usage;
270 let saved_usage = &saved.usage;
271 usage.system_prompt_tokens += saved_usage.system_prompt_tokens;
272 usage.skills_tokens += saved_usage.skills_tokens;
273 usage.tool_calls_input_tokens += saved_usage.tool_calls_input_tokens;
274 usage.tool_calls_output_tokens += saved_usage.tool_calls_output_tokens;
275 usage.user_messages_tokens += saved_usage.user_messages_tokens;
276 usage.model_output_tokens += saved_usage.model_output_tokens;
277 if self.log_messages == 0 {
278 self.log_messages = saved.log_messages;
279 self.sectioned_messages = saved.sectioned_messages;
280 self.sections = saved.sections;
281 self.block_bytes = saved.block_bytes;
282 self.block_tokens = saved.block_tokens;
283 self.band_bytes = saved.band_bytes;
284 self.band_tokens = saved.band_tokens;
285 self.view_images = saved.view_images;
286 self.tail_bytes = saved.tail_bytes;
287 self.tail_tokens = saved.tail_tokens;
288 self.log_bytes = saved.log_bytes;
289 self.log_content = saved.log_content;
290 }
291 }
292}
293
294#[derive(Debug, Clone, Copy, PartialEq, Eq)]
297pub enum WorkerOutcome {
298 Upgraded,
300 Dropped,
303 Failed,
305}
306
307#[derive(Debug)]
312pub struct Transcript {
313 settings: TranscriptSettings,
314 log: Vec<Message>,
315 sizes: Vec<usize>,
318 tokens: Vec<u64>,
321 total_bytes: usize,
325 total_tokens: u64,
327 images: Vec<usize>,
330 content: LogContent,
333 cut: usize,
336 sections: Vec<Section>,
339 skills_bytes: usize,
342 skills: Vec<SkillText>,
345 min_skill_body: usize,
348 reads: Vec<Read>,
350 pinned: HashMap<String, Range>,
355 pending_shares: Shares,
359 stats: TranscriptStats,
360 saved: Option<Vec<Section>>,
365}
366
367#[derive(Debug, Clone, PartialEq, Eq)]
371pub struct SkillText {
372 pub name: String,
374 pub body: String,
376}
377
378#[derive(Debug, Clone, Copy)]
381struct Read {
382 call: usize,
384 result: usize,
386 skill: usize,
388}
389
390const NEEDLE_BYTES: usize = 64;
393
394fn needle(body: &str) -> &str {
397 let mut end = NEEDLE_BYTES.min(body.len());
398 while !body.is_char_boundary(end) {
399 end -= 1;
400 }
401 &body[..end]
402}
403
404#[derive(Debug, Clone, Copy, Default)]
407struct Shares {
408 system_prompt: usize,
409 skills: usize,
410 tool_defs: usize,
411 tool_calls: usize,
412 tool_results: usize,
413 user_text: usize,
414 assistant_text: usize,
415}
416
417fn add_message_content(content: &mut LogContent, message: &Message) {
422 for part in &message.content {
423 match part {
424 Content::Text(text) => match message.role {
425 Role::User => content.user_text += summary::text_tokens(text.len()),
426 Role::Assistant => content.assistant_text += summary::text_tokens(text.len()),
427 Role::System | Role::Tool => {}
428 },
429 Content::ToolCall(call) => {
430 content.tool_calls +=
431 summary::text_tokens(call.name.len() + call.args.to_string().len());
432 }
433 Content::ToolResult(result) => {
434 content.tool_results += summary::text_tokens(result.content.len());
435 content.tool_results += result.images.len() as u64 * summary::IMAGE_TOKENS;
439 }
440 Content::Image(_) => match message.role {
444 Role::User => content.user_text += summary::IMAGE_TOKENS,
445 Role::Assistant => content.assistant_text += summary::IMAGE_TOKENS,
446 Role::System | Role::Tool => {}
447 },
448 }
449 }
450}
451
452impl Shares {
453 fn total(&self) -> usize {
454 self.system_prompt
455 + self.skills
456 + self.tool_defs
457 + self.tool_calls
458 + self.tool_results
459 + self.user_text
460 + self.assistant_text
461 }
462}
463
464impl Transcript {
465 pub fn new(settings: TranscriptSettings) -> Self {
467 Self {
468 settings,
469 log: Vec::new(),
470 sizes: Vec::new(),
471 tokens: Vec::new(),
472 images: Vec::new(),
473 total_bytes: 0,
474 total_tokens: 0,
475 content: LogContent::default(),
476 cut: 0,
477 sections: Vec::new(),
478 skills_bytes: 0,
479 skills: Vec::new(),
480 min_skill_body: usize::MAX,
481 reads: Vec::new(),
482 pinned: HashMap::new(),
483 pending_shares: Shares::default(),
484 stats: TranscriptStats::default(),
485 saved: None,
486 }
487 }
488
489 pub fn observe(&mut self, messages: &[Message]) {
495 if messages.len() >= self.log.len() && messages[..self.log.len()] == self.log[..] {
496 let first = self.log.len();
497 for message in &messages[first..] {
498 let bytes = summary::message_bytes(message);
499 let tokens = summary::message_tokens(message);
500 let images = summary::message_images(message);
501 self.sizes.push(bytes);
502 self.tokens.push(tokens);
503 self.images.push(images);
504 self.total_bytes += bytes;
505 self.total_tokens += tokens;
506 add_message_content(&mut self.content, message);
507 }
508 self.log.extend_from_slice(&messages[first..]);
509 self.scan_reads(first);
510 } else {
511 self.log = messages.to_vec();
512 self.sizes = Vec::with_capacity(self.log.len());
513 self.tokens = Vec::with_capacity(self.log.len());
514 self.images = Vec::with_capacity(self.log.len());
515 self.total_bytes = 0;
516 self.total_tokens = 0;
517 self.content = LogContent::default();
518 for index in 0..self.log.len() {
519 let bytes = summary::message_bytes(&self.log[index]);
520 let tokens = summary::message_tokens(&self.log[index]);
521 let images = summary::message_images(&self.log[index]);
522 self.sizes.push(bytes);
523 self.tokens.push(tokens);
524 self.images.push(images);
525 self.total_bytes += bytes;
526 self.total_tokens += tokens;
527 add_message_content(&mut self.content, &self.log[index]);
528 }
529 self.cut = 0;
530 self.sections.clear();
531 self.reads.clear();
532 self.scan_reads(0);
533 }
534 if let Some(saved) = self.saved.take() {
542 let mut end = 0usize;
543 let tiles = !saved.is_empty()
547 && saved.iter().all(|section| {
548 match section.range.id.checked_add(section.range.n) {
549 Some(next) if section.range.id == end => {
550 end = next;
551 end <= self.log.len()
552 }
553 _ => false,
554 }
555 })
556 && end <= self.log.len();
557 if tiles {
558 self.sections = saved;
559 self.cut = end;
560 }
561 }
562 self.pinned = self
568 .sections
569 .iter()
570 .flat_map(|section| {
571 section
572 .pinned
573 .iter()
574 .map(|name| (name.clone(), section.range))
575 })
576 .collect();
577 }
578
579 pub fn len(&self) -> usize {
581 self.log.len()
582 }
583
584 pub fn is_empty(&self) -> bool {
586 self.log.is_empty()
587 }
588
589 pub fn message(&self, id: usize) -> Option<&Message> {
591 self.log.get(id)
592 }
593
594 pub fn range(&self, range: Range) -> Option<&[Message]> {
599 let end = range.id.checked_add(range.n)?;
600 self.log.get(range.id..end)
601 }
602
603 pub fn stats(&self) -> TranscriptStats {
605 self.stats
606 }
607
608 pub fn max_view_images(&self) -> usize {
612 self.settings.max_view_images
613 }
614
615 pub fn carry(&mut self, saved: &TranscriptStats) {
619 self.stats.carry(saved);
620 }
621
622 pub fn saved_sections(&self) -> Vec<Section> {
625 self.sections.clone()
626 }
627
628 pub fn adopt_sections(&mut self, sections: Vec<Section>) {
632 self.saved = Some(sections);
633 }
634
635 pub fn reset_stats(&mut self) {
639 self.stats = TranscriptStats::default();
640 }
641
642 pub fn set_skills_bytes(&mut self, bytes: usize) {
647 self.skills_bytes = bytes;
648 }
649
650 pub fn set_skills(&mut self, skills: Vec<SkillText>) {
657 self.skills = skills;
658 self.min_skill_body = self
659 .skills
660 .iter()
661 .map(|skill| skill.body.len())
662 .min()
663 .unwrap_or(usize::MAX);
664 self.reads.clear();
665 self.scan_reads(0);
666 }
667
668 fn carried_skill(&self, result: &ToolResult) -> Option<usize> {
675 if result.content.len() < self.min_skill_body {
676 return None;
677 }
678 self.skills.iter().position(|skill| {
679 result.content.len() >= skill.body.len()
680 && result.content.contains(needle(&skill.body))
681 && result.content.contains(&skill.body)
682 })
683 }
684
685 fn scan_reads(&mut self, from: usize) {
692 for index in from..self.log.len() {
693 if self.log[index].role != Role::Tool {
694 continue;
695 }
696 for part in &self.log[index].content {
697 let Content::ToolResult(result) = part else {
698 continue;
699 };
700 let Some(skill) = self.carried_skill(result) else {
701 continue;
702 };
703 let calls = || {
708 self.log[index - 1]
709 .content
710 .iter()
711 .filter_map(|part| match part {
712 Content::ToolCall(call) => Some(call),
713 _ => None,
714 })
715 };
716 let paired = index > 0
717 && self.log[index - 1].role == Role::Assistant
718 && match (calls().next(), calls().nth(1)) {
719 (Some(call), None) => call.id == result.id,
720 _ => false,
721 };
722 if paired {
723 self.reads.push(Read {
724 call: index - 1,
725 result: index,
726 skill,
727 });
728 break;
729 }
730 }
731 }
732 }
733
734 fn read_starting(&self, index: usize) -> Option<Read> {
736 let at = self.reads.partition_point(|read| read.call < index);
737 self.reads
738 .get(at)
739 .copied()
740 .filter(|read| read.call == index)
741 }
742
743 pub fn stage_usage_shares(
748 &mut self,
749 system: Option<&str>,
750 tools: &[ToolSpec],
751 messages: &[Message],
752 ) {
753 let mut shares = Shares::default();
754 if let Some(system) = system {
755 let skills = self.skills_bytes.min(system.len());
756 shares.skills = skills;
757 shares.system_prompt = system.len() - skills;
758 }
759 for spec in tools {
762 shares.tool_defs +=
763 spec.name.len() + spec.description.len() + spec.parameters.to_string().len();
764 }
765 for message in messages {
766 for content in &message.content {
767 match content {
768 Content::Text(text) => match message.role {
769 Role::User => shares.user_text += text.len(),
770 Role::Assistant => shares.assistant_text += text.len(),
771 Role::System | Role::Tool => {}
772 },
773 Content::ToolCall(call) => {
774 shares.tool_calls += call.name.len() + call.args.to_string().len();
775 }
776 Content::ToolResult(result) => {
777 shares.tool_results += result.content.len();
778 shares.tool_results += result.images.len() * summary::IMAGE_BYTES;
781 }
782 Content::Image(_) => {}
785 }
786 }
787 }
788 self.pending_shares = shares;
789 }
790
791 pub fn record_usage(&mut self, usage: &Usage) {
796 self.stats.input_tokens += u64::from(usage.input_tokens);
797 self.stats.cached_input_tokens += u64::from(usage.cached_input_tokens);
798 self.stats.output_tokens += u64::from(usage.output_tokens);
799 let shares = std::mem::take(&mut self.pending_shares);
800 let total = shares.total();
801 let input = u64::from(usage.input_tokens);
802 if total > 0 && input > 0 {
803 let spread = |bytes: usize| input * bytes as u64 / total as u64;
804 let breakdown = &mut self.stats.usage;
805 breakdown.system_prompt_tokens += spread(shares.system_prompt);
806 breakdown.skills_tokens += spread(shares.skills);
807 breakdown.tool_calls_input_tokens += spread(shares.tool_defs + shares.tool_calls);
808 breakdown.tool_calls_output_tokens += spread(shares.tool_results);
809 breakdown.user_messages_tokens += spread(shares.user_text);
810 breakdown.model_output_tokens += spread(shares.assistant_text);
811 }
812 self.stats.usage.model_output_tokens += u64::from(usage.output_tokens);
813 }
814
815 pub fn record_worker_call(&mut self, outcome: WorkerOutcome) {
819 self.stats.summarizer_calls += 1;
820 if outcome == WorkerOutcome::Failed {
821 self.stats.summarizer_failures += 1;
822 }
823 }
824
825 pub fn commit_summary(&mut self, pending: &PendingSummary, text: String) -> bool {
830 let index = match self.sections.get(pending.section) {
840 Some(section) if section.range == pending.range => pending.section,
841 _ => match self
842 .sections
843 .iter()
844 .position(|section| section.range == pending.range)
845 {
846 Some(index) => index,
847 None => return false,
848 },
849 };
850 let section = &mut self.sections[index];
851 let mut text = compact::cap_summary(text);
852 for name in §ion.pinned {
855 if let Some(skill) = self.skills.iter().find(|skill| &skill.name == name) {
856 text.push_str("\n\n");
857 text.push_str(&compact::skill_section_text(name, &skill.body));
858 }
859 }
860 section.text = text;
861 section.origin = SectionOrigin::Model;
862 true
863 }
864
865 pub fn plan_flush(&mut self) -> Vec<PendingSummary> {
874 self.sync_sizes();
875 let len = self.log.len();
876 let tail_start = self.tail_index();
877
878 let mut byte_target = self.cut;
884 if self.total_bytes > self.settings.max_view_bytes {
885 let tail_bytes = self.bytes(tail_start, len);
886 let allowance = self.settings.max_view_bytes.saturating_sub(tail_bytes);
887 let mut c_min = tail_start;
888 let mut budget = allowance;
889 while c_min > self.cut {
890 let cost = self.sizes[c_min - 1];
891 if cost > budget {
892 break;
893 }
894 budget -= cost;
895 c_min -= 1;
896 }
897 if c_min > self.cut {
898 let half = allowance / 2;
899 let mut c_new = c_min;
900 let mut band = self.bytes(c_new, tail_start);
901 while c_new < tail_start && band > half {
906 band -= self.sizes[c_new];
907 c_new += 1;
908 }
909 byte_target = byte_target.max(c_new);
910 }
911 }
912
913 let mut image_target = self.cut;
920 let mut band_images: usize = self.images[self.cut..len].iter().sum();
921 while image_target < tail_start && band_images > self.settings.max_view_images {
922 band_images -= self.images[image_target];
923 image_target += 1;
924 }
925
926 let mut c_new = byte_target.max(image_target);
931 let mut pending = Vec::new();
932 if c_new > self.cut {
933 while c_new < tail_start && self.log[c_new].role == Role::Tool {
934 c_new += 1;
935 }
936 pending = self.extend_sections(self.cut, c_new);
937 self.cut = c_new;
938 self.stats.flushes += 1;
939 pending.extend(self.consolidate());
940 }
941 pending
942 }
943
944 pub fn view(&mut self, messages: &[Message]) -> Option<Vec<Message>> {
953 self.observe(messages);
954 self.plan_flush();
955 self.render()
956 }
957
958 pub fn render(&mut self) -> Option<Vec<Message>> {
962 self.stats.requests += 1;
963 self.stats.log_bytes = self.total_bytes;
964 self.stats.log_content = self.content;
965 self.stats.view_images = self.images[self.cut..].iter().sum();
966 if self.cut == 0 {
967 self.stats.pass_through += 1;
968 return None;
969 }
970 let len = self.log.len();
971 let tail_start = self.tail_index();
972 self.stats.log_messages = len;
973 self.stats.sectioned_messages = self.cut;
974 self.stats.sections = self.sections.len();
975 self.stats.block_bytes = self.block_bytes();
976 self.stats.block_tokens = summary::text_tokens(self.stats.block_bytes);
977 self.stats.band_bytes = self.bytes(self.cut, len);
978 self.stats.band_tokens = self.tokens_between(self.cut, len);
979 self.stats.tail_bytes = self.bytes(tail_start, len);
980 self.stats.tail_tokens = self.tokens_between(tail_start, len);
981 self.stats.viewed += 1;
982
983 let mut text = String::from(
984 "<transcript>\n\
985 The blocks below cover this conversation's older messages,\n\
986 oldest first. Each block is headed `id+n|`: the n messages\n\
987 from index id on, condensed. zoom(id, n) returns those n\n\
988 messages whole; long output is cut and the note names the\n\
989 `at` to resume at. The messages after the blocks are\n\
990 recent; they are whole.\n\n",
991 );
992 for section in &self.sections {
993 text.push_str(&format!(
994 "{}+{}|\n{}\n\n",
995 section.range.id, section.range.n, section.text
996 ));
997 }
998 text.push_str("</transcript>");
999 let mut out = Vec::with_capacity(len - self.cut + 1);
1000 out.push(Message::text(Role::User, text));
1001 out.extend(self.log[self.cut..].iter().cloned());
1002 Some(out)
1003 }
1004
1005 fn tail_index(&self) -> usize {
1010 let user = self
1011 .log
1012 .iter()
1013 .rposition(|message| message.role == Role::User)
1014 .unwrap_or(self.log.len());
1015 user.max(self.cut)
1016 }
1017
1018 fn bytes(&self, from: usize, to: usize) -> usize {
1020 self.sizes[from..to].iter().sum()
1021 }
1022
1023 fn tokens_between(&self, from: usize, to: usize) -> u64 {
1025 self.tokens[from..to].iter().sum()
1026 }
1027
1028 fn block_bytes(&self) -> usize {
1030 self.sections.iter().map(Section::view_bytes).sum()
1031 }
1032
1033 fn sync_sizes(&mut self) {
1037 self.sizes.truncate(self.log.len());
1038 self.tokens.truncate(self.log.len());
1039 self.images.truncate(self.log.len());
1040 let mut patched = false;
1041 while self.sizes.len() < self.log.len() {
1042 let id = self.sizes.len();
1043 self.sizes.push(summary::message_bytes(&self.log[id]));
1044 self.tokens.push(summary::message_tokens(&self.log[id]));
1045 self.images.push(summary::message_images(&self.log[id]));
1046 patched = true;
1047 }
1048 if patched {
1049 self.total_bytes = self.sizes.iter().sum();
1050 self.total_tokens = self.tokens.iter().sum();
1051 self.content = LogContent::default();
1052 for message in &self.log {
1053 add_message_content(&mut self.content, message);
1054 }
1055 }
1056 }
1057
1058 fn extend_sections(&mut self, start: usize, end: usize) -> Vec<PendingSummary> {
1063 let mut pending = Vec::new();
1064 let mut at = start;
1065 while at < end {
1066 if let Some(read) = self.read_starting(at) {
1072 let range = Range {
1073 id: at,
1074 n: read.result + 1 - at,
1075 };
1076 let name = self.skills[read.skill].name.clone();
1077 let section = match self.pinned.get(&name) {
1078 Some(carried) => Section {
1079 range,
1080 text: compact::skill_pointer_text(&name, *carried),
1081 origin: SectionOrigin::Extractive,
1082 pinned: Vec::new(),
1083 },
1084 None => {
1085 self.pinned.insert(name.clone(), range);
1086 let body = self.skills[read.skill].body.clone();
1087 Section {
1088 range,
1089 text: compact::skill_section_text(&name, &body),
1090 origin: SectionOrigin::Extractive,
1091 pinned: vec![name],
1092 }
1093 }
1094 };
1095 self.sections.push(section);
1096 at = read.result + 1;
1097 continue;
1098 }
1099 let mut stop = at;
1100 let mut bytes = 0usize;
1101 let mut count = 0usize;
1102 while stop < end {
1103 let cost = self.sizes[stop];
1104 if count > 0
1105 && (bytes + cost > self.settings.step_bytes
1106 || count >= self.settings.max_section_messages)
1107 {
1108 break;
1109 }
1110 if count > 0 && self.read_starting(stop).is_some() {
1113 break;
1114 }
1115 bytes += cost;
1116 count += 1;
1117 stop += 1;
1118 }
1119 while stop < end && self.log[stop].role == Role::Tool {
1120 stop += 1;
1121 }
1122 let range = Range {
1123 id: at,
1124 n: stop - at,
1125 };
1126 let messages = self.log[at..stop].to_vec();
1127 let text = compact::section_digest(&messages);
1128 let context = self.sections.last().map(|s| s.text.clone());
1132 self.sections.push(Section {
1133 range,
1134 text,
1135 origin: SectionOrigin::Extractive,
1136 pinned: Vec::new(),
1137 });
1138 pending.push(PendingSummary {
1139 section: self.sections.len() - 1,
1140 range,
1141 messages,
1142 context,
1143 });
1144 at = stop;
1145 }
1146 pending
1147 }
1148
1149 fn consolidate(&mut self) -> Vec<PendingSummary> {
1156 let mut pending = Vec::new();
1157 while self.sections.len() >= 2 && self.block_bytes() > self.settings.max_block_bytes {
1158 let range = Range {
1159 id: self.sections[0].range.id,
1160 n: self.sections[0].range.n + self.sections[1].range.n,
1161 };
1162 let messages = match range
1163 .id
1164 .checked_add(range.n)
1165 .and_then(|end| self.log.get(range.id..end))
1166 {
1167 Some(messages) => messages.to_vec(),
1168 None => return pending,
1172 };
1173 let mut text = compact::section_digest(&messages);
1174 let mut pinned: Vec<String> = Vec::new();
1179 for old in [&self.sections[0], &self.sections[1]] {
1180 for name in &old.pinned {
1181 if pinned.contains(name) {
1182 continue;
1183 }
1184 if let Some(skill) = self.skills.iter().find(|skill| &skill.name == name) {
1192 text.push_str("\n\n");
1193 text.push_str(&compact::skill_section_text(name, &skill.body));
1194 pinned.push(name.clone());
1195 }
1196 }
1197 }
1198 self.sections.drain(..2);
1199 self.sections.insert(
1200 0,
1201 Section {
1202 range,
1203 text,
1204 origin: SectionOrigin::Extractive,
1205 pinned,
1206 },
1207 );
1208 pending.push(PendingSummary {
1211 section: 0,
1212 range,
1213 messages,
1214 context: None,
1215 });
1216 self.stats.consolidations += 1;
1217 }
1218 pending
1219 }
1220}
1221
1222pub struct TranscriptView {
1229 inner: Arc<dyn ModelProvider>,
1230 transcript: Arc<Mutex<Transcript>>,
1231 summarizer: Option<Arc<dyn Summarizer>>,
1232}
1233
1234impl TranscriptView {
1235 pub fn new(inner: Arc<dyn ModelProvider>, transcript: Arc<Mutex<Transcript>>) -> Self {
1240 Self {
1241 inner,
1242 transcript,
1243 summarizer: None,
1244 }
1245 }
1246
1247 pub fn with_summarizer(
1251 inner: Arc<dyn ModelProvider>,
1252 transcript: Arc<Mutex<Transcript>>,
1253 summarizer: Arc<dyn Summarizer>,
1254 ) -> Self {
1255 Self {
1256 inner,
1257 transcript,
1258 summarizer: Some(summarizer),
1259 }
1260 }
1261}
1262
1263impl std::fmt::Debug for TranscriptView {
1264 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1265 f.debug_struct("TranscriptView").finish_non_exhaustive()
1267 }
1268}
1269
1270#[async_trait]
1271impl ModelProvider for TranscriptView {
1272 async fn complete(
1273 &self,
1274 mut req: rhema_core::ModelRequest,
1275 sink: &mut dyn EventSink,
1276 ) -> Result<ModelOutput, ProviderError> {
1277 let pending = {
1280 let mut transcript = self
1281 .transcript
1282 .lock()
1283 .unwrap_or_else(PoisonError::into_inner);
1284 transcript.observe(&req.messages);
1285 transcript.plan_flush()
1286 };
1287 if let Some(worker) = &self.summarizer
1293 && !pending.is_empty()
1294 {
1295 Self::spawn_worker_fill(Arc::clone(worker), Arc::clone(&self.transcript), pending);
1296 }
1297 let view = {
1298 let mut transcript = self
1299 .transcript
1300 .lock()
1301 .unwrap_or_else(PoisonError::into_inner);
1302 transcript.render()
1303 };
1304 if let Some(messages) = view {
1305 req.messages = messages;
1306 }
1307 {
1308 let mut transcript = self
1309 .transcript
1310 .lock()
1311 .unwrap_or_else(PoisonError::into_inner);
1312 transcript.stage_usage_shares(req.system.as_deref(), &req.tools, &req.messages);
1313 }
1314 let result = self.inner.complete(req, sink).await;
1315 if let Ok(output) = &result {
1316 let mut transcript = self
1317 .transcript
1318 .lock()
1319 .unwrap_or_else(PoisonError::into_inner);
1320 transcript.record_usage(&output.usage);
1321 }
1322 result
1323 }
1324}
1325
1326impl TranscriptView {
1327 fn spawn_worker_fill(
1335 worker: Arc<dyn Summarizer>,
1336 mirror: Arc<Mutex<Transcript>>,
1337 pending: Vec<PendingSummary>,
1338 ) {
1339 tokio::spawn(async move {
1340 for chunk in pending.chunks(WORKER_CONCURRENCY) {
1341 let mut fills = Vec::with_capacity(chunk.len());
1342 for item in chunk {
1343 let worker = Arc::clone(&worker);
1344 let messages = item.messages.clone();
1345 let context = item.context.clone();
1346 let section = item.section;
1347 let range = item.range;
1348 fills.push(tokio::spawn(async move {
1349 (
1350 worker.summarize(&messages, context.as_deref()).await,
1351 section,
1352 range,
1353 )
1354 }));
1355 }
1356 for fill in fills {
1357 let outcome = match fill.await {
1361 Ok((Ok(text), section, range)) => Some((text, section, range)),
1362 _ => None,
1363 };
1364 let mut transcript = mirror.lock().unwrap_or_else(PoisonError::into_inner);
1365 match outcome {
1366 Some((text, section, range)) => {
1367 let pending = PendingSummary {
1370 section,
1371 range,
1372 messages: Vec::new(),
1373 context: None,
1374 };
1375 let upgraded = transcript.commit_summary(&pending, text);
1376 transcript.record_worker_call(match upgraded {
1377 true => WorkerOutcome::Upgraded,
1378 false => WorkerOutcome::Dropped,
1379 });
1380 }
1381 None => transcript.record_worker_call(WorkerOutcome::Failed),
1382 }
1383 }
1384 }
1385 });
1386 }
1387}
1388
1389#[cfg(test)]
1390mod tests {
1391 use super::*;
1392 use rhema_core::{Content, ToolCall, ToolResult};
1393 use std::collections::HashSet;
1394 use std::sync::Mutex as StdMutex;
1395 use std::sync::atomic::{AtomicBool, Ordering};
1396
1397 async fn wait_for(done: impl Fn() -> bool) {
1400 for _ in 0..10_000 {
1401 if done() {
1402 return;
1403 }
1404 tokio::task::yield_now().await;
1405 }
1406 panic!("the background fill never finished");
1407 }
1408
1409 fn result_bytes(kb: usize) -> String {
1411 "x".repeat(kb * 1024)
1412 }
1413
1414 fn call_round(id: &str, result_kb: usize) -> Vec<Message> {
1415 vec![
1416 Message {
1417 annotations: Default::default(),
1418 role: Role::Assistant,
1419 content: vec![
1420 Content::Text("checking".into()),
1421 Content::ToolCall(ToolCall {
1422 id: id.into(),
1423 name: "bash".into(),
1424 args: serde_json::json!({ "command": "make test" }),
1425 provider_data: serde_json::Value::Null,
1426 }),
1427 ],
1428 },
1429 Message {
1430 annotations: Default::default(),
1431 role: Role::Tool,
1432 content: vec![Content::ToolResult(ToolResult::success(
1433 id,
1434 result_bytes(result_kb),
1435 ))],
1436 },
1437 ]
1438 }
1439
1440 fn long_history(rounds: usize) -> Vec<Message> {
1443 let mut messages = vec![Message::text(Role::User, "fix the build")];
1444 for i in 0..rounds {
1445 messages.extend(call_round(&format!("c{i}"), 8));
1446 }
1447 messages.push(Message::text(Role::User, "and now summarize"));
1448 messages
1449 }
1450
1451 fn settings(max_view_bytes: usize) -> TranscriptSettings {
1452 TranscriptSettings {
1453 max_view_bytes,
1454 ..TranscriptSettings::default()
1455 }
1456 }
1457
1458 #[test]
1459 fn below_the_budget_the_view_is_none() {
1460 let mut transcript = Transcript::new(settings(128_000));
1461 let messages = long_history(4); assert!(transcript.view(&messages).is_none());
1463 let stats = transcript.stats();
1464 assert_eq!(stats.requests, 1);
1465 assert_eq!(stats.pass_through, 1);
1466 assert_eq!(stats.viewed, 0);
1467 }
1468
1469 #[test]
1470 fn past_the_budget_the_aged_prefix_is_block_and_the_tail_whole() {
1471 let mut transcript = Transcript::new(settings(128_000));
1472 let messages = long_history(30); let view = transcript.view(&messages).unwrap();
1474
1475 assert_eq!(view[0].role, Role::User);
1478 let rhema_core::Content::Text(text) = &view[0].content[0] else {
1479 panic!("text view message");
1480 };
1481 assert!(text.starts_with("<transcript>"), "{text}");
1482 assert!(text.contains("zoom(id, n)"), "{text}");
1483 assert!(text.contains("0+"), "{text}");
1485
1486 let last = view.last().unwrap();
1488 assert_eq!(*last, Message::text(Role::User, "and now summarize"));
1489 assert!(view.len() < messages.len(), "the view is shorter");
1490
1491 let stats = transcript.stats();
1492 assert_eq!(stats.flushes, 1);
1493 assert_eq!(stats.sectioned_messages, transcript.cut);
1494 assert!(stats.block_bytes > 0);
1495 assert!(stats.band_bytes + stats.block_bytes < 245 * 1024);
1496 assert!(stats.block_tokens > 0);
1498 assert!(stats.band_tokens > 0);
1499 assert!(stats.tail_tokens <= stats.band_tokens);
1500 }
1501
1502 #[test]
1503 fn between_flushes_the_block_is_append_only() {
1504 let mut transcript = Transcript::new(settings(40_000));
1505 let first = long_history(5); let view = transcript.view(&first).unwrap();
1507 let first_block = match &view[0].content[..] {
1508 [rhema_core::Content::Text(text)] => text.clone(),
1509 _ => panic!("text view message"),
1510 };
1511 let sections_after_first = transcript.sections.clone();
1512
1513 let mut second = first.clone();
1516 second.extend(call_round("c5", 1));
1517 second.push(Message::text(Role::User, "next"));
1518 let view = transcript.view(&second).unwrap();
1519 let second_block = match &view[0].content[..] {
1520 [rhema_core::Content::Text(text)] => text.clone(),
1521 _ => panic!("text view message"),
1522 };
1523 assert_eq!(transcript.stats.flushes, 1, "no second flush");
1524 assert_eq!(transcript.sections, sections_after_first);
1525 assert_eq!(first_block, second_block, "the block is byte-identical");
1526 assert!(view.len() > 1);
1527 }
1528
1529 #[test]
1530 fn a_flush_overshoots_to_half_the_allowance_and_the_hysteresis_holds() {
1531 let mut transcript = Transcript::new(settings(128_000));
1532 let mut messages = vec![Message::text(Role::User, "fix the build")];
1533 for i in 0..20 {
1534 messages.extend(call_round(&format!("c{i}"), 8)); }
1536 messages.push(Message::text(Role::User, "go on"));
1537 assert!(transcript.view(&messages).is_some());
1538 let stats = transcript.stats();
1539 assert_eq!(stats.flushes, 1);
1540 let allowance = 128_000 - stats.tail_bytes;
1543 let band = stats.band_bytes - stats.tail_bytes;
1544 assert!(
1545 band <= allowance / 2,
1546 "band {band} over half the allowance {}",
1547 allowance / 2
1548 );
1549 let mut grown = messages.clone();
1552 for i in 20..26 {
1553 grown.extend(call_round(&format!("c{i}"), 8)); }
1555 grown.push(Message::text(Role::User, "still going"));
1556 transcript.view(&grown);
1557 assert_eq!(transcript.stats.flushes, 1, "flushed inside the hysteresis");
1558 }
1559
1560 #[test]
1561 fn a_flush_never_splits_a_tool_round_at_a_section_boundary() {
1562 let mut transcript = Transcript::new(settings(20_000));
1563 let messages = vec![Message::text(Role::User, "go")]
1565 .into_iter()
1566 .chain(call_round("c0", 16))
1567 .chain(call_round("c1", 16))
1568 .chain(std::iter::once(Message::text(Role::User, "done")))
1569 .collect::<Vec<_>>();
1570 let view = transcript.view(&messages).unwrap();
1571 let carried_calls: HashSet<String> = view
1574 .iter()
1575 .flat_map(|m| &m.content)
1576 .filter_map(|c| match c {
1577 rhema_core::Content::ToolCall(call) => Some(call.id.clone()),
1578 _ => None,
1579 })
1580 .collect();
1581 for message in &view {
1582 for content in &message.content {
1583 if let rhema_core::Content::ToolResult(result) = content {
1584 assert!(
1585 carried_calls.contains(&result.id),
1586 "orphan result {} in the view",
1587 result.id
1588 );
1589 }
1590 }
1591 }
1592 for section in &transcript.sections {
1596 let first = transcript
1597 .range(section.range)
1598 .expect("section in the log")
1599 .first()
1600 .unwrap();
1601 assert_ne!(first.role, Role::Tool, "section {:?}", section.range);
1602 }
1603 }
1604
1605 #[test]
1606 fn sections_respect_the_step_and_message_bounds() {
1607 let mut transcript = Transcript::new(TranscriptSettings {
1608 step_bytes: 20_000,
1609 max_section_messages: 3,
1610 ..settings(20_000)
1611 });
1612 let messages = long_history(8);
1613 transcript.observe(&messages);
1614 transcript.plan_flush();
1615 assert!(transcript.sections.len() > 1, "bounds force a split");
1616 for section in &transcript.sections {
1617 assert!(section.range.n <= 4, "{:?}", section.range);
1618 }
1619 let mut at = 0;
1621 for section in &transcript.sections {
1622 assert_eq!(section.range.id, at);
1623 at += section.range.n;
1624 }
1625 assert_eq!(at, transcript.cut);
1626 }
1627
1628 #[test]
1629 fn a_worker_upgrade_lands_and_a_wrong_one_is_rejected() {
1630 let mut transcript = Transcript::new(settings(20_000));
1631 let messages = long_history(30);
1632 transcript.observe(&messages);
1633 let pending = transcript.plan_flush();
1634 assert!(!pending.is_empty());
1635
1636 let good = pending[0].clone();
1637 assert!(transcript.commit_summary(&good, "## Goals Met\n- all".into()));
1638 assert_eq!(transcript.sections[0].text, "## Goals Met\n- all");
1639 assert_eq!(transcript.sections[0].origin, SectionOrigin::Model);
1640
1641 let stale = PendingSummary {
1644 section: pending[0].section,
1645 range: Range { id: 999, n: 1 },
1646 messages: Vec::new(),
1647 context: None,
1648 };
1649 assert!(!transcript.commit_summary(&stale, "ghost".into()));
1650 assert_eq!(transcript.sections[0].text, "## Goals Met\n- all");
1651 }
1652
1653 #[test]
1654 fn a_resume_adopts_the_saved_sections_and_skips_the_refill() {
1655 let log = long_history(30);
1656 let mut first = Transcript::new(settings(20_000));
1658 first.observe(&log);
1659 let pending = first.plan_flush();
1660 assert!(!pending.is_empty());
1661 for item in &pending {
1662 assert!(first.commit_summary(item, format!("## Goals Met\n- model {}", item.section)));
1663 }
1664 let saved = first.saved_sections();
1665 assert!(saved.iter().all(|s| s.origin == SectionOrigin::Model));
1666
1667 let mut second = Transcript::new(settings(20_000));
1670 second.adopt_sections(saved.clone());
1671 second.observe(&log);
1672 assert_eq!(second.cut, first.cut);
1673 assert_eq!(second.sections, saved);
1674 assert!(second.plan_flush().is_empty());
1676
1677 let mut extended = log.clone();
1679 extended.push(Message::text(Role::User, "one more"));
1680 second.observe(&extended);
1681 let view = second.render().unwrap();
1682 assert_eq!(view.last(), Some(&Message::text(Role::User, "one more")));
1683 }
1684
1685 fn skill_body(name: &str, rules: usize) -> String {
1689 let mut body = format!("---\nname: {name}\ndescription: the {name} trigger\n---\n\n");
1690 for i in 0..rules {
1691 body.push_str(&format!("Rule {i}: do the {name} thing.\n"));
1692 }
1693 body
1694 }
1695
1696 fn cat_result(id: &str, stdout: &str) -> Message {
1700 Message {
1701 annotations: Default::default(),
1702 role: Role::Tool,
1703 content: vec![Content::ToolResult(ToolResult::success(
1704 id,
1705 format!("exit code 0\n--- stdout ---\n{stdout}\n--- stderr ---\n"),
1706 ))],
1707 }
1708 }
1709
1710 fn skill_round(id: &str, name: &str, rules: usize) -> Vec<Message> {
1712 let body = skill_body(name, rules);
1713 vec![
1714 Message {
1715 annotations: Default::default(),
1716 role: Role::Assistant,
1717 content: vec![
1718 Content::Text("loading the skill".into()),
1719 Content::ToolCall(ToolCall {
1720 id: id.into(),
1721 name: "bash".into(),
1722 args: serde_json::json!({
1723 "command": format!("cat .rhema/skills/{name}/SKILL.md")
1724 }),
1725 provider_data: serde_json::Value::Null,
1726 }),
1727 ],
1728 },
1729 cat_result(id, &body),
1730 ]
1731 }
1732
1733 #[test]
1734 fn a_flushed_skill_read_rides_the_block_whole_and_unsummarized() {
1735 let mut transcript = Transcript::new(settings(40_000));
1736 transcript.set_skills(vec![SkillText {
1737 name: "unslop".into(),
1738 body: skill_body("unslop", 40),
1739 }]);
1740 let mut messages = vec![Message::text(Role::User, "fix the build")];
1741 messages.extend(skill_round("s1", "unslop", 40));
1742 messages.extend(long_history(6));
1743 messages.push(Message::text(Role::User, "and now summarize"));
1744
1745 transcript.observe(&messages);
1746 let pending = transcript.plan_flush();
1747 let body = skill_body("unslop", 40);
1748
1749 let pinned = transcript
1753 .sections
1754 .iter()
1755 .find(|section| !section.pinned.is_empty())
1756 .expect("one pinned section");
1757 assert_eq!(pinned.pinned, ["unslop"]);
1758 assert_eq!(pinned.range.n, 2);
1759 assert!(pinned.text.contains(&body), "{}", pinned.text);
1760 assert!(!pending.iter().any(|summary| summary.range == pinned.range));
1761
1762 let view = transcript.render().unwrap();
1765 let rhema_core::Content::Text(text) = &view[0].content[0] else {
1766 panic!("text view message");
1767 };
1768 assert!(text.contains(&body), "{text}");
1769 }
1770
1771 #[test]
1772 fn a_reread_compacts_to_a_pointer_at_the_first_copy() {
1773 let mut transcript = Transcript::new(settings(40_000));
1774 transcript.set_skills(vec![SkillText {
1775 name: "unslop".into(),
1776 body: skill_body("unslop", 40),
1777 }]);
1778 let mut messages = vec![Message::text(Role::User, "fix the build")];
1779 messages.extend(skill_round("s1", "unslop", 40));
1780 messages.extend(skill_round("s2", "unslop", 40));
1781 messages.extend(long_history(6));
1782 messages.push(Message::text(Role::User, "and now summarize"));
1783
1784 transcript.observe(&messages);
1785 transcript.plan_flush();
1786
1787 let pinned: Vec<_> = transcript
1788 .sections
1789 .iter()
1790 .filter(|section| !section.pinned.is_empty())
1791 .collect();
1792 assert_eq!(pinned.len(), 1, "one carrier");
1793 let carried = pinned[0].range;
1794 let body = skill_body("unslop", 40);
1795 let view = transcript.render().unwrap();
1796 let rhema_core::Content::Text(text) = &view[0].content[0] else {
1797 panic!("text view message");
1798 };
1799 assert_eq!(text.matches(&body).count(), 1, "one copy of the body");
1800 assert!(
1801 text.contains(&format!(
1802 "skill unslop read again; its whole text is carried at {}+{}|",
1803 carried.id, carried.n
1804 )),
1805 "{text}"
1806 );
1807 }
1808
1809 #[test]
1810 fn a_multicall_turn_digests_normally_without_a_pin() {
1811 let mut transcript = Transcript::new(settings(40_000));
1812 transcript.set_skills(vec![SkillText {
1813 name: "unslop".into(),
1814 body: skill_body("unslop", 40),
1815 }]);
1816 let mut messages = vec![Message::text(Role::User, "fix the build")];
1817 messages.push(Message {
1820 annotations: Default::default(),
1821 role: Role::Assistant,
1822 content: vec![
1823 Content::ToolCall(ToolCall {
1824 id: "a".into(),
1825 name: "bash".into(),
1826 args: serde_json::json!({ "command": "cat the skill" }),
1827 provider_data: serde_json::Value::Null,
1828 }),
1829 Content::ToolCall(ToolCall {
1830 id: "b".into(),
1831 name: "bash".into(),
1832 args: serde_json::json!({ "command": "make test" }),
1833 provider_data: serde_json::Value::Null,
1834 }),
1835 ],
1836 });
1837 messages.push(cat_result("a", &skill_body("unslop", 40)));
1838 messages.push(cat_result("b", "ok"));
1839 messages.extend(long_history(6));
1840 messages.push(Message::text(Role::User, "and now summarize"));
1841
1842 transcript.observe(&messages);
1843 transcript.plan_flush();
1844 assert!(
1845 transcript.sections.iter().all(|s| s.pinned.is_empty()),
1846 "{:?}",
1847 transcript.sections
1848 );
1849 }
1850
1851 #[test]
1852 fn consolidation_keeps_the_pinned_body_in_the_block() {
1853 let mut transcript = Transcript::new(TranscriptSettings {
1854 max_view_bytes: 40_000,
1855 step_bytes: 4_000,
1856 max_block_bytes: 1_000,
1857 ..TranscriptSettings::default()
1858 });
1859 transcript.set_skills(vec![SkillText {
1860 name: "unslop".into(),
1861 body: skill_body("unslop", 40),
1862 }]);
1863 let mut messages = vec![Message::text(Role::User, "fix the build")];
1864 messages.extend(skill_round("s1", "unslop", 40));
1865 messages.extend(long_history(30));
1866 messages.push(Message::text(Role::User, "and now summarize"));
1867
1868 transcript.observe(&messages);
1869 transcript.plan_flush();
1870 let body = skill_body("unslop", 40);
1871 assert!(
1872 transcript.stats.consolidations > 0,
1873 "the fixture must consolidate"
1874 );
1875 let view = transcript.render().unwrap();
1876 let rhema_core::Content::Text(text) = &view[0].content[0] else {
1877 panic!("text view message");
1878 };
1879 assert!(text.contains(&body), "{text}");
1880 }
1881
1882 #[test]
1883 fn the_model_fill_leaves_the_pinned_body_beneath_it() {
1884 let mut transcript = Transcript::new(TranscriptSettings {
1885 max_view_bytes: 40_000,
1886 step_bytes: 4_000,
1887 max_block_bytes: 1_000,
1888 ..TranscriptSettings::default()
1889 });
1890 transcript.set_skills(vec![SkillText {
1891 name: "unslop".into(),
1892 body: skill_body("unslop", 40),
1893 }]);
1894 let mut messages = vec![Message::text(Role::User, "fix the build")];
1895 messages.extend(skill_round("s1", "unslop", 40));
1896 messages.extend(long_history(30));
1897 messages.push(Message::text(Role::User, "and now summarize"));
1898
1899 transcript.observe(&messages);
1900 let pending = transcript.plan_flush();
1901 let body = skill_body("unslop", 40);
1902
1903 let summary = pending
1906 .iter()
1907 .rev()
1908 .find(|summary| {
1909 transcript
1910 .sections
1911 .get(summary.section)
1912 .is_some_and(|section| {
1913 section.range == summary.range && !section.pinned.is_empty()
1914 })
1915 })
1916 .expect("a live union pending over a pinned section")
1917 .clone();
1918 assert!(transcript.commit_summary(&summary, "## Goals Met\n- dense fill".into()));
1919 let text = &transcript.sections[summary.section].text;
1920 assert!(text.starts_with("## Goals Met\n- dense fill"), "{text}");
1921 assert!(text.contains(&body), "{text}");
1922 }
1923
1924 #[test]
1925 fn a_fill_lands_after_the_flushs_own_consolidation_moves_it() {
1926 let mut transcript = Transcript::new(TranscriptSettings {
1933 max_view_bytes: 40_000,
1934 step_bytes: 4_000,
1935 max_block_bytes: 1_000,
1936 ..TranscriptSettings::default()
1937 });
1938 let mut messages = vec![Message::text(Role::User, "fix the build")];
1939 messages.extend(long_history(30));
1940 messages.push(Message::text(Role::User, "and now summarize"));
1941 transcript.observe(&messages);
1942 let pending = transcript.plan_flush();
1943 assert!(
1944 transcript.stats.consolidations > 0,
1945 "the fixture must consolidate"
1946 );
1947
1948 let moved = pending.iter().filter(|summary| {
1949 transcript
1950 .sections
1951 .get(summary.section)
1952 .is_none_or(|section| section.range != summary.range)
1953 });
1954 assert!(
1955 moved.count() > 0,
1956 "the fixture must move a commissioned section"
1957 );
1958
1959 for summary in &pending {
1960 let index = transcript
1961 .sections
1962 .iter()
1963 .position(|section| section.range == summary.range);
1964 let committed = transcript.commit_summary(summary, "## dense fill".into());
1965 assert_eq!(
1966 index.is_some(),
1967 committed,
1968 "the range decides, not the index"
1969 );
1970 if let Some(index) = index {
1971 assert_eq!(transcript.sections[index].text, "## dense fill");
1972 assert!(matches!(
1973 transcript.sections[index].origin,
1974 SectionOrigin::Model
1975 ));
1976 }
1977 }
1978 }
1979
1980 #[test]
1981 fn a_merge_drops_a_pin_the_discovery_no_longer_holds() {
1982 let mut transcript = Transcript::new(TranscriptSettings {
1987 max_view_bytes: 40_000,
1988 step_bytes: 4_000,
1989 max_block_bytes: 1_000,
1990 ..TranscriptSettings::default()
1991 });
1992 transcript.set_skills(vec![SkillText {
1993 name: "unslop".into(),
1994 body: skill_body("unslop", 40),
1995 }]);
1996 let mut messages = vec![Message::text(Role::User, "fix the build")];
1997 messages.extend(skill_round("s1", "unslop", 40));
1998 messages.extend(long_history(6));
1999 messages.push(Message::text(Role::User, "and now summarize"));
2000 transcript.observe(&messages);
2001 let pending = transcript.plan_flush();
2002 drop(pending);
2003 assert!(
2004 transcript
2005 .sections
2006 .iter()
2007 .any(|section| section.pinned.iter().any(|name| name == "unslop")),
2008 "the fixture must pin the skill first"
2009 );
2010
2011 transcript.set_skills(Vec::new());
2015 let mut messages2 = messages;
2016 messages2.extend(long_history(6));
2017 messages2.push(Message::text(Role::User, "carry on"));
2018 transcript.observe(&messages2);
2019 let pending = transcript.plan_flush();
2020 drop(pending);
2021 assert!(
2022 transcript.stats.consolidations > 0,
2023 "the fixture must consolidate the merge"
2024 );
2025 assert!(
2026 transcript
2027 .sections
2028 .iter()
2029 .all(|section| !section.pinned.iter().any(|name| name == "unslop")),
2030 "a claim without its body is a lie"
2031 );
2032 transcript.observe(&messages2);
2035 assert!(!transcript.pinned.contains_key("unslop"));
2036 }
2037
2038 #[test]
2039 fn a_resume_keeps_deduplicating_rereads() {
2040 let mut first = Transcript::new(settings(40_000));
2041 first.set_skills(vec![SkillText {
2042 name: "unslop".into(),
2043 body: skill_body("unslop", 40),
2044 }]);
2045 let mut messages = vec![Message::text(Role::User, "fix the build")];
2046 messages.extend(skill_round("s1", "unslop", 40));
2047 messages.extend(long_history(8));
2048 messages.push(Message::text(Role::User, "and now summarize"));
2049 first.observe(&messages);
2050 first.plan_flush();
2051 let saved = first.saved_sections();
2052 assert!(!saved.is_empty(), "the first session must have flushed");
2053
2054 let mut second = Transcript::new(settings(40_000));
2057 second.adopt_sections(saved);
2058 let mut resumed = messages.clone();
2059 resumed.extend(skill_round("s2", "unslop", 40));
2060 resumed.extend(long_history(2));
2061 resumed.push(Message::text(Role::User, "one more"));
2062 second.observe(&resumed);
2063 second.plan_flush();
2064 let body = skill_body("unslop", 40);
2065 let view = second.render().unwrap();
2066 let rhema_core::Content::Text(text) = &view[0].content[0] else {
2067 panic!("text view message");
2068 };
2069 assert_eq!(text.matches(&body).count(), 1, "one copy after resume");
2070 }
2071
2072 #[test]
2073 fn tampered_saved_sections_fall_back_to_the_rebuild() {
2074 let mut transcript = Transcript::new(settings(20_000));
2075 transcript.adopt_sections(vec![Section {
2076 range: Range { id: 5, n: 9 },
2077 text: "## Goals Met\n- orphan".into(),
2078 origin: SectionOrigin::Model,
2079 pinned: Vec::new(),
2080 }]);
2081 transcript.observe(&long_history(30));
2082 assert_eq!(transcript.cut, 0);
2084 assert!(transcript.sections.is_empty());
2085 assert!(!transcript.plan_flush().is_empty());
2087 }
2088
2089 #[test]
2090 fn a_pending_summary_carries_the_adjacent_digest_as_context() {
2091 let mut transcript = Transcript::new(settings(20_000));
2092 transcript.observe(&long_history(30));
2093 let pending = transcript.plan_flush();
2094 assert!(pending.len() >= 2);
2095 assert_eq!(pending[0].context, None);
2098 for (prev, item) in pending.iter().zip(pending.iter().skip(1)) {
2099 let expected = transcript.sections[prev.section].text.clone();
2100 assert_eq!(item.context.as_deref(), Some(expected.as_str()));
2101 }
2102
2103 let first = pending[0].clone();
2106 assert!(transcript.commit_summary(&first, "## Goals Met\n- model".into()));
2107 let mut extended = long_history(30);
2108 for i in 0..12 {
2109 extended.push(Message::text(
2110 Role::User,
2111 format!("extra filler {i}: {}", "y".repeat(1024)),
2112 ));
2113 }
2114 transcript.observe(&extended);
2115 let expected = transcript.sections.last().unwrap().text.clone();
2118 let pending = transcript.plan_flush();
2119 assert!(!pending.is_empty());
2120 assert_eq!(pending[0].context.as_deref(), Some(expected.as_str()));
2121 }
2122
2123 #[test]
2124 fn the_block_consolidates_past_its_cap() {
2125 let mut transcript = Transcript::new(TranscriptSettings {
2126 max_block_bytes: 500,
2127 ..settings(20_000)
2128 });
2129 let messages = long_history(30);
2130 transcript.observe(&messages);
2131 transcript.plan_flush();
2132 assert!(transcript.block_bytes() <= 500);
2133 assert!(transcript.stats.consolidations > 0);
2134 let mut at = 0;
2136 for section in &transcript.sections {
2137 assert_eq!(section.range.id, at);
2138 at += section.range.n;
2139 }
2140 assert_eq!(at, transcript.cut);
2141 }
2142
2143 #[test]
2144 fn a_resumed_session_rebuilds_the_compaction_from_nothing() {
2145 let mut transcript = Transcript::new(settings(20_000));
2146 transcript.observe(&long_history(30));
2147 transcript.plan_flush();
2148 assert!(transcript.cut > 0);
2149 transcript.observe(&long_history(2));
2151 assert_eq!(transcript.cut, 0);
2152 assert!(transcript.sections.is_empty());
2153 }
2154
2155 #[test]
2156 fn the_breakdown_spreads_reported_input_by_wire_share() {
2157 let mut transcript = Transcript::new(TranscriptSettings::default());
2158 transcript.set_skills_bytes(500);
2159 let system = format!("{}{}", "b".repeat(1_500), "s".repeat(500));
2162 let call_args = serde_json::json!({ "c": "x".repeat(100) });
2163 let messages = vec![
2164 Message::text(Role::User, "u".repeat(1_000)),
2165 Message {
2166 annotations: Default::default(),
2167 role: Role::Assistant,
2168 content: vec![
2169 Content::Text("a".repeat(400)),
2170 Content::ToolCall(ToolCall {
2171 id: "c1".into(),
2172 name: "bash".into(),
2173 args: call_args.clone(),
2174 provider_data: serde_json::Value::Null,
2175 }),
2176 ],
2177 },
2178 Message {
2179 annotations: Default::default(),
2180 role: Role::Tool,
2181 content: vec![Content::ToolResult(ToolResult::success(
2182 "c1",
2183 "r".repeat(1_000),
2184 ))],
2185 },
2186 ];
2187 transcript.stage_usage_shares(Some(&system), &[], &messages);
2188 transcript.record_usage(&Usage {
2189 input_tokens: 10_000,
2190 output_tokens: 100,
2191 cached_input_tokens: 0,
2192 });
2193
2194 let total = 2_000 + 1_000 + 400 + ("bash".len() + call_args.to_string().len()) + 1_000;
2195 let spread = |bytes: usize| 10_000 * bytes as u64 / total as u64;
2196 let b = transcript.stats().usage;
2197 assert_eq!(b.system_prompt_tokens, spread(1_500));
2198 assert_eq!(b.skills_tokens, spread(500));
2199 assert_eq!(
2200 b.tool_calls_input_tokens,
2201 spread("bash".len() + call_args.to_string().len())
2202 );
2203 assert_eq!(b.tool_calls_output_tokens, spread(1_000));
2204 assert_eq!(b.user_messages_tokens, spread(1_000));
2205 assert_eq!(b.model_output_tokens, spread(400) + 100);
2208 transcript.record_usage(&Usage {
2211 input_tokens: 1_000,
2212 output_tokens: 0,
2213 cached_input_tokens: 0,
2214 });
2215 assert_eq!(transcript.stats().usage.user_messages_tokens, spread(1_000));
2216 }
2217
2218 #[test]
2219 fn a_skills_share_past_the_system_clamps() {
2220 let mut transcript = Transcript::new(TranscriptSettings::default());
2221 transcript.set_skills_bytes(9_999);
2222 transcript.stage_usage_shares(Some("short"), &[], &[]);
2223 transcript.record_usage(&Usage {
2224 input_tokens: 100,
2225 output_tokens: 0,
2226 cached_input_tokens: 0,
2227 });
2228 let b = transcript.stats().usage;
2229 assert_eq!(b.skills_tokens, 100);
2230 assert_eq!(b.system_prompt_tokens, 0);
2231 }
2232
2233 #[test]
2234 fn a_carry_continues_the_saved_run() {
2235 let saved = TranscriptStats {
2236 requests: 10,
2237 pass_through: 6,
2238 viewed: 4,
2239 flushes: 1,
2240 consolidations: 1,
2241 summarizer_calls: 2,
2242 summarizer_failures: 1,
2243 input_tokens: 90_000,
2244 cached_input_tokens: 70_000,
2245 output_tokens: 10_000,
2246 usage: UsageBreakdown {
2247 system_prompt_tokens: 20_000,
2248 skills_tokens: 2_000,
2249 tool_calls_input_tokens: 30_000,
2250 tool_calls_output_tokens: 30_000,
2251 user_messages_tokens: 8_000,
2252 model_output_tokens: 10_000,
2253 },
2254 log_messages: 12,
2256 sectioned_messages: 4,
2257 sections: 2,
2258 block_bytes: 900,
2259 block_tokens: 225,
2260 band_bytes: 3_000,
2261 band_tokens: 820,
2262 view_images: 2,
2263 tail_bytes: 1_200,
2264 tail_tokens: 340,
2265 log_bytes: 5_400,
2266 log_content: LogContent {
2267 tool_calls: 100,
2268 tool_results: 4_000,
2269 user_text: 300,
2270 assistant_text: 1_000,
2271 },
2272 };
2273
2274 let mut fresh = TranscriptStats::default();
2278 fresh.carry(&saved);
2279 assert_eq!(fresh, saved);
2280
2281 let mut live = TranscriptStats {
2285 requests: 2,
2286 input_tokens: 5_000,
2287 output_tokens: 300,
2288 usage: UsageBreakdown {
2289 user_messages_tokens: 5_000,
2290 model_output_tokens: 300,
2291 ..UsageBreakdown::default()
2292 },
2293 log_messages: 4,
2294 block_bytes: 100,
2295 ..TranscriptStats::default()
2296 };
2297 live.carry(&saved);
2298 assert_eq!(live.requests, 12);
2299 assert_eq!(live.input_tokens, 95_000);
2300 assert_eq!(live.output_tokens, 10_300);
2301 assert_eq!(live.usage.user_messages_tokens, 13_000);
2302 assert_eq!(live.usage.model_output_tokens, 10_300);
2303 assert_eq!(live.usage.system_prompt_tokens, 20_000);
2304 assert_eq!(live.block_bytes, 100, "the live mirror's snapshot");
2305 assert_eq!(live.log_messages, 4);
2306
2307 let mut later = TranscriptStats {
2310 requests: 3,
2311 input_tokens: 8_000,
2312 ..TranscriptStats::default()
2313 };
2314 later.carry(&saved);
2315 assert_eq!(later.requests, 13);
2316 assert_eq!(later.input_tokens, 98_000);
2317 }
2318
2319 fn image_history(n: usize) -> Vec<Message> {
2323 (0..n)
2324 .map(|i| Message {
2325 annotations: Default::default(),
2326 role: Role::User,
2327 content: vec![
2328 Content::Text(format!("look {i}")),
2329 Content::Image(rhema_core::Image::new(
2330 rhema_core::ImageMediaType::Png,
2331 "AAAA",
2332 )),
2333 ],
2334 })
2335 .collect()
2336 }
2337
2338 #[test]
2342 fn the_image_cap_flushes_below_the_byte_budget() {
2343 let mut transcript = Transcript::new(TranscriptSettings {
2344 max_view_images: 2,
2345 ..settings(128_000)
2346 });
2347 let messages = image_history(5);
2348 transcript.observe(&messages);
2349 let pending = transcript.plan_flush();
2350 assert!(
2351 !pending.is_empty(),
2352 "the cap flushes what bytes never would"
2353 );
2354 assert_eq!(transcript.cut, 3);
2355 assert_eq!(transcript.stats.flushes, 1);
2356 let mut at = 0;
2358 for section in &transcript.sections {
2359 assert_eq!(section.range.id, at);
2360 at += section.range.n;
2361 }
2362 assert_eq!(at, 3);
2363 let digest = &transcript.sections.last().unwrap().text;
2365 assert!(digest.contains("3 images"), "{digest}");
2366 transcript.render();
2367 assert_eq!(transcript.stats().view_images, 2);
2368 }
2369
2370 #[test]
2374 fn one_turn_past_the_image_cap_sends_whole_and_counts() {
2375 let mut transcript = Transcript::new(TranscriptSettings {
2376 max_view_images: 2,
2377 ..settings(128_000)
2378 });
2379 let messages = vec![Message {
2380 annotations: Default::default(),
2381 role: Role::User,
2382 content: vec![
2383 Content::Text("three shots".into()),
2384 Content::Image(rhema_core::Image::new(rhema_core::ImageMediaType::Png, "A")),
2385 Content::Image(rhema_core::Image::new(rhema_core::ImageMediaType::Png, "B")),
2386 Content::Image(rhema_core::Image::new(rhema_core::ImageMediaType::Png, "C")),
2387 ],
2388 }];
2389 transcript.observe(&messages);
2390 assert!(transcript.plan_flush().is_empty());
2391 assert_eq!(transcript.cut, 0);
2392 transcript.render();
2393 assert_eq!(transcript.stats().view_images, 3);
2394 }
2395
2396 #[test]
2400 fn the_log_bytes_snapshot_counts_the_log_once() {
2401 let mut transcript = Transcript::new(settings(128_000));
2402 let messages = long_history(4); transcript.observe(&messages);
2404 transcript.render();
2405 let expected: usize = messages.iter().map(summary::message_bytes).sum();
2406 assert_eq!(transcript.stats().log_bytes, expected);
2407
2408 let grown = long_history(5);
2410 transcript.observe(&grown);
2411 transcript.render();
2412 let expected: usize = grown.iter().map(summary::message_bytes).sum();
2413 assert_eq!(transcript.stats().log_bytes, expected);
2414 }
2415
2416 #[test]
2421 fn the_content_split_counts_each_message_once() {
2422 let mut transcript = Transcript::new(settings(128_000));
2423 let messages = long_history(4);
2424 transcript.observe(&messages);
2425 transcript.render();
2426 let content = transcript.stats().log_content;
2427 assert_eq!(
2428 content.tool_results,
2429 4 * summary::text_tokens(result_bytes(8).len())
2430 );
2431 assert_eq!(
2432 content.assistant_text,
2433 4 * summary::text_tokens("checking".len())
2434 );
2435 assert_eq!(
2436 content.user_text,
2437 summary::text_tokens("fix the build".len())
2438 + summary::text_tokens("and now summarize".len())
2439 );
2440 let args = serde_json::json!({ "command": "make test" }).to_string();
2441 assert_eq!(
2442 content.tool_calls,
2443 4 * summary::text_tokens("bash".len() + args.len())
2444 );
2445 let expected: u64 = messages.iter().map(summary::message_tokens).sum();
2448 assert_eq!(content.total(), expected);
2449 }
2450
2451 #[test]
2452 fn an_image_costs_one_message_in_the_split_and_the_budget() {
2453 let mut transcript = Transcript::new(settings(128_000));
2454 transcript.observe(&[Message {
2455 annotations: Default::default(),
2456 role: Role::Tool,
2457 content: vec![Content::ToolResult(
2458 ToolResult::success("c1", "ok").with_images(vec![rhema_core::Image::new(
2459 rhema_core::ImageMediaType::Png,
2460 "A".repeat(2_000_000),
2461 )]),
2462 )],
2463 }]);
2464 transcript.render();
2465 let stats = transcript.stats();
2466 assert_eq!(stats.log_bytes, 2 + summary::IMAGE_BYTES);
2469 assert_eq!(stats.log_content.tool_results, summary::IMAGE_TOKENS);
2471 }
2472
2473 #[test]
2474 fn reset_stats_zeroes_the_accounting_and_keeps_the_log() {
2475 let mut transcript = Transcript::new(TranscriptSettings::default());
2476 transcript.observe(&[Message::text(Role::User, "kept")]);
2477 transcript.record_usage(&Usage {
2478 input_tokens: 1_000,
2479 output_tokens: 100,
2480 cached_input_tokens: 0,
2481 });
2482 assert_eq!(transcript.len(), 1);
2483 transcript.reset_stats();
2484 assert_eq!(transcript.stats(), TranscriptStats::default());
2485 assert_eq!(transcript.len(), 1);
2486 }
2487
2488 #[test]
2489 fn usage_records_and_the_hit_rate_reads() {
2490 let mut transcript = Transcript::new(TranscriptSettings::default());
2491 assert!(transcript.stats().cache_hit_rate().is_none());
2492 transcript.record_usage(&Usage {
2493 input_tokens: 1_000,
2494 output_tokens: 100,
2495 cached_input_tokens: 800,
2496 });
2497 let stats = transcript.stats();
2498 assert_eq!(stats.input_tokens, 1_000);
2499 assert_eq!(stats.cached_input_tokens, 800);
2500 let rate = stats.cache_hit_rate().unwrap();
2501 assert!((rate - 0.8).abs() < 1e-9);
2502 }
2503
2504 struct Recording(StdMutex<Vec<Vec<Message>>>);
2506 #[async_trait]
2507 impl ModelProvider for Recording {
2508 async fn complete(
2509 &self,
2510 req: rhema_core::ModelRequest,
2511 _sink: &mut dyn EventSink,
2512 ) -> Result<ModelOutput, ProviderError> {
2513 self.0.lock().unwrap().push(req.messages);
2514 Ok(ModelOutput {
2515 message: Message::text(Role::Assistant, "done"),
2516 stop_reason: rhema_core::StopReason::EndTurn,
2517 usage: Usage {
2518 input_tokens: 500,
2519 output_tokens: 10,
2520 cached_input_tokens: 400,
2521 },
2522 })
2523 }
2524 }
2525
2526 #[tokio::test]
2527 async fn the_decorator_rewrites_the_request_and_the_mirror_stays_whole() {
2528 let recording = Arc::new(Recording(StdMutex::new(Vec::new())));
2529 let transcript = Arc::new(Mutex::new(Transcript::new(settings(20_000))));
2530 let view = TranscriptView::new(recording.clone(), transcript.clone());
2531 let messages = long_history(30);
2532 let req = rhema_core::ModelRequest {
2533 system: None,
2534 messages: messages.clone(),
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();
2540
2541 let seen = recording.0.lock().unwrap();
2542 let sent = &seen[0];
2543 assert!(sent.len() < messages.len());
2544 assert_eq!(sent.last().unwrap().role, Role::User);
2545 let mirror = transcript.lock().unwrap();
2547 assert_eq!(mirror.len(), messages.len());
2548 assert_eq!(mirror.message(0), Some(&messages[0]));
2549 assert_eq!(mirror.stats().cache_hit_rate(), Some(0.8));
2551 }
2552
2553 #[tokio::test]
2554 async fn the_decorator_upgrades_sections_with_its_summarizer() {
2555 struct Worker;
2557 #[async_trait]
2558 impl ModelProvider for Worker {
2559 async fn complete(
2560 &self,
2561 _req: rhema_core::ModelRequest,
2562 _sink: &mut dyn EventSink,
2563 ) -> Result<ModelOutput, ProviderError> {
2564 Ok(ModelOutput {
2565 message: Message::text(Role::Assistant, "## Goals Met\n- worker wrote this"),
2566 stop_reason: rhema_core::StopReason::EndTurn,
2567 usage: Usage::default(),
2568 })
2569 }
2570 }
2571
2572 let recording = Arc::new(Recording(StdMutex::new(Vec::new())));
2573 let transcript = Arc::new(Mutex::new(Transcript::new(settings(20_000))));
2574 let view = TranscriptView::with_summarizer(
2575 recording.clone(),
2576 transcript.clone(),
2577 Arc::new(compact::ModelSummarizer::new(Arc::new(Worker), "cheap")),
2578 );
2579 let req = rhema_core::ModelRequest {
2580 system: None,
2581 messages: long_history(30),
2582 tools: Vec::new(),
2583 params: rhema_core::ChatParams::new("m"),
2584 };
2585 let mut sink = NoopSink;
2586 view.complete(req, &mut sink).await.unwrap();
2587
2588 {
2591 let sent = recording.0.lock().unwrap();
2592 let rhema_core::Content::Text(text) = &sent[0][0].content[0] else {
2593 panic!("text view message");
2594 };
2595 assert!(!text.contains("worker wrote this"), "{text}");
2596 }
2597
2598 wait_for(|| {
2600 transcript
2601 .lock()
2602 .unwrap()
2603 .sections
2604 .iter()
2605 .all(|s| s.origin == SectionOrigin::Model)
2606 })
2607 .await;
2608
2609 {
2612 let mirror = transcript.lock().unwrap();
2613 let stats = mirror.stats();
2614 assert!(stats.summarizer_calls > 0);
2615 assert_eq!(stats.summarizer_failures, 0);
2616 assert!(
2617 mirror
2618 .sections
2619 .iter()
2620 .all(|s| s.text.contains("worker wrote this"))
2621 );
2622 }
2623
2624 let req = rhema_core::ModelRequest {
2626 system: None,
2627 messages: long_history(30),
2628 tools: Vec::new(),
2629 params: rhema_core::ChatParams::new("m"),
2630 };
2631 let mut sink = NoopSink;
2632 view.complete(req, &mut sink).await.unwrap();
2633 let sent = recording.0.lock().unwrap();
2634 let rhema_core::Content::Text(text) = &sent[1][0].content[0] else {
2635 panic!("text view message");
2636 };
2637 assert!(text.contains("worker wrote this"), "{text}");
2638 }
2639
2640 #[tokio::test]
2641 async fn a_failing_summarizer_never_blocks_the_request() {
2642 struct Failing;
2643 #[async_trait]
2644 impl ModelProvider for Failing {
2645 async fn complete(
2646 &self,
2647 _req: rhema_core::ModelRequest,
2648 _sink: &mut dyn EventSink,
2649 ) -> Result<ModelOutput, ProviderError> {
2650 Err(ProviderError::Timeout)
2651 }
2652 }
2653
2654 let recording = Arc::new(Recording(StdMutex::new(Vec::new())));
2655 let transcript = Arc::new(Mutex::new(Transcript::new(settings(20_000))));
2656 let view = TranscriptView::with_summarizer(
2657 recording.clone(),
2658 transcript.clone(),
2659 Arc::new(compact::ModelSummarizer::new(Arc::new(Failing), "cheap")),
2660 );
2661 let req = rhema_core::ModelRequest {
2662 system: None,
2663 messages: long_history(30),
2664 tools: Vec::new(),
2665 params: rhema_core::ChatParams::new("m"),
2666 };
2667 let mut sink = NoopSink;
2668 view.complete(req, &mut sink).await.unwrap();
2672 {
2673 let sent = recording.0.lock().unwrap();
2676 assert_eq!(sent.len(), 1);
2677 }
2678 wait_for(|| transcript.lock().unwrap().stats().summarizer_calls > 0).await;
2679 let mirror = transcript.lock().unwrap();
2680 assert_eq!(
2681 mirror.stats().summarizer_failures,
2682 mirror.stats().summarizer_calls
2683 );
2684 assert!(
2685 mirror
2686 .sections
2687 .iter()
2688 .all(|s| s.origin == SectionOrigin::Extractive)
2689 );
2690 }
2691
2692 struct Gated(Arc<AtomicBool>);
2696
2697 #[async_trait]
2698 impl ModelProvider for Gated {
2699 async fn complete(
2700 &self,
2701 _req: rhema_core::ModelRequest,
2702 _sink: &mut dyn EventSink,
2703 ) -> Result<ModelOutput, ProviderError> {
2704 while !self.0.load(Ordering::SeqCst) {
2705 tokio::task::yield_now().await;
2706 }
2707 Ok(ModelOutput {
2708 message: Message::text(Role::Assistant, "## Goals Met\n- late but dense"),
2709 stop_reason: rhema_core::StopReason::EndTurn,
2710 usage: Usage::default(),
2711 })
2712 }
2713 }
2714
2715 #[tokio::test]
2716 async fn a_slow_summarizer_never_delays_the_request() {
2717 let gate = Arc::new(AtomicBool::new(false));
2718 let recording = Arc::new(Recording(StdMutex::new(Vec::new())));
2719 let transcript = Arc::new(Mutex::new(Transcript::new(settings(20_000))));
2720 let view = TranscriptView::with_summarizer(
2721 recording.clone(),
2722 transcript.clone(),
2723 Arc::new(compact::ModelSummarizer::new(
2724 Arc::new(Gated(Arc::clone(&gate))),
2725 "cheap",
2726 )),
2727 );
2728 let req = rhema_core::ModelRequest {
2729 system: None,
2730 messages: long_history(30),
2731 tools: Vec::new(),
2732 params: rhema_core::ChatParams::new("m"),
2733 };
2734 let turn = tokio::spawn(async move {
2735 let mut sink = NoopSink;
2736 view.complete(req, &mut sink).await.unwrap();
2737 });
2738
2739 wait_for(|| !recording.0.lock().unwrap().is_empty()).await;
2742 wait_for(|| turn.is_finished()).await;
2743 assert!(
2744 !gate.load(Ordering::SeqCst),
2745 "the request waited on the gated worker"
2746 );
2747
2748 gate.store(true, Ordering::SeqCst);
2750 wait_for(|| {
2751 transcript
2752 .lock()
2753 .unwrap()
2754 .sections
2755 .iter()
2756 .all(|s| s.origin == SectionOrigin::Model)
2757 })
2758 .await;
2759 let mirror = transcript.lock().unwrap();
2760 assert!(
2761 mirror
2762 .sections
2763 .iter()
2764 .all(|s| s.text.contains("late but dense")),
2765 "{:?}",
2766 mirror.sections
2767 );
2768 }
2769
2770 struct NoopSink;
2771
2772 impl EventSink for NoopSink {
2773 fn emit(&mut self, _event: rhema_core::Event<'_>) {}
2774 }
2775}