Skip to main content

rhema_transcript/
view.rs

1//! The request view: the provider decorator that rewrites
2//! `req.messages` under a byte budget, and the mirror `zoom` reads.
3//!
4//! The decorator sits outside everything else on the request path, as
5//! paste expansion does: the engine clones the session into the request
6//! untouched, the decorator projects it, the session keeps every
7//! message (SPEC.md ยง6). Requests carry the full history, so the
8//! decorator's mirror is exactly the log as of the last request, a
9//! resumed session rebuilds it wholesale on the first call.
10//!
11//! Past the budget the aged prefix is covered by the stepped
12//! compaction block ([`crate::compact`]): sections tiling `[0, cut)`,
13//! appended only at flushes so the request prefix stays cache-stable
14//! between them. This module owns the cut and the sections; the
15//! summarizer seam and the section writers live in
16//! [`crate::compact`].
17
18use 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
31/// How many section fills the background worker runs at once. A flush
32/// can chunk a whole allowance into a dozen sections; the cap keeps
33/// one worker provider from seeing a stampede.
34const WORKER_CONCURRENCY: usize = 4;
35
36/// The view's settings.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub struct TranscriptSettings {
39    /// The byte budget a request's messages aim for. The transcript
40    /// engages only past it, below, requests pass through
41    /// byte-identical, and the current turn may exceed it: the tail is
42    /// never cut.
43    pub max_view_bytes: usize,
44    /// The bytes one section's messages aim for: the summarizer
45    /// worker's input bound, and the granularity compaction works at.
46    /// A section carries at least one message whatever this says.
47    pub step_bytes: usize,
48    /// The messages one section covers at most. Bounds the extractive
49    /// stand-in's lossiness: a digest keeps the user's words whole and
50    /// counts the rest, so this caps how much tool traffic one line
51    /// may paper over when no model fill is configured.
52    pub max_section_messages: usize,
53    /// The bytes the committed block may reach before the oldest
54    /// sections consolidate into one. Consolidation rewrites the
55    /// block, a full cache break, so it fires only past this cap,
56    /// and merges down to half of it before stopping.
57    pub max_block_bytes: usize,
58}
59
60impl Default for TranscriptSettings {
61    fn default() -> Self {
62        Self {
63            // Tool-heavy sessions (build logs, file dumps in results)
64            // run oversized tails constantly; 256 KB keeps the
65            // allowance, and with it the stretch between flushes,
66            // worth the name at that workload.
67            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/// The session's token usage, split by what it bought. The five input
76/// categories share each request's reported input tokens in proportion
77/// to their wire bytes (tool *definitions* ride with the calls that
78/// use them); the model's generated output tokens all land on
79/// `model_output_tokens`, which also carries the assistant text the
80/// history re-sends. The compaction block travels as a user message
81/// and counts there.
82#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
83pub struct UsageBreakdown {
84    /// The system prompt minus its skills section.
85    pub system_prompt_tokens: u64,
86    /// The skills section of the system prompt, when the agent could
87    /// isolate it at render time; zero otherwise.
88    pub skills_tokens: u64,
89    /// Tool definitions plus the tool-call arguments re-sent in
90    /// assistant messages.
91    pub tool_calls_input_tokens: u64,
92    /// Tool results, the tools' output, re-sent as input.
93    pub tool_calls_output_tokens: u64,
94    /// User text, the compaction block included.
95    pub user_messages_tokens: u64,
96    /// The model's words: assistant text in the history plus every
97    /// generated output token.
98    pub model_output_tokens: u64,
99}
100
101impl UsageBreakdown {
102    /// The six categories, labeled as the Usage page spells them.
103    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    /// The grand total the percentages read against.
115    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/// The log's own content by category, in estimated tokens, each
126/// message counted once, the content the billed split re-sends once
127/// per request. Tool content has its own buckets, text and images go
128/// to the message's role, and a system message counts nowhere: the
129/// system prompt, the skills section, and the tool definitions ride
130/// every request but live in no message, so they have no figure here.
131#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
132pub struct LogContent {
133    /// Tool-call arguments in assistant messages.
134    pub tool_calls: u64,
135    /// Tool results in tool messages.
136    pub tool_results: u64,
137    /// User text, the compaction block included.
138    pub user_text: u64,
139    /// Assistant text.
140    pub assistant_text: u64,
141}
142
143impl LogContent {
144    /// The four categories summed: the log's estimated tokens, each
145    /// message counted once.
146    pub fn total(&self) -> u64 {
147        self.tool_calls + self.tool_results + self.user_text + self.assistant_text
148    }
149}
150
151/// The compaction's benchmark snapshot: what the view has been doing,
152/// and what the providers' own usage says about the prefix cache. All
153/// counters run from the transcript's construction; a resumed session
154/// keeps its run continuous by folding the saved counters in with
155/// [`TranscriptStats::carry`]. The struct is the saved shape: the
156/// frontend serializes it into the session file verbatim.
157#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
158pub struct TranscriptStats {
159    /// Requests the decorator forwarded.
160    pub requests: u64,
161    /// Requests below the budget, sent byte-identical: the whole
162    /// prefix a cache holds.
163    pub pass_through: u64,
164    /// Requests carrying the compaction block plus the whole band.
165    pub viewed: u64,
166    /// Flushes: cut movements, the only moments the view's prefix
167    /// breaks.
168    pub flushes: u64,
169    /// Consolidations: block rewrites past the block cap, each one a
170    /// full cache break.
171    pub consolidations: u64,
172    /// Summarizer calls issued, successes and failures together.
173    pub summarizer_calls: u64,
174    /// Summarizer calls that failed; each left the extractive
175    /// stand-in in place.
176    pub summarizer_failures: u64,
177    /// The mirror's message count at the last request.
178    pub log_messages: usize,
179    /// Messages under the block at the last request: the cut.
180    pub sectioned_messages: usize,
181    /// The block's section count at the last request.
182    pub sections: usize,
183    /// The block's bytes at the last request: the budget's unit.
184    pub block_bytes: usize,
185    /// The block's estimated tokens at the last request.
186    #[serde(default)]
187    pub block_tokens: u64,
188    /// The bytes carried whole from the cut to the log's end, at the
189    /// last request.
190    pub band_bytes: usize,
191    /// The estimated tokens carried whole from the cut to the log's
192    /// end, at the last request.
193    #[serde(default)]
194    pub band_tokens: u64,
195    /// The current turn's bytes at the last request.
196    pub tail_bytes: usize,
197    /// The current turn's estimated tokens at the last request.
198    #[serde(default)]
199    pub tail_tokens: u64,
200    /// The log's wire bytes at the last request, what the
201    /// conversation actually holds, each message counted once. The
202    /// usage split below sums the same content once per request;
203    /// this is the once.
204    #[serde(default)]
205    pub log_bytes: usize,
206    /// The log's estimated tokens by category at the last request,
207    /// counted once.
208    #[serde(default)]
209    pub log_content: LogContent,
210    /// Input tokens the providers reported, summed over requests,
211    /// cached tokens included.
212    pub input_tokens: u64,
213    /// Of those, the tokens the provider served from its prompt cache.
214    pub cached_input_tokens: u64,
215    /// Output tokens the providers reported, summed over requests.
216    pub output_tokens: u64,
217    /// The session's usage split by category.
218    pub usage: UsageBreakdown,
219}
220
221impl TranscriptStats {
222    /// The session's prompt-cache hit rate: cached input over all
223    /// input. `None` before any usage was reported. The providers'
224    /// own numbers, the ground truth the stepped design optimizes.
225    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    /// Folds a saved session's counters in, so a resumed session's
234    /// stats read as one run with the pre-resume requests included:
235    /// the run counters and the usage split sum, the cache rate keeps
236    /// covering everything. The at-last-request snapshots describe
237    /// the mirror that measured them, so they stay this side's,
238    /// except while this mirror has not looked at a log yet
239    /// (`log_messages == 0`), where the snapshot is what a Usage page
240    /// opened before the first request would otherwise render as
241    /// zeros, and the saved one is the honest figure.
242    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/// How one summarizer call ended, as [`Transcript::record_worker_call`]
278/// counts it.
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280pub enum WorkerOutcome {
281    /// The worker answered; the section's stand-in was upgraded.
282    Upgraded,
283    /// The worker failed; the extractive stand-in stays in place.
284    Failed,
285}
286
287/// The mirror: the log as the last request carried it, the stepped
288/// compaction state over it, and the benchmark counters. Shared
289/// between the decorator (which refreshes it) and the zoom tool (which
290/// reads the log).
291#[derive(Debug)]
292pub struct Transcript {
293    settings: TranscriptSettings,
294    log: Vec<Message>,
295    /// Per-message wire bytes, parallel to `log`: the budget's unit,
296    /// counted once per message instead of per request.
297    sizes: Vec<usize>,
298    /// Per-message estimated tokens, parallel to `log`: the Usage
299    /// page's unit, maintained beside `sizes`.
300    tokens: Vec<u64>,
301    /// [`Vec`]`sizes` summed once, maintained by `observe` and read by
302    /// the planner and the counters. The whole-log walk this replaces
303    /// re-serialized every tool call's arguments on every request.
304    total_bytes: usize,
305    /// [`Vec`]`tokens` summed once, maintained beside `total_bytes`.
306    total_tokens: u64,
307    /// The log's estimated tokens by category, maintained by `observe`
308    /// the same way; `render` snapshots it into `stats.log_content`.
309    content: LogContent,
310    /// First message not under the block: `[0, cut)` is sectioned,
311    /// `[cut, len)` travels whole. Moves only at flushes.
312    cut: usize,
313    /// The committed block: sections tiling `[0, cut)`, oldest first,
314    /// append-only between flushes.
315    sections: Vec<Section>,
316    /// The skills section's byte share of the system prompt, measured
317    /// at render time by the agent that assembled it. Zero until set.
318    skills_bytes: usize,
319    /// The skills whose bodies pin whole into the block. Empty, and
320    /// nothing pins.
321    skills: Vec<SkillText>,
322    /// The shortest pinned body: the detect gate, below which no
323    /// result can carry a body at all. `usize::MAX` with no skills.
324    min_skill_body: usize,
325    /// The skill reads found in the log, ordered by `call`.
326    reads: Vec<Read>,
327    /// The skill names a committed section carries whole, with that
328    /// section's range: the dedupe that turns re-reads into pointers.
329    /// Rebuilt from the sections on every observe, so resume adoption
330    /// keeps it true.
331    pinned: HashMap<String, Range>,
332    /// The wire bytes the pending response's input tokens spread over:
333    /// staged from the request before it goes out, consumed by
334    /// [`Transcript::record_usage`].
335    pending_shares: Shares,
336    stats: TranscriptStats,
337    /// A previous session's sections, handed over by the session save
338    /// and waiting for the resumed log. `observe` adopts them on the
339    /// resume's replace when they tile a prefix of the rebuilt log,
340    /// and drops them for anything else.
341    saved: Option<Vec<Section>>,
342}
343
344/// A skill whose body pins: a tool result carrying one stays whole in
345/// the block instead of compacting to a digest. Set on the mirror at
346/// wiring time, from the same discovery the prompt renders.
347#[derive(Debug, Clone, PartialEq, Eq)]
348pub struct SkillText {
349    /// The skill's folder name.
350    pub name: String,
351    /// The whole `SKILL.md`, frontmatter included.
352    pub body: String,
353}
354
355/// One skill read found in the log: the call-and-result span and the
356/// skill the result carried.
357#[derive(Debug, Clone, Copy)]
358struct Read {
359    /// The log index of the assistant message holding the call.
360    call: usize,
361    /// The log index of the tool message carrying the body.
362    result: usize,
363    /// The skill's index in the mirror's skill list.
364    skill: usize,
365}
366
367/// The bytes of a detect needle: a body's head, distinct per skill,
368/// compared before the whole body is.
369const NEEDLE_BYTES: usize = 64;
370
371/// The body's head on a char boundary: the cheap prefilter a result
372/// must contain before the whole body is compared.
373fn needle(body: &str) -> &str {
374    let mut end = NEEDLE_BYTES.min(body.len());
375    while !body.is_char_boundary(end) {
376        end -= 1;
377    }
378    &body[..end]
379}
380
381/// One request's wire bytes by category, the proportions the
382/// reported input tokens are spread over.
383#[derive(Debug, Clone, Copy, Default)]
384struct Shares {
385    system_prompt: usize,
386    skills: usize,
387    tool_defs: usize,
388    tool_calls: usize,
389    tool_results: usize,
390    user_text: usize,
391    assistant_text: usize,
392}
393
394/// Adds one message's estimated tokens by category into `content`, the
395/// per-message form of the split the counters and the usage shares
396/// both read. The same taxonomy the request shares spread the billed
397/// input over, minus the pieces that ride no message.
398fn add_message_content(content: &mut LogContent, message: &Message) {
399    for part in &message.content {
400        match part {
401            Content::Text(text) => match message.role {
402                Role::User => content.user_text += summary::text_tokens(text.len()),
403                Role::Assistant => content.assistant_text += summary::text_tokens(text.len()),
404                Role::System | Role::Tool => {}
405            },
406            Content::ToolCall(call) => {
407                content.tool_calls +=
408                    summary::text_tokens(call.name.len() + call.args.to_string().len());
409            }
410            Content::ToolResult(result) => {
411                content.tool_results += summary::text_tokens(result.content.len());
412                // An image is a vision price, not text: the split
413                // prices it as one, and the categories still tile the
414                // log's tokens whatever the log holds.
415                content.tool_results += result.images.len() as u64 * summary::IMAGE_TOKENS;
416            }
417            // A bare image rides the message's own turn: its vision
418            // price joins that role's bucket, so the split still
419            // covers every token a user or assistant message carries.
420            Content::Image(_) => match message.role {
421                Role::User => content.user_text += summary::IMAGE_TOKENS,
422                Role::Assistant => content.assistant_text += summary::IMAGE_TOKENS,
423                Role::System | Role::Tool => {}
424            },
425        }
426    }
427}
428
429impl Shares {
430    fn total(&self) -> usize {
431        self.system_prompt
432            + self.skills
433            + self.tool_defs
434            + self.tool_calls
435            + self.tool_results
436            + self.user_text
437            + self.assistant_text
438    }
439}
440
441impl Transcript {
442    /// A mirror with no history yet; the first request fills it.
443    pub fn new(settings: TranscriptSettings) -> Self {
444        Self {
445            settings,
446            log: Vec::new(),
447            sizes: Vec::new(),
448            tokens: Vec::new(),
449            total_bytes: 0,
450            total_tokens: 0,
451            content: LogContent::default(),
452            cut: 0,
453            sections: Vec::new(),
454            skills_bytes: 0,
455            skills: Vec::new(),
456            min_skill_body: usize::MAX,
457            reads: Vec::new(),
458            pinned: HashMap::new(),
459            pending_shares: Shares::default(),
460            stats: TranscriptStats::default(),
461            saved: None,
462        }
463    }
464
465    /// Folds a request's messages into the log: an extension of what is
466    /// already here extends it; anything else, a fresh session, a
467    /// resume, replaces it, and the compaction state rebuilds from
468    /// nothing (the first request re-derives it; nothing derived is
469    /// ever persisted).
470    pub fn observe(&mut self, messages: &[Message]) {
471        if messages.len() >= self.log.len() && messages[..self.log.len()] == self.log[..] {
472            let first = self.log.len();
473            for message in &messages[first..] {
474                let bytes = summary::message_bytes(message);
475                let tokens = summary::message_tokens(message);
476                self.sizes.push(bytes);
477                self.tokens.push(tokens);
478                self.total_bytes += bytes;
479                self.total_tokens += tokens;
480                add_message_content(&mut self.content, message);
481            }
482            self.log.extend_from_slice(&messages[first..]);
483            self.scan_reads(first);
484        } else {
485            self.log = messages.to_vec();
486            self.sizes = Vec::with_capacity(self.log.len());
487            self.tokens = Vec::with_capacity(self.log.len());
488            self.total_bytes = 0;
489            self.total_tokens = 0;
490            self.content = LogContent::default();
491            for index in 0..self.log.len() {
492                let bytes = summary::message_bytes(&self.log[index]);
493                let tokens = summary::message_tokens(&self.log[index]);
494                self.sizes.push(bytes);
495                self.tokens.push(tokens);
496                self.total_bytes += bytes;
497                self.total_tokens += tokens;
498                add_message_content(&mut self.content, &self.log[index]);
499            }
500            self.cut = 0;
501            self.sections.clear();
502            self.reads.clear();
503            self.scan_reads(0);
504        }
505        // The saved sections are adopted only when they tile a prefix
506        // of the log this mirror now holds: the resume then rides the
507        // compaction the previous session already paid for, dense
508        // from the first request. Anything else, a truncated log, an
509        // edited session, falls back to the rebuild. A fresh
510        // mirror's first observe lands here too: its log was empty,
511        // so the compare above took the extension branch.
512        if let Some(saved) = self.saved.take() {
513            let mut end = 0usize;
514            // The sections ride the session file: the arithmetic is
515            // checked, and a wrap, like a gap or a bad length, just
516            // fails the tiling and falls back to the rebuild.
517            let tiles = !saved.is_empty()
518                && saved.iter().all(|section| {
519                    match section.range.id.checked_add(section.range.n) {
520                        Some(next) if section.range.id == end => {
521                            end = next;
522                            end <= self.log.len()
523                        }
524                        _ => false,
525                    }
526                })
527                && end <= self.log.len();
528            if tiles {
529                self.sections = saved;
530                self.cut = end;
531            }
532        }
533        // The pin map reads the committed state, which sections carry
534        // bodies whole decides verbatim versus pointer at the next
535        // flush, so it rebuilds whenever the sections can have
536        // changed, which includes resume adoption swapping all of
537        // them.
538        self.pinned = self
539            .sections
540            .iter()
541            .flat_map(|section| {
542                section
543                    .pinned
544                    .iter()
545                    .map(|name| (name.clone(), section.range))
546            })
547            .collect();
548    }
549
550    /// How many messages the log holds.
551    pub fn len(&self) -> usize {
552        self.log.len()
553    }
554
555    /// Whether the log is empty.
556    pub fn is_empty(&self) -> bool {
557        self.log.is_empty()
558    }
559
560    /// Message `id`, as `zoom(id, 1)` reads it.
561    pub fn message(&self, id: usize) -> Option<&Message> {
562        self.log.get(id)
563    }
564
565    /// The messages of `range`, as `zoom` reads them; `None` past the
566    /// log's end. The range arrives from the model's tool call, so
567    /// the arithmetic is checked: a huge `n` is a malformed call
568    /// answered with nothing, not a panic.
569    pub fn range(&self, range: Range) -> Option<&[Message]> {
570        let end = range.id.checked_add(range.n)?;
571        self.log.get(range.id..end)
572    }
573
574    /// The compaction's benchmark snapshot.
575    pub fn stats(&self) -> TranscriptStats {
576        self.stats
577    }
578
579    /// Folds a saved session's benchmark counters in: a resumed
580    /// session's stats keep reading as one run. See
581    /// [`TranscriptStats::carry`] for what sums and what does not.
582    pub fn carry(&mut self, saved: &TranscriptStats) {
583        self.stats.carry(saved);
584    }
585
586    /// The committed sections, oldest first: what a session save
587    /// carries so the next session skips the re-fill.
588    pub fn saved_sections(&self) -> Vec<Section> {
589        self.sections.clone()
590    }
591
592    /// Hands a previous session's sections over. They are not adopted
593    /// on the spot: the resumed log is unknown until the first
594    /// request, and [`Transcript::observe`] validates them against it.
595    pub fn adopt_sections(&mut self, sections: Vec<Section>) {
596        self.saved = Some(sections);
597    }
598
599    /// Zeroes the benchmark counters; the log and the compaction state
600    /// stay, the next request rebuilds both anyway. A conversation
601    /// cleared mid-agent starts its accounting over.
602    pub fn reset_stats(&mut self) {
603        self.stats = TranscriptStats::default();
604    }
605
606    /// Sets the skills section's byte share of the system prompt,
607    /// measured by the agent that rendered it, since the section's
608    /// shape is the template's to decide. Zero (the default) folds the
609    /// whole system prompt into `system_prompt_tokens`.
610    pub fn set_skills_bytes(&mut self, bytes: usize) {
611        self.skills_bytes = bytes;
612    }
613
614    /// Sets the skills whose bodies pin whole into the block. A tool
615    /// result carrying one becomes its own verbatim section at flush
616    /// time instead of a digest; a re-read becomes a pointer to the
617    /// section already carrying the body. Safe to call at any point,
618    /// setting re-detects over the whole log, and normally called
619    /// once at wiring, from the same discovery the prompt rendered.
620    pub fn set_skills(&mut self, skills: Vec<SkillText>) {
621        self.skills = skills;
622        self.min_skill_body = self
623            .skills
624            .iter()
625            .map(|skill| skill.body.len())
626            .min()
627            .unwrap_or(usize::MAX);
628        self.reads.clear();
629        self.scan_reads(0);
630    }
631
632    /// The skill a tool result carries, if any: the length gate first
633    /// (a shorter result cannot contain a body), then the head needle,
634    /// then the whole body. Matching by content rather than by the
635    /// command means any read that returned the whole file qualifies,
636    /// `cat`, `sed`, a subagent's result, and no shell line is
637    /// parsed.
638    fn carried_skill(&self, result: &ToolResult) -> Option<usize> {
639        if result.content.len() < self.min_skill_body {
640            return None;
641        }
642        self.skills.iter().position(|skill| {
643            result.content.len() >= skill.body.len()
644                && result.content.contains(needle(&skill.body))
645                && result.content.contains(&skill.body)
646        })
647    }
648
649    /// Detects skill reads in the log from `from` on, appending to
650    /// [`Transcript::reads`] in order. A read needs the pair intact:
651    /// the result, and directly before it an assistant message
652    /// carrying exactly that one call. A multi-call turn digests
653    /// normally rather than splitting a section around one of its
654    /// results.
655    fn scan_reads(&mut self, from: usize) {
656        for index in from..self.log.len() {
657            if self.log[index].role != Role::Tool {
658                continue;
659            }
660            for part in &self.log[index].content {
661                let Content::ToolResult(result) = part else {
662                    continue;
663                };
664                let Some(skill) = self.carried_skill(result) else {
665                    continue;
666                };
667                // The call directly before: exactly one ToolCall in
668                // the turn (a second call's result would orphan behind
669                // the pin), and it must be this result's id. Leading
670                // text blocks are fine, a real turn narrates.
671                let calls = || {
672                    self.log[index - 1]
673                        .content
674                        .iter()
675                        .filter_map(|part| match part {
676                            Content::ToolCall(call) => Some(call),
677                            _ => None,
678                        })
679                };
680                let paired = index > 0
681                    && self.log[index - 1].role == Role::Assistant
682                    && match (calls().next(), calls().nth(1)) {
683                        (Some(call), None) => call.id == result.id,
684                        _ => false,
685                    };
686                if paired {
687                    self.reads.push(Read {
688                        call: index - 1,
689                        result: index,
690                        skill,
691                    });
692                    break;
693                }
694            }
695        }
696    }
697
698    /// The read whose call sits at `index`, if any.
699    fn read_starting(&self, index: usize) -> Option<Read> {
700        let at = self.reads.partition_point(|read| read.call < index);
701        self.reads
702            .get(at)
703            .copied()
704            .filter(|read| read.call == index)
705    }
706
707    /// Stages the byte shares of the request about to go out: what the
708    /// next [`Transcript::record_usage`] spreads the reported input
709    /// tokens over. The decorator calls it after the view is applied,
710    /// so the shares read what is actually sent.
711    pub fn stage_usage_shares(
712        &mut self,
713        system: Option<&str>,
714        tools: &[ToolSpec],
715        messages: &[Message],
716    ) {
717        let mut shares = Shares::default();
718        if let Some(system) = system {
719            let skills = self.skills_bytes.min(system.len());
720            shares.skills = skills;
721            shares.system_prompt = system.len() - skills;
722        }
723        // The tool definitions ride the request's tools array; they
724        // are input every step, and they share the calls' row.
725        for spec in tools {
726            shares.tool_defs +=
727                spec.name.len() + spec.description.len() + spec.parameters.to_string().len();
728        }
729        for message in messages {
730            for content in &message.content {
731                match content {
732                    Content::Text(text) => match message.role {
733                        Role::User => shares.user_text += text.len(),
734                        Role::Assistant => shares.assistant_text += text.len(),
735                        Role::System | Role::Tool => {}
736                    },
737                    Content::ToolCall(call) => {
738                        shares.tool_calls += call.name.len() + call.args.to_string().len();
739                    }
740                    Content::ToolResult(result) => {
741                        shares.tool_results += result.content.len();
742                        // An image is one message's worth of context,
743                        // here and in the view's budget alike.
744                        shares.tool_results += result.images.len() * summary::IMAGE_BYTES;
745                    }
746                    // Shares spreads tokens over the categories it names,
747                    // and none of them is a bare image.
748                    Content::Image(_) => {}
749                }
750            }
751        }
752        self.pending_shares = shares;
753    }
754
755    /// Records one provider response's usage: the ground truth the
756    /// cache-hit rate reports from. The decorator calls this once per
757    /// forwarded request; the reported input tokens spread over the
758    /// staged shares by byte proportion.
759    pub fn record_usage(&mut self, usage: &Usage) {
760        self.stats.input_tokens += u64::from(usage.input_tokens);
761        self.stats.cached_input_tokens += u64::from(usage.cached_input_tokens);
762        self.stats.output_tokens += u64::from(usage.output_tokens);
763        let shares = std::mem::take(&mut self.pending_shares);
764        let total = shares.total();
765        let input = u64::from(usage.input_tokens);
766        if total > 0 && input > 0 {
767            let spread = |bytes: usize| input * bytes as u64 / total as u64;
768            let breakdown = &mut self.stats.usage;
769            breakdown.system_prompt_tokens += spread(shares.system_prompt);
770            breakdown.skills_tokens += spread(shares.skills);
771            breakdown.tool_calls_input_tokens += spread(shares.tool_defs + shares.tool_calls);
772            breakdown.tool_calls_output_tokens += spread(shares.tool_results);
773            breakdown.user_messages_tokens += spread(shares.user_text);
774            breakdown.model_output_tokens += spread(shares.assistant_text);
775        }
776        self.stats.usage.model_output_tokens += u64::from(usage.output_tokens);
777    }
778
779    /// Records one summarizer call the decorator issued outside the
780    /// mirror's lock; a [`WorkerOutcome::Failed`] counts it against the
781    /// worker.
782    pub fn record_worker_call(&mut self, outcome: WorkerOutcome) {
783        self.stats.summarizer_calls += 1;
784        if outcome == WorkerOutcome::Failed {
785            self.stats.summarizer_failures += 1;
786        }
787    }
788
789    /// Commits an upgraded section text from a [`PendingSummary`] a
790    /// worker task filled outside the request. `false` when the section no
791    /// longer matches, a concurrent plan rebuilt it, and the text is
792    /// dropped: every intermediate state stays a valid view.
793    pub fn commit_summary(&mut self, pending: &PendingSummary, text: String) -> bool {
794        let Some(section) = self.sections.get(pending.section) else {
795            return false;
796        };
797        if section.range != pending.range {
798            return false;
799        }
800        let section = &mut self.sections[pending.section];
801        let mut text = compact::cap_summary(text);
802        // Pinned bodies ride after the fill: the worker condenses the
803        // range's events, the skill text stays whole beneath it.
804        for name in &section.pinned {
805            if let Some(skill) = self.skills.iter().find(|skill| &skill.name == name) {
806                text.push_str("\n\n");
807                text.push_str(&compact::skill_section_text(name, &skill.body));
808            }
809        }
810        section.text = text;
811        section.origin = SectionOrigin::Model;
812        true
813    }
814
815    /// The flush planner: decides whether the budget is breached, and
816    /// if so moves the cut and commits the new sections, extractive
817    /// stand-ins first, returning the summaries a [`Summarizer`]
818    /// should upgrade. Between flushes this touches nothing: the block
819    /// is append-only by construction.
820    ///
821    /// Called under the mirror's lock with `observe` already applied;
822    /// never blocks and never calls a model.
823    pub fn plan_flush(&mut self) -> Vec<PendingSummary> {
824        self.sync_sizes();
825        let len = self.log.len();
826        if self.total_bytes <= self.settings.max_view_bytes {
827            return Vec::new();
828        }
829        let tail_start = self.tail_index();
830        let tail_bytes = self.bytes(tail_start, len);
831        let allowance = self.settings.max_view_bytes.saturating_sub(tail_bytes);
832
833        // The minimum band: walk back from the tail over whole
834        // messages while they fit. The walk stops at the cut, the
835        // block never un-commits.
836        let mut c_min = tail_start;
837        let mut budget = allowance;
838        while c_min > self.cut {
839            let cost = self.sizes[c_min - 1];
840            if cost > budget {
841                break;
842            }
843            budget -= cost;
844            c_min -= 1;
845        }
846        let mut pending = Vec::new();
847        if c_min > self.cut {
848            // Breach. Overshoot to half the allowance: the band after
849            // the flush leaves a whole hysteresis of growth before the
850            // next one, so flushes, the only prefix breaks, stay
851            // far apart.
852            let half = allowance / 2;
853            let mut c_new = c_min;
854            let mut band = self.bytes(c_new, tail_start);
855            // The smallest position whose remaining band fits half:
856            // walk forward while the band still exceeds it. The break
857            // on `next > half` was the inverse and left the band at
858            // the full allowance, flushes every request.
859            while c_new < tail_start && band > half {
860                band -= self.sizes[c_new];
861                c_new += 1;
862            }
863            // The band must not open on a tool result: its call would
864            // stay behind in the last section. Trailing results come
865            // along into the block.
866            while c_new < tail_start && self.log[c_new].role == Role::Tool {
867                c_new += 1;
868            }
869            if c_new > self.cut {
870                pending = self.extend_sections(self.cut, c_new);
871                self.cut = c_new;
872                self.stats.flushes += 1;
873                pending.extend(self.consolidate());
874            }
875        }
876        pending
877    }
878
879    /// The view of the log: `None` passes it through unchanged, below
880    /// the budget, or nothing sectioned yet. Past it, the block
881    /// followed by the whole band from the cut.
882    ///
883    /// The one-stop form for callers without a summarizer:
884    /// [`Transcript::plan_flush`] plus this, with the extractive
885    /// stand-ins final. The decorator plans and renders under the
886    /// lock and hands the fill a background task.
887    pub fn view(&mut self, messages: &[Message]) -> Option<Vec<Message>> {
888        self.observe(messages);
889        self.plan_flush();
890        self.render()
891    }
892
893    /// Builds the request view from the committed state. Called once
894    /// per request, after any summarizer commits; updates the
895    /// benchmark counters.
896    pub fn render(&mut self) -> Option<Vec<Message>> {
897        self.stats.requests += 1;
898        self.stats.log_bytes = self.total_bytes;
899        self.stats.log_content = self.content;
900        if self.cut == 0 {
901            self.stats.pass_through += 1;
902            return None;
903        }
904        let len = self.log.len();
905        let tail_start = self.tail_index();
906        self.stats.log_messages = len;
907        self.stats.sectioned_messages = self.cut;
908        self.stats.sections = self.sections.len();
909        self.stats.block_bytes = self.block_bytes();
910        self.stats.block_tokens = summary::text_tokens(self.stats.block_bytes);
911        self.stats.band_bytes = self.bytes(self.cut, len);
912        self.stats.band_tokens = self.tokens_between(self.cut, len);
913        self.stats.tail_bytes = self.bytes(tail_start, len);
914        self.stats.tail_tokens = self.tokens_between(tail_start, len);
915        self.stats.viewed += 1;
916
917        let mut text = String::from(
918            "<transcript>\n\
919             The blocks below cover this conversation's older messages,\n\
920             oldest first. Each block is headed `id+n|`: the n messages\n\
921             from index id on, condensed. zoom(id, n) returns those n\n\
922             messages whole; long output is cut and the note names the\n\
923             `at` to resume at. The messages after the blocks are\n\
924             recent; they are whole.\n\n",
925        );
926        for section in &self.sections {
927            text.push_str(&format!(
928                "{}+{}|\n{}\n\n",
929                section.range.id, section.range.n, section.text
930            ));
931        }
932        text.push_str("</transcript>");
933        let mut out = Vec::with_capacity(len - self.cut + 1);
934        out.push(Message::text(Role::User, text));
935        out.extend(self.log[self.cut..].iter().cloned());
936        Some(out)
937    }
938
939    /// The last user message's index, clamped to the cut: the tail is
940    /// never under the block. No user message at all, an
941    /// assistant-only history, and everything from the cut on is the
942    /// tail.
943    fn tail_index(&self) -> usize {
944        let user = self
945            .log
946            .iter()
947            .rposition(|message| message.role == Role::User)
948            .unwrap_or(self.log.len());
949        user.max(self.cut)
950    }
951
952    /// The wire bytes of `log[from..to]`, from the size cache.
953    fn bytes(&self, from: usize, to: usize) -> usize {
954        self.sizes[from..to].iter().sum()
955    }
956
957    /// The estimated tokens of `log[from..to]`, from the token cache.
958    fn tokens_between(&self, from: usize, to: usize) -> u64 {
959        self.tokens[from..to].iter().sum()
960    }
961
962    /// The block's bytes: every section's header plus text.
963    fn block_bytes(&self) -> usize {
964        self.sections.iter().map(Section::view_bytes).sum()
965    }
966
967    /// Realigns the size cache with the log; `observe` maintains it,
968    /// so this is a defensive no-op in normal flow. When it does patch,
969    /// the running totals rebuild from scratch.
970    fn sync_sizes(&mut self) {
971        self.sizes.truncate(self.log.len());
972        self.tokens.truncate(self.log.len());
973        let mut patched = false;
974        while self.sizes.len() < self.log.len() {
975            let id = self.sizes.len();
976            self.sizes.push(summary::message_bytes(&self.log[id]));
977            self.tokens.push(summary::message_tokens(&self.log[id]));
978            patched = true;
979        }
980        if patched {
981            self.total_bytes = self.sizes.iter().sum();
982            self.total_tokens = self.tokens.iter().sum();
983            self.content = LogContent::default();
984            for message in &self.log {
985                add_message_content(&mut self.content, message);
986            }
987        }
988    }
989
990    /// Sections `[start, end)` into the block: chunks at message
991    /// boundaries within the step and message-count bounds, each
992    /// ending so the next never opens on a tool result whose call the
993    /// chunk holds. Returns one pending summary per chunk.
994    fn extend_sections(&mut self, start: usize, end: usize) -> Vec<PendingSummary> {
995        let mut pending = Vec::new();
996        let mut at = start;
997        while at < end {
998            // A skill read pins its call-and-result span as one
999            // section: the first read commits the body whole, a
1000            // re-read a pointer to the section already carrying it.
1001            // No pending goes out for it, so no model fill can rewrite
1002            // the body into a count line.
1003            if let Some(read) = self.read_starting(at) {
1004                let range = Range {
1005                    id: at,
1006                    n: read.result + 1 - at,
1007                };
1008                let name = self.skills[read.skill].name.clone();
1009                let section = match self.pinned.get(&name) {
1010                    Some(carried) => Section {
1011                        range,
1012                        text: compact::skill_pointer_text(&name, *carried),
1013                        origin: SectionOrigin::Extractive,
1014                        pinned: Vec::new(),
1015                    },
1016                    None => {
1017                        self.pinned.insert(name.clone(), range);
1018                        let body = self.skills[read.skill].body.clone();
1019                        Section {
1020                            range,
1021                            text: compact::skill_section_text(&name, &body),
1022                            origin: SectionOrigin::Extractive,
1023                            pinned: vec![name],
1024                        }
1025                    }
1026                };
1027                self.sections.push(section);
1028                at = read.result + 1;
1029                continue;
1030            }
1031            let mut stop = at;
1032            let mut bytes = 0usize;
1033            let mut count = 0usize;
1034            while stop < end {
1035                let cost = self.sizes[stop];
1036                if count > 0
1037                    && (bytes + cost > self.settings.step_bytes
1038                        || count >= self.settings.max_section_messages)
1039                {
1040                    break;
1041                }
1042                // A read call opens its own section: close this chunk
1043                // before it, whatever the budget says.
1044                if count > 0 && self.read_starting(stop).is_some() {
1045                    break;
1046                }
1047                bytes += cost;
1048                count += 1;
1049                stop += 1;
1050            }
1051            while stop < end && self.log[stop].role == Role::Tool {
1052                stop += 1;
1053            }
1054            let range = Range {
1055                id: at,
1056                n: stop - at,
1057            };
1058            let messages = self.log[at..stop].to_vec();
1059            let text = compact::section_digest(&messages);
1060            // The digest of whatever sits directly before this chunk:
1061            // the stand-in committed for the previous chunk, or the
1062            // block's last section for the first chunk of a flush.
1063            let context = self.sections.last().map(|s| s.text.clone());
1064            self.sections.push(Section {
1065                range,
1066                text,
1067                origin: SectionOrigin::Extractive,
1068                pinned: Vec::new(),
1069            });
1070            pending.push(PendingSummary {
1071                section: self.sections.len() - 1,
1072                range,
1073                messages,
1074                context,
1075            });
1076            at = stop;
1077        }
1078        pending
1079    }
1080
1081    /// Consolidates the block past its cap: the two oldest sections
1082    /// merge into one, the union range re-derived from the log, not
1083    /// from the summaries, until the block is at half the cap. Each
1084    /// merge returns a pending summary for the model fill. Rare and
1085    /// stepped: this is the one append-only exception, and it is a
1086    /// full cache break when it fires.
1087    fn consolidate(&mut self) -> Vec<PendingSummary> {
1088        let mut pending = Vec::new();
1089        while self.sections.len() >= 2 && self.block_bytes() > self.settings.max_block_bytes {
1090            let range = Range {
1091                id: self.sections[0].range.id,
1092                n: self.sections[0].range.n + self.sections[1].range.n,
1093            };
1094            let messages = match range
1095                .id
1096                .checked_add(range.n)
1097                .and_then(|end| self.log.get(range.id..end))
1098            {
1099                Some(messages) => messages.to_vec(),
1100                // Sections whose arithmetic does not hold against the
1101                // log (file-derived, adopted past validation): skip
1102                // the merge rather than panic on it.
1103                None => return pending,
1104            };
1105            let mut text = compact::section_digest(&messages);
1106            // The union keeps whatever bodies the merged sections
1107            // carried: the pin outlives the merge, re-appended after
1108            // the digest so the block never loses a skill's text. The
1109            // model fill re-appends them again at commit.
1110            let mut pinned: Vec<String> = Vec::new();
1111            for old in [&self.sections[0], &self.sections[1]] {
1112                for name in &old.pinned {
1113                    if pinned.contains(name) {
1114                        continue;
1115                    }
1116                    if let Some(skill) = self.skills.iter().find(|skill| &skill.name == name) {
1117                        text.push_str("\n\n");
1118                        text.push_str(&compact::skill_section_text(name, &skill.body));
1119                    }
1120                    pinned.push(name.clone());
1121                }
1122            }
1123            self.sections.drain(..2);
1124            self.sections.insert(
1125                0,
1126                Section {
1127                    range,
1128                    text,
1129                    origin: SectionOrigin::Extractive,
1130                    pinned,
1131                },
1132            );
1133            // The union is the block's first section: nothing sits
1134            // before it to resolve references against.
1135            pending.push(PendingSummary {
1136                section: 0,
1137                range,
1138                messages,
1139                context: None,
1140            });
1141            self.stats.consolidations += 1;
1142        }
1143        pending
1144    }
1145}
1146
1147/// The transcript as a [`ModelProvider`]: wraps `inner`, rewrites every
1148/// request's messages through the stepped view, and refreshes the
1149/// shared mirror first. A configured [`Summarizer`] upgrades the new
1150/// sections' stand-ins in a background task after the request went
1151/// out, never inside it, never under the mirror's lock, so a slow or
1152/// failing worker delays nothing.
1153pub struct TranscriptView {
1154    inner: Arc<dyn ModelProvider>,
1155    transcript: Arc<Mutex<Transcript>>,
1156    summarizer: Option<Arc<dyn Summarizer>>,
1157}
1158
1159impl TranscriptView {
1160    /// The wrapper over `inner`, mirroring into `transcript`, the same
1161    /// mirror a [`crate::zoom::Zoom`] resolver reads. Build both from
1162    /// one mirror, or let [`crate::attach`] do it. No summarizer: new
1163    /// sections keep their extractive stand-ins.
1164    pub fn new(inner: Arc<dyn ModelProvider>, transcript: Arc<Mutex<Transcript>>) -> Self {
1165        Self {
1166            inner,
1167            transcript,
1168            summarizer: None,
1169        }
1170    }
1171
1172    /// The wrapper with a summarizer for the model fill of new
1173    /// sections. The fill runs in tokio tasks: calling [`Self::complete`]
1174    /// with a summarizer requires a running runtime.
1175    pub fn with_summarizer(
1176        inner: Arc<dyn ModelProvider>,
1177        transcript: Arc<Mutex<Transcript>>,
1178        summarizer: Arc<dyn Summarizer>,
1179    ) -> Self {
1180        Self {
1181            inner,
1182            transcript,
1183            summarizer: Some(summarizer),
1184        }
1185    }
1186}
1187
1188impl std::fmt::Debug for TranscriptView {
1189    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1190        // The inner provider is a trait object and stays opaque.
1191        f.debug_struct("TranscriptView").finish_non_exhaustive()
1192    }
1193}
1194
1195#[async_trait]
1196impl ModelProvider for TranscriptView {
1197    async fn complete(
1198        &self,
1199        mut req: rhema_core::ModelRequest,
1200        sink: &mut dyn EventSink,
1201    ) -> Result<ModelOutput, ProviderError> {
1202        // Plan under the lock: move the cut, commit stand-ins. Never
1203        // a model call, never an await here.
1204        let pending = {
1205            let mut transcript = self
1206                .transcript
1207                .lock()
1208                .unwrap_or_else(PoisonError::into_inner);
1209            transcript.observe(&req.messages);
1210            transcript.plan_flush()
1211        };
1212        // The fill runs after this request, outside it and outside the
1213        // lock: the request goes out now with the extractive
1214        // stand-ins, and the upgrades commit under the mirror's lock
1215        // as they land. A slow or failing worker delays nothing and
1216        // leaves the stand-in standing.
1217        if let Some(worker) = &self.summarizer
1218            && !pending.is_empty()
1219        {
1220            Self::spawn_worker_fill(Arc::clone(worker), Arc::clone(&self.transcript), pending);
1221        }
1222        let view = {
1223            let mut transcript = self
1224                .transcript
1225                .lock()
1226                .unwrap_or_else(PoisonError::into_inner);
1227            transcript.render()
1228        };
1229        if let Some(messages) = view {
1230            req.messages = messages;
1231        }
1232        {
1233            let mut transcript = self
1234                .transcript
1235                .lock()
1236                .unwrap_or_else(PoisonError::into_inner);
1237            transcript.stage_usage_shares(req.system.as_deref(), &req.tools, &req.messages);
1238        }
1239        let result = self.inner.complete(req, sink).await;
1240        if let Ok(output) = &result {
1241            let mut transcript = self
1242                .transcript
1243                .lock()
1244                .unwrap_or_else(PoisonError::into_inner);
1245            transcript.record_usage(&output.usage);
1246        }
1247        result
1248    }
1249}
1250
1251impl TranscriptView {
1252    /// Dispatches one background fill over `pending`: chunks of
1253    /// [`WORKER_CONCURRENCY`] summarize concurrently, and each chunk's
1254    /// answers commit under the mirror's lock as they resolve. The
1255    /// range check in [`Transcript::commit_summary`] rejects anything a
1256    /// concurrent plan rebuilt in the meantime, so a commit that races
1257    /// a flush or a consolidation drops its text and the stand-in
1258    /// stands.
1259    fn spawn_worker_fill(
1260        worker: Arc<dyn Summarizer>,
1261        mirror: Arc<Mutex<Transcript>>,
1262        pending: Vec<PendingSummary>,
1263    ) {
1264        tokio::spawn(async move {
1265            for chunk in pending.chunks(WORKER_CONCURRENCY) {
1266                let mut fills = Vec::with_capacity(chunk.len());
1267                for item in chunk {
1268                    let worker = Arc::clone(&worker);
1269                    let messages = item.messages.clone();
1270                    let context = item.context.clone();
1271                    let section = item.section;
1272                    let range = item.range;
1273                    fills.push(tokio::spawn(async move {
1274                        (
1275                            worker.summarize(&messages, context.as_deref()).await,
1276                            section,
1277                            range,
1278                        )
1279                    }));
1280                }
1281                for fill in fills {
1282                    // A task that panicked or was cancelled counts as a
1283                    // failure, like a provider error: the stand-in
1284                    // stands either way.
1285                    let outcome = match fill.await {
1286                        Ok((Ok(text), section, range)) => Some((text, section, range)),
1287                        _ => None,
1288                    };
1289                    let mut transcript = mirror.lock().unwrap_or_else(PoisonError::into_inner);
1290                    match outcome {
1291                        Some((text, section, range)) => {
1292                            // `commit_summary` reads the address, not
1293                            // the messages; the range check decides.
1294                            let pending = PendingSummary {
1295                                section,
1296                                range,
1297                                messages: Vec::new(),
1298                                context: None,
1299                            };
1300                            transcript.commit_summary(&pending, text);
1301                            transcript.record_worker_call(WorkerOutcome::Upgraded);
1302                        }
1303                        None => transcript.record_worker_call(WorkerOutcome::Failed),
1304                    }
1305                }
1306            }
1307        });
1308    }
1309}
1310
1311#[cfg(test)]
1312mod tests {
1313    use super::*;
1314    use rhema_core::{Content, ToolCall, ToolResult};
1315    use std::collections::HashSet;
1316    use std::sync::Mutex as StdMutex;
1317    use std::sync::atomic::{AtomicBool, Ordering};
1318
1319    /// The test runtime is current-thread: spawned tasks run while the
1320    /// test yields. Wait until `done` holds, then stop yielding.
1321    async fn wait_for(done: impl Fn() -> bool) {
1322        for _ in 0..10_000 {
1323            if done() {
1324                return;
1325            }
1326            tokio::task::yield_now().await;
1327        }
1328        panic!("the background fill never finished");
1329    }
1330
1331    /// A big tool result, in kilobytes.
1332    fn result_bytes(kb: usize) -> String {
1333        "x".repeat(kb * 1024)
1334    }
1335
1336    fn call_round(id: &str, result_kb: usize) -> Vec<Message> {
1337        vec![
1338            Message {
1339                role: Role::Assistant,
1340                content: vec![
1341                    Content::Text("checking".into()),
1342                    Content::ToolCall(ToolCall {
1343                        id: id.into(),
1344                        name: "bash".into(),
1345                        args: serde_json::json!({ "command": "make test" }),
1346                        provider_data: serde_json::Value::Null,
1347                    }),
1348                ],
1349            },
1350            Message {
1351                role: Role::Tool,
1352                content: vec![Content::ToolResult(ToolResult::success(
1353                    id,
1354                    result_bytes(result_kb),
1355                ))],
1356            },
1357        ]
1358    }
1359
1360    /// A history over the default budget: many 8 KiB tool rounds, then
1361    /// a final user message.
1362    fn long_history(rounds: usize) -> Vec<Message> {
1363        let mut messages = vec![Message::text(Role::User, "fix the build")];
1364        for i in 0..rounds {
1365            messages.extend(call_round(&format!("c{i}"), 8));
1366        }
1367        messages.push(Message::text(Role::User, "and now summarize"));
1368        messages
1369    }
1370
1371    fn settings(max_view_bytes: usize) -> TranscriptSettings {
1372        TranscriptSettings {
1373            max_view_bytes,
1374            ..TranscriptSettings::default()
1375        }
1376    }
1377
1378    #[test]
1379    fn below_the_budget_the_view_is_none() {
1380        let mut transcript = Transcript::new(settings(128_000));
1381        let messages = long_history(4); // ~33 KiB
1382        assert!(transcript.view(&messages).is_none());
1383        let stats = transcript.stats();
1384        assert_eq!(stats.requests, 1);
1385        assert_eq!(stats.pass_through, 1);
1386        assert_eq!(stats.viewed, 0);
1387    }
1388
1389    #[test]
1390    fn past_the_budget_the_aged_prefix_is_block_and_the_tail_whole() {
1391        let mut transcript = Transcript::new(settings(128_000));
1392        let messages = long_history(30); // ~245 KiB
1393        let view = transcript.view(&messages).unwrap();
1394
1395        // One synthetic user message first, tagged, carrying the
1396        // block's sections.
1397        assert_eq!(view[0].role, Role::User);
1398        let rhema_core::Content::Text(text) = &view[0].content[0] else {
1399            panic!("text view message");
1400        };
1401        assert!(text.starts_with("<transcript>"), "{text}");
1402        assert!(text.contains("zoom(id, n)"), "{text}");
1403        // Sections are addressed `id+n|`, tiling from the log's start.
1404        assert!(text.contains("0+"), "{text}");
1405
1406        // The tail, the last user message, is present whole.
1407        let last = view.last().unwrap();
1408        assert_eq!(*last, Message::text(Role::User, "and now summarize"));
1409        assert!(view.len() < messages.len(), "the view is shorter");
1410
1411        let stats = transcript.stats();
1412        assert_eq!(stats.flushes, 1);
1413        assert_eq!(stats.sectioned_messages, transcript.cut);
1414        assert!(stats.block_bytes > 0);
1415        assert!(stats.band_bytes + stats.block_bytes < 245 * 1024);
1416        // The token figures describe the same parts as the byte ones.
1417        assert!(stats.block_tokens > 0);
1418        assert!(stats.band_tokens > 0);
1419        assert!(stats.tail_tokens <= stats.band_tokens);
1420    }
1421
1422    #[test]
1423    fn between_flushes_the_block_is_append_only() {
1424        let mut transcript = Transcript::new(settings(40_000));
1425        let first = long_history(5); // ~40 KiB, over budget
1426        let view = transcript.view(&first).unwrap();
1427        let first_block = match &view[0].content[..] {
1428            [rhema_core::Content::Text(text)] => text.clone(),
1429            _ => panic!("text view message"),
1430        };
1431        let sections_after_first = transcript.sections.clone();
1432
1433        // Growth well under the hysteresis: no new flush, the
1434        // committed sections byte-identical, only the band grows.
1435        let mut second = first.clone();
1436        second.extend(call_round("c5", 1));
1437        second.push(Message::text(Role::User, "next"));
1438        let view = transcript.view(&second).unwrap();
1439        let second_block = match &view[0].content[..] {
1440            [rhema_core::Content::Text(text)] => text.clone(),
1441            _ => panic!("text view message"),
1442        };
1443        assert_eq!(transcript.stats.flushes, 1, "no second flush");
1444        assert_eq!(transcript.sections, sections_after_first);
1445        assert_eq!(first_block, second_block, "the block is byte-identical");
1446        assert!(view.len() > 1);
1447    }
1448
1449    #[test]
1450    fn a_flush_overshoots_to_half_the_allowance_and_the_hysteresis_holds() {
1451        let mut transcript = Transcript::new(settings(128_000));
1452        let mut messages = vec![Message::text(Role::User, "fix the build")];
1453        for i in 0..20 {
1454            messages.extend(call_round(&format!("c{i}"), 8)); // ~164 KiB
1455        }
1456        messages.push(Message::text(Role::User, "go on"));
1457        assert!(transcript.view(&messages).is_some());
1458        let stats = transcript.stats();
1459        assert_eq!(stats.flushes, 1);
1460        // The band the flush leaves behind sits at or below half the
1461        // allowance, the overshoot, not at the full allowance.
1462        let allowance = 128_000 - stats.tail_bytes;
1463        let band = stats.band_bytes - stats.tail_bytes;
1464        assert!(
1465            band <= allowance / 2,
1466            "band {band} over half the allowance {}",
1467            allowance / 2
1468        );
1469        // The hysteresis is the half-allowance the overshoot bought:
1470        // growth inside it must not flush again.
1471        let mut grown = messages.clone();
1472        for i in 20..26 {
1473            grown.extend(call_round(&format!("c{i}"), 8)); // ~49 KiB < allowance/2
1474        }
1475        grown.push(Message::text(Role::User, "still going"));
1476        transcript.view(&grown);
1477        assert_eq!(transcript.stats.flushes, 1, "flushed inside the hysteresis");
1478    }
1479
1480    #[test]
1481    fn a_flush_never_splits_a_tool_round_at_a_section_boundary() {
1482        let mut transcript = Transcript::new(settings(20_000));
1483        // user, round c0 (16 KiB), round c1 (16 KiB), user.
1484        let messages = vec![Message::text(Role::User, "go")]
1485            .into_iter()
1486            .chain(call_round("c0", 16))
1487            .chain(call_round("c1", 16))
1488            .chain(std::iter::once(Message::text(Role::User, "done")))
1489            .collect::<Vec<_>>();
1490        let view = transcript.view(&messages).unwrap();
1491        // Every tool result carried whole has its call carried too:
1492        // the pairs survive the cut together.
1493        let carried_calls: HashSet<String> = view
1494            .iter()
1495            .flat_map(|m| &m.content)
1496            .filter_map(|c| match c {
1497                rhema_core::Content::ToolCall(call) => Some(call.id.clone()),
1498                _ => None,
1499            })
1500            .collect();
1501        for message in &view {
1502            for content in &message.content {
1503                if let rhema_core::Content::ToolResult(result) = content {
1504                    assert!(
1505                        carried_calls.contains(&result.id),
1506                        "orphan result {} in the view",
1507                        result.id
1508                    );
1509                }
1510            }
1511        }
1512        // And no section's range opens on a result: the same pairing
1513        // holds inside the block, so a section never stands in for a
1514        // round it splits.
1515        for section in &transcript.sections {
1516            let first = transcript
1517                .range(section.range)
1518                .expect("section in the log")
1519                .first()
1520                .unwrap();
1521            assert_ne!(first.role, Role::Tool, "section {:?}", section.range);
1522        }
1523    }
1524
1525    #[test]
1526    fn sections_respect_the_step_and_message_bounds() {
1527        let mut transcript = Transcript::new(TranscriptSettings {
1528            step_bytes: 20_000,
1529            max_section_messages: 3,
1530            ..settings(20_000)
1531        });
1532        let messages = long_history(8);
1533        transcript.observe(&messages);
1534        transcript.plan_flush();
1535        assert!(transcript.sections.len() > 1, "bounds force a split");
1536        for section in &transcript.sections {
1537            assert!(section.range.n <= 4, "{:?}", section.range);
1538        }
1539        // The sections tile the cut without gaps.
1540        let mut at = 0;
1541        for section in &transcript.sections {
1542            assert_eq!(section.range.id, at);
1543            at += section.range.n;
1544        }
1545        assert_eq!(at, transcript.cut);
1546    }
1547
1548    #[test]
1549    fn a_worker_upgrade_lands_and_a_wrong_one_is_rejected() {
1550        let mut transcript = Transcript::new(settings(20_000));
1551        let messages = long_history(30);
1552        transcript.observe(&messages);
1553        let pending = transcript.plan_flush();
1554        assert!(!pending.is_empty());
1555
1556        let good = pending[0].clone();
1557        assert!(transcript.commit_summary(&good, "## Goals Met\n- all".into()));
1558        assert_eq!(transcript.sections[0].text, "## Goals Met\n- all");
1559        assert_eq!(transcript.sections[0].origin, SectionOrigin::Model);
1560
1561        // A stale pending, the range moved on, is dropped.
1562        // The context is irrelevant to the commit's range check.
1563        let stale = PendingSummary {
1564            section: pending[0].section,
1565            range: Range { id: 999, n: 1 },
1566            messages: Vec::new(),
1567            context: None,
1568        };
1569        assert!(!transcript.commit_summary(&stale, "ghost".into()));
1570        assert_eq!(transcript.sections[0].text, "## Goals Met\n- all");
1571    }
1572
1573    #[test]
1574    fn a_resume_adopts_the_saved_sections_and_skips_the_refill() {
1575        let log = long_history(30);
1576        // The first session sections and upgrades the block.
1577        let mut first = Transcript::new(settings(20_000));
1578        first.observe(&log);
1579        let pending = first.plan_flush();
1580        assert!(!pending.is_empty());
1581        for item in &pending {
1582            assert!(first.commit_summary(item, format!("## Goals Met\n- model {}", item.section)));
1583        }
1584        let saved = first.saved_sections();
1585        assert!(saved.iter().all(|s| s.origin == SectionOrigin::Model));
1586
1587        // The resumed session adopts them: the compaction the last
1588        // session paid for rides as-is, dense from the first request.
1589        let mut second = Transcript::new(settings(20_000));
1590        second.adopt_sections(saved.clone());
1591        second.observe(&log);
1592        assert_eq!(second.cut, first.cut);
1593        assert_eq!(second.sections, saved);
1594        // No re-sectioning, no pending fill: nothing to re-pay.
1595        assert!(second.plan_flush().is_empty());
1596
1597        // The band keeps growing from the adopted cut.
1598        let mut extended = log.clone();
1599        extended.push(Message::text(Role::User, "one more"));
1600        second.observe(&extended);
1601        let view = second.render().unwrap();
1602        assert_eq!(view.last(), Some(&Message::text(Role::User, "one more")));
1603    }
1604
1605    // --- the skill pin ---
1606
1607    /// A skill body, frontmatter included, at a known size.
1608    fn skill_body(name: &str, rules: usize) -> String {
1609        let mut body = format!("---\nname: {name}\ndescription: the {name} trigger\n---\n\n");
1610        for i in 0..rules {
1611            body.push_str(&format!("Rule {i}: do the {name} thing.\n"));
1612        }
1613        body
1614    }
1615
1616    /// The shell's wrapped form of a `cat` result: exit code, stdout,
1617    /// stderr (shell.rs renders exactly this around a command's
1618    /// output).
1619    fn cat_result(id: &str, stdout: &str) -> Message {
1620        Message {
1621            role: Role::Tool,
1622            content: vec![Content::ToolResult(ToolResult::success(
1623                id,
1624                format!("exit code 0\n--- stdout ---\n{stdout}\n--- stderr ---\n"),
1625            ))],
1626        }
1627    }
1628
1629    /// One turn reading a skill: the bash cat, then the wrapped body.
1630    fn skill_round(id: &str, name: &str, rules: usize) -> Vec<Message> {
1631        let body = skill_body(name, rules);
1632        vec![
1633            Message {
1634                role: Role::Assistant,
1635                content: vec![
1636                    Content::Text("loading the skill".into()),
1637                    Content::ToolCall(ToolCall {
1638                        id: id.into(),
1639                        name: "bash".into(),
1640                        args: serde_json::json!({
1641                            "command": format!("cat .rhema/skills/{name}/SKILL.md")
1642                        }),
1643                        provider_data: serde_json::Value::Null,
1644                    }),
1645                ],
1646            },
1647            cat_result(id, &body),
1648        ]
1649    }
1650
1651    #[test]
1652    fn a_flushed_skill_read_rides_the_block_whole_and_unsummarized() {
1653        let mut transcript = Transcript::new(settings(40_000));
1654        transcript.set_skills(vec![SkillText {
1655            name: "unslop".into(),
1656            body: skill_body("unslop", 40),
1657        }]);
1658        let mut messages = vec![Message::text(Role::User, "fix the build")];
1659        messages.extend(skill_round("s1", "unslop", 40));
1660        messages.extend(long_history(6));
1661        messages.push(Message::text(Role::User, "and now summarize"));
1662
1663        transcript.observe(&messages);
1664        let pending = transcript.plan_flush();
1665        let body = skill_body("unslop", 40);
1666
1667        // The pinned span is its own two-message section, never queued
1668        // for the worker: no fill can rewrite the body into a count
1669        // line.
1670        let pinned = transcript
1671            .sections
1672            .iter()
1673            .find(|section| !section.pinned.is_empty())
1674            .expect("one pinned section");
1675        assert_eq!(pinned.pinned, ["unslop"]);
1676        assert_eq!(pinned.range.n, 2);
1677        assert!(pinned.text.contains(&body), "{}", pinned.text);
1678        assert!(!pending.iter().any(|summary| summary.range == pinned.range));
1679
1680        // The rendered block carries the body verbatim, shell wrapper
1681        // and all detection passing.
1682        let view = transcript.render().unwrap();
1683        let rhema_core::Content::Text(text) = &view[0].content[0] else {
1684            panic!("text view message");
1685        };
1686        assert!(text.contains(&body), "{text}");
1687    }
1688
1689    #[test]
1690    fn a_reread_compacts_to_a_pointer_at_the_first_copy() {
1691        let mut transcript = Transcript::new(settings(40_000));
1692        transcript.set_skills(vec![SkillText {
1693            name: "unslop".into(),
1694            body: skill_body("unslop", 40),
1695        }]);
1696        let mut messages = vec![Message::text(Role::User, "fix the build")];
1697        messages.extend(skill_round("s1", "unslop", 40));
1698        messages.extend(skill_round("s2", "unslop", 40));
1699        messages.extend(long_history(6));
1700        messages.push(Message::text(Role::User, "and now summarize"));
1701
1702        transcript.observe(&messages);
1703        transcript.plan_flush();
1704
1705        let pinned: Vec<_> = transcript
1706            .sections
1707            .iter()
1708            .filter(|section| !section.pinned.is_empty())
1709            .collect();
1710        assert_eq!(pinned.len(), 1, "one carrier");
1711        let carried = pinned[0].range;
1712        let body = skill_body("unslop", 40);
1713        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_eq!(text.matches(&body).count(), 1, "one copy of the body");
1718        assert!(
1719            text.contains(&format!(
1720                "skill unslop read again; its whole text is carried at {}+{}|",
1721                carried.id, carried.n
1722            )),
1723            "{text}"
1724        );
1725    }
1726
1727    #[test]
1728    fn a_multicall_turn_digests_normally_without_a_pin() {
1729        let mut transcript = Transcript::new(settings(40_000));
1730        transcript.set_skills(vec![SkillText {
1731            name: "unslop".into(),
1732            body: skill_body("unslop", 40),
1733        }]);
1734        let mut messages = vec![Message::text(Role::User, "fix the build")];
1735        // One turn, two calls: the skill cat plus an unrelated command.
1736        // Pinning would orphan the second result behind its call.
1737        messages.push(Message {
1738            role: Role::Assistant,
1739            content: vec![
1740                Content::ToolCall(ToolCall {
1741                    id: "a".into(),
1742                    name: "bash".into(),
1743                    args: serde_json::json!({ "command": "cat the skill" }),
1744                    provider_data: serde_json::Value::Null,
1745                }),
1746                Content::ToolCall(ToolCall {
1747                    id: "b".into(),
1748                    name: "bash".into(),
1749                    args: serde_json::json!({ "command": "make test" }),
1750                    provider_data: serde_json::Value::Null,
1751                }),
1752            ],
1753        });
1754        messages.push(cat_result("a", &skill_body("unslop", 40)));
1755        messages.push(cat_result("b", "ok"));
1756        messages.extend(long_history(6));
1757        messages.push(Message::text(Role::User, "and now summarize"));
1758
1759        transcript.observe(&messages);
1760        transcript.plan_flush();
1761        assert!(
1762            transcript.sections.iter().all(|s| s.pinned.is_empty()),
1763            "{:?}",
1764            transcript.sections
1765        );
1766    }
1767
1768    #[test]
1769    fn consolidation_keeps_the_pinned_body_in_the_block() {
1770        let mut transcript = Transcript::new(TranscriptSettings {
1771            max_view_bytes: 40_000,
1772            step_bytes: 4_000,
1773            max_block_bytes: 1_000,
1774            ..TranscriptSettings::default()
1775        });
1776        transcript.set_skills(vec![SkillText {
1777            name: "unslop".into(),
1778            body: skill_body("unslop", 40),
1779        }]);
1780        let mut messages = vec![Message::text(Role::User, "fix the build")];
1781        messages.extend(skill_round("s1", "unslop", 40));
1782        messages.extend(long_history(30));
1783        messages.push(Message::text(Role::User, "and now summarize"));
1784
1785        transcript.observe(&messages);
1786        transcript.plan_flush();
1787        let body = skill_body("unslop", 40);
1788        assert!(
1789            transcript.stats.consolidations > 0,
1790            "the fixture must consolidate"
1791        );
1792        let view = transcript.render().unwrap();
1793        let rhema_core::Content::Text(text) = &view[0].content[0] else {
1794            panic!("text view message");
1795        };
1796        assert!(text.contains(&body), "{text}");
1797    }
1798
1799    #[test]
1800    fn the_model_fill_leaves_the_pinned_body_beneath_it() {
1801        let mut transcript = Transcript::new(TranscriptSettings {
1802            max_view_bytes: 40_000,
1803            step_bytes: 4_000,
1804            max_block_bytes: 1_000,
1805            ..TranscriptSettings::default()
1806        });
1807        transcript.set_skills(vec![SkillText {
1808            name: "unslop".into(),
1809            body: skill_body("unslop", 40),
1810        }]);
1811        let mut messages = vec![Message::text(Role::User, "fix the build")];
1812        messages.extend(skill_round("s1", "unslop", 40));
1813        messages.extend(long_history(30));
1814        messages.push(Message::text(Role::User, "and now summarize"));
1815
1816        transcript.observe(&messages);
1817        let pending = transcript.plan_flush();
1818        let body = skill_body("unslop", 40);
1819
1820        // The consolidation's live union pending: its range still
1821        // matches the section, and the section carries the pin.
1822        let summary = pending
1823            .iter()
1824            .rev()
1825            .find(|summary| {
1826                transcript
1827                    .sections
1828                    .get(summary.section)
1829                    .is_some_and(|section| {
1830                        section.range == summary.range && !section.pinned.is_empty()
1831                    })
1832            })
1833            .expect("a live union pending over a pinned section")
1834            .clone();
1835        assert!(transcript.commit_summary(&summary, "## Goals Met\n- dense fill".into()));
1836        let text = &transcript.sections[summary.section].text;
1837        assert!(text.starts_with("## Goals Met\n- dense fill"), "{text}");
1838        assert!(text.contains(&body), "{text}");
1839    }
1840
1841    #[test]
1842    fn a_resume_keeps_deduplicating_rereads() {
1843        let mut first = Transcript::new(settings(40_000));
1844        first.set_skills(vec![SkillText {
1845            name: "unslop".into(),
1846            body: skill_body("unslop", 40),
1847        }]);
1848        let mut messages = vec![Message::text(Role::User, "fix the build")];
1849        messages.extend(skill_round("s1", "unslop", 40));
1850        messages.extend(long_history(8));
1851        messages.push(Message::text(Role::User, "and now summarize"));
1852        first.observe(&messages);
1853        first.plan_flush();
1854        let saved = first.saved_sections();
1855        assert!(!saved.is_empty(), "the first session must have flushed");
1856
1857        // The resume adopts those sections, then a re-read of the same
1858        // skill flushes to a pointer, not a second body.
1859        let mut second = Transcript::new(settings(40_000));
1860        second.adopt_sections(saved);
1861        let mut resumed = messages.clone();
1862        resumed.extend(skill_round("s2", "unslop", 40));
1863        resumed.extend(long_history(2));
1864        resumed.push(Message::text(Role::User, "one more"));
1865        second.observe(&resumed);
1866        second.plan_flush();
1867        let body = skill_body("unslop", 40);
1868        let view = second.render().unwrap();
1869        let rhema_core::Content::Text(text) = &view[0].content[0] else {
1870            panic!("text view message");
1871        };
1872        assert_eq!(text.matches(&body).count(), 1, "one copy after resume");
1873    }
1874
1875    #[test]
1876    fn tampered_saved_sections_fall_back_to_the_rebuild() {
1877        let mut transcript = Transcript::new(settings(20_000));
1878        transcript.adopt_sections(vec![Section {
1879            range: Range { id: 5, n: 9 },
1880            text: "## Goals Met\n- orphan".into(),
1881            origin: SectionOrigin::Model,
1882            pinned: Vec::new(),
1883        }]);
1884        transcript.observe(&long_history(30));
1885        // The first id 5, not 0: the tiling rejects the adoption.
1886        assert_eq!(transcript.cut, 0);
1887        assert!(transcript.sections.is_empty());
1888        // The next request rebuilds from nothing.
1889        assert!(!transcript.plan_flush().is_empty());
1890    }
1891
1892    #[test]
1893    fn a_pending_summary_carries_the_adjacent_digest_as_context() {
1894        let mut transcript = Transcript::new(settings(20_000));
1895        transcript.observe(&long_history(30));
1896        let pending = transcript.plan_flush();
1897        assert!(pending.len() >= 2);
1898        // The first section has no predecessor; every later one points
1899        // at the stand-in committed for the section before it.
1900        assert_eq!(pending[0].context, None);
1901        for (prev, item) in pending.iter().zip(pending.iter().skip(1)) {
1902            let expected = transcript.sections[prev.section].text.clone();
1903            assert_eq!(item.context.as_deref(), Some(expected.as_str()));
1904        }
1905
1906        // A later flush's first chunk inherits the block's last
1907        // section as its context.
1908        let first = pending[0].clone();
1909        assert!(transcript.commit_summary(&first, "## Goals Met\n- model".into()));
1910        let mut extended = long_history(30);
1911        for i in 0..12 {
1912            extended.push(Message::text(
1913                Role::User,
1914                format!("extra filler {i}: {}", "y".repeat(1024)),
1915            ));
1916        }
1917        transcript.observe(&extended);
1918        // Read the predecessor before planning: plan_flush itself
1919        // pushes the new sections.
1920        let expected = transcript.sections.last().unwrap().text.clone();
1921        let pending = transcript.plan_flush();
1922        assert!(!pending.is_empty());
1923        assert_eq!(pending[0].context.as_deref(), Some(expected.as_str()));
1924    }
1925
1926    #[test]
1927    fn the_block_consolidates_past_its_cap() {
1928        let mut transcript = Transcript::new(TranscriptSettings {
1929            max_block_bytes: 500,
1930            ..settings(20_000)
1931        });
1932        let messages = long_history(30);
1933        transcript.observe(&messages);
1934        transcript.plan_flush();
1935        assert!(transcript.block_bytes() <= 500);
1936        assert!(transcript.stats.consolidations > 0);
1937        // The surviving sections still tile the prefix.
1938        let mut at = 0;
1939        for section in &transcript.sections {
1940            assert_eq!(section.range.id, at);
1941            at += section.range.n;
1942        }
1943        assert_eq!(at, transcript.cut);
1944    }
1945
1946    #[test]
1947    fn a_resumed_session_rebuilds_the_compaction_from_nothing() {
1948        let mut transcript = Transcript::new(settings(20_000));
1949        transcript.observe(&long_history(30));
1950        transcript.plan_flush();
1951        assert!(transcript.cut > 0);
1952        // A different history wholesale: the derived state resets.
1953        transcript.observe(&long_history(2));
1954        assert_eq!(transcript.cut, 0);
1955        assert!(transcript.sections.is_empty());
1956    }
1957
1958    #[test]
1959    fn the_breakdown_spreads_reported_input_by_wire_share() {
1960        let mut transcript = Transcript::new(TranscriptSettings::default());
1961        transcript.set_skills_bytes(500);
1962        // System: 1500 base bytes + 500 skills bytes. Messages: one
1963        // user text, one assistant text with a call, one result.
1964        let system = format!("{}{}", "b".repeat(1_500), "s".repeat(500));
1965        let call_args = serde_json::json!({ "c": "x".repeat(100) });
1966        let messages = vec![
1967            Message::text(Role::User, "u".repeat(1_000)),
1968            Message {
1969                role: Role::Assistant,
1970                content: vec![
1971                    Content::Text("a".repeat(400)),
1972                    Content::ToolCall(ToolCall {
1973                        id: "c1".into(),
1974                        name: "bash".into(),
1975                        args: call_args.clone(),
1976                        provider_data: serde_json::Value::Null,
1977                    }),
1978                ],
1979            },
1980            Message {
1981                role: Role::Tool,
1982                content: vec![Content::ToolResult(ToolResult::success(
1983                    "c1",
1984                    "r".repeat(1_000),
1985                ))],
1986            },
1987        ];
1988        transcript.stage_usage_shares(Some(&system), &[], &messages);
1989        transcript.record_usage(&Usage {
1990            input_tokens: 10_000,
1991            output_tokens: 100,
1992            cached_input_tokens: 0,
1993        });
1994
1995        let total = 2_000 + 1_000 + 400 + ("bash".len() + call_args.to_string().len()) + 1_000;
1996        let spread = |bytes: usize| 10_000 * bytes as u64 / total as u64;
1997        let b = transcript.stats().usage;
1998        assert_eq!(b.system_prompt_tokens, spread(1_500));
1999        assert_eq!(b.skills_tokens, spread(500));
2000        assert_eq!(
2001            b.tool_calls_input_tokens,
2002            spread("bash".len() + call_args.to_string().len())
2003        );
2004        assert_eq!(b.tool_calls_output_tokens, spread(1_000));
2005        assert_eq!(b.user_messages_tokens, spread(1_000));
2006        // The model's words: the history's assistant text plus the
2007        // generated output.
2008        assert_eq!(b.model_output_tokens, spread(400) + 100);
2009        // The shares consumed: a usage record without a staged request
2010        // spreads nothing.
2011        transcript.record_usage(&Usage {
2012            input_tokens: 1_000,
2013            output_tokens: 0,
2014            cached_input_tokens: 0,
2015        });
2016        assert_eq!(transcript.stats().usage.user_messages_tokens, spread(1_000));
2017    }
2018
2019    #[test]
2020    fn a_skills_share_past_the_system_clamps() {
2021        let mut transcript = Transcript::new(TranscriptSettings::default());
2022        transcript.set_skills_bytes(9_999);
2023        transcript.stage_usage_shares(Some("short"), &[], &[]);
2024        transcript.record_usage(&Usage {
2025            input_tokens: 100,
2026            output_tokens: 0,
2027            cached_input_tokens: 0,
2028        });
2029        let b = transcript.stats().usage;
2030        assert_eq!(b.skills_tokens, 100);
2031        assert_eq!(b.system_prompt_tokens, 0);
2032    }
2033
2034    #[test]
2035    fn a_carry_continues_the_saved_run() {
2036        let saved = TranscriptStats {
2037            requests: 10,
2038            pass_through: 6,
2039            viewed: 4,
2040            flushes: 1,
2041            consolidations: 1,
2042            summarizer_calls: 2,
2043            summarizer_failures: 1,
2044            input_tokens: 90_000,
2045            cached_input_tokens: 70_000,
2046            output_tokens: 10_000,
2047            usage: UsageBreakdown {
2048                system_prompt_tokens: 20_000,
2049                skills_tokens: 2_000,
2050                tool_calls_input_tokens: 30_000,
2051                tool_calls_output_tokens: 30_000,
2052                user_messages_tokens: 8_000,
2053                model_output_tokens: 10_000,
2054            },
2055            // The saved snapshot describes the log the resume replaced.
2056            log_messages: 12,
2057            sectioned_messages: 4,
2058            sections: 2,
2059            block_bytes: 900,
2060            block_tokens: 225,
2061            band_bytes: 3_000,
2062            band_tokens: 820,
2063            tail_bytes: 1_200,
2064            tail_tokens: 340,
2065            log_bytes: 5_400,
2066            log_content: LogContent {
2067                tool_calls: 100,
2068                tool_results: 4_000,
2069                user_text: 300,
2070                assistant_text: 1_000,
2071            },
2072        };
2073
2074        // A mirror that has not looked at a log yet shows the saved
2075        // run whole, the counters and, until its first request, the
2076        // snapshot too.
2077        let mut fresh = TranscriptStats::default();
2078        fresh.carry(&saved);
2079        assert_eq!(fresh, saved);
2080
2081        // The mirror then counts requests of its own: each read folds
2082        // the same saved run in once, so the totals are the run's,
2083        // never doubled, and the snapshot is the live mirror's.
2084        let mut live = TranscriptStats {
2085            requests: 2,
2086            input_tokens: 5_000,
2087            output_tokens: 300,
2088            usage: UsageBreakdown {
2089                user_messages_tokens: 5_000,
2090                model_output_tokens: 300,
2091                ..UsageBreakdown::default()
2092            },
2093            log_messages: 4,
2094            block_bytes: 100,
2095            ..TranscriptStats::default()
2096        };
2097        live.carry(&saved);
2098        assert_eq!(live.requests, 12);
2099        assert_eq!(live.input_tokens, 95_000);
2100        assert_eq!(live.output_tokens, 10_300);
2101        assert_eq!(live.usage.user_messages_tokens, 13_000);
2102        assert_eq!(live.usage.model_output_tokens, 10_300);
2103        assert_eq!(live.usage.system_prompt_tokens, 20_000);
2104        assert_eq!(live.block_bytes, 100, "the live mirror's snapshot");
2105        assert_eq!(live.log_messages, 4);
2106
2107        // A later read: the mirror grew, the baseline still folds in
2108        // once.
2109        let mut later = TranscriptStats {
2110            requests: 3,
2111            input_tokens: 8_000,
2112            ..TranscriptStats::default()
2113        };
2114        later.carry(&saved);
2115        assert_eq!(later.requests, 13);
2116        assert_eq!(later.input_tokens, 98_000);
2117    }
2118
2119    /// The log-size snapshot: what the conversation holds, each
2120    /// message counted once, refreshed on every request, pass-through
2121    /// ones included. The usage split's once-counted counterpart.
2122    #[test]
2123    fn the_log_bytes_snapshot_counts_the_log_once() {
2124        let mut transcript = Transcript::new(settings(128_000));
2125        let messages = long_history(4); // ~33 KiB, below the budget
2126        transcript.observe(&messages);
2127        transcript.render();
2128        let expected: usize = messages.iter().map(summary::message_bytes).sum();
2129        assert_eq!(transcript.stats().log_bytes, expected);
2130
2131        // An extension rides in; the next request recounts the log.
2132        let grown = long_history(5);
2133        transcript.observe(&grown);
2134        transcript.render();
2135        let expected: usize = grown.iter().map(summary::message_bytes).sum();
2136        assert_eq!(transcript.stats().log_bytes, expected);
2137    }
2138
2139    /// The content split: the log's estimated tokens by category, each
2140    /// message counted once. For this fixture the categories tile the
2141    /// log, no images, no system or tool-role text, so they sum to
2142    /// the log's whole estimate.
2143    #[test]
2144    fn the_content_split_counts_each_message_once() {
2145        let mut transcript = Transcript::new(settings(128_000));
2146        let messages = long_history(4);
2147        transcript.observe(&messages);
2148        transcript.render();
2149        let content = transcript.stats().log_content;
2150        assert_eq!(
2151            content.tool_results,
2152            4 * summary::text_tokens(result_bytes(8).len())
2153        );
2154        assert_eq!(
2155            content.assistant_text,
2156            4 * summary::text_tokens("checking".len())
2157        );
2158        assert_eq!(
2159            content.user_text,
2160            summary::text_tokens("fix the build".len())
2161                + summary::text_tokens("and now summarize".len())
2162        );
2163        let args = serde_json::json!({ "command": "make test" }).to_string();
2164        assert_eq!(
2165            content.tool_calls,
2166            4 * summary::text_tokens("bash".len() + args.len())
2167        );
2168        // The categories tile the log's tokens: the figure the Usage
2169        // page heads the split with.
2170        let expected: u64 = messages.iter().map(summary::message_tokens).sum();
2171        assert_eq!(content.total(), expected);
2172    }
2173
2174    #[test]
2175    fn an_image_costs_one_message_in_the_split_and_the_budget() {
2176        let mut transcript = Transcript::new(settings(128_000));
2177        transcript.observe(&[Message {
2178            role: Role::Tool,
2179            content: vec![Content::ToolResult(
2180                ToolResult::success("c1", "ok").with_images(vec![rhema_core::Image::new(
2181                    rhema_core::ImageMediaType::Png,
2182                    "A".repeat(2_000_000),
2183                )]),
2184            )],
2185        }]);
2186        transcript.render();
2187        let stats = transcript.stats();
2188        // Two megabytes of base64 is one message: "ok" plus the flat
2189        // charge, so the split still tiles the log's bytes.
2190        assert_eq!(stats.log_bytes, 2 + summary::IMAGE_BYTES);
2191        // In tokens the image is its vision price, not a byte count.
2192        assert_eq!(stats.log_content.tool_results, summary::IMAGE_TOKENS);
2193    }
2194
2195    #[test]
2196    fn reset_stats_zeroes_the_accounting_and_keeps_the_log() {
2197        let mut transcript = Transcript::new(TranscriptSettings::default());
2198        transcript.observe(&[Message::text(Role::User, "kept")]);
2199        transcript.record_usage(&Usage {
2200            input_tokens: 1_000,
2201            output_tokens: 100,
2202            cached_input_tokens: 0,
2203        });
2204        assert_eq!(transcript.len(), 1);
2205        transcript.reset_stats();
2206        assert_eq!(transcript.stats(), TranscriptStats::default());
2207        assert_eq!(transcript.len(), 1);
2208    }
2209
2210    #[test]
2211    fn usage_records_and_the_hit_rate_reads() {
2212        let mut transcript = Transcript::new(TranscriptSettings::default());
2213        assert!(transcript.stats().cache_hit_rate().is_none());
2214        transcript.record_usage(&Usage {
2215            input_tokens: 1_000,
2216            output_tokens: 100,
2217            cached_input_tokens: 800,
2218        });
2219        let stats = transcript.stats();
2220        assert_eq!(stats.input_tokens, 1_000);
2221        assert_eq!(stats.cached_input_tokens, 800);
2222        let rate = stats.cache_hit_rate().unwrap();
2223        assert!((rate - 0.8).abs() < 1e-9);
2224    }
2225
2226    /// Records what it was handed.
2227    struct Recording(StdMutex<Vec<Vec<Message>>>);
2228    #[async_trait]
2229    impl ModelProvider for Recording {
2230        async fn complete(
2231            &self,
2232            req: rhema_core::ModelRequest,
2233            _sink: &mut dyn EventSink,
2234        ) -> Result<ModelOutput, ProviderError> {
2235            self.0.lock().unwrap().push(req.messages);
2236            Ok(ModelOutput {
2237                message: Message::text(Role::Assistant, "done"),
2238                stop_reason: rhema_core::StopReason::EndTurn,
2239                usage: Usage {
2240                    input_tokens: 500,
2241                    output_tokens: 10,
2242                    cached_input_tokens: 400,
2243                },
2244            })
2245        }
2246    }
2247
2248    #[tokio::test]
2249    async fn the_decorator_rewrites_the_request_and_the_mirror_stays_whole() {
2250        let recording = Arc::new(Recording(StdMutex::new(Vec::new())));
2251        let transcript = Arc::new(Mutex::new(Transcript::new(settings(20_000))));
2252        let view = TranscriptView::new(recording.clone(), transcript.clone());
2253        let messages = long_history(30);
2254        let req = rhema_core::ModelRequest {
2255            system: None,
2256            messages: messages.clone(),
2257            tools: Vec::new(),
2258            params: rhema_core::ChatParams::new("m"),
2259        };
2260        let mut sink = NoopSink;
2261        view.complete(req, &mut sink).await.unwrap();
2262
2263        let seen = recording.0.lock().unwrap();
2264        let sent = &seen[0];
2265        assert!(sent.len() < messages.len());
2266        assert_eq!(sent.last().unwrap().role, Role::User);
2267        // The mirror kept every message, none dropped.
2268        let mirror = transcript.lock().unwrap();
2269        assert_eq!(mirror.len(), messages.len());
2270        assert_eq!(mirror.message(0), Some(&messages[0]));
2271        // The usage landed: the hit rate is reportable.
2272        assert_eq!(mirror.stats().cache_hit_rate(), Some(0.8));
2273    }
2274
2275    #[tokio::test]
2276    async fn the_decorator_upgrades_sections_with_its_summarizer() {
2277        /// Answers every call with the same dense block.
2278        struct Worker;
2279        #[async_trait]
2280        impl ModelProvider for Worker {
2281            async fn complete(
2282                &self,
2283                _req: rhema_core::ModelRequest,
2284                _sink: &mut dyn EventSink,
2285            ) -> Result<ModelOutput, ProviderError> {
2286                Ok(ModelOutput {
2287                    message: Message::text(Role::Assistant, "## Goals Met\n- worker wrote this"),
2288                    stop_reason: rhema_core::StopReason::EndTurn,
2289                    usage: Usage::default(),
2290                })
2291            }
2292        }
2293
2294        let recording = Arc::new(Recording(StdMutex::new(Vec::new())));
2295        let transcript = Arc::new(Mutex::new(Transcript::new(settings(20_000))));
2296        let view = TranscriptView::with_summarizer(
2297            recording.clone(),
2298            transcript.clone(),
2299            Arc::new(compact::ModelSummarizer::new(Arc::new(Worker), "cheap")),
2300        );
2301        let req = rhema_core::ModelRequest {
2302            system: None,
2303            messages: long_history(30),
2304            tools: Vec::new(),
2305            params: rhema_core::ChatParams::new("m"),
2306        };
2307        let mut sink = NoopSink;
2308        view.complete(req, &mut sink).await.unwrap();
2309
2310        // The request went out with the extractive stand-ins: the fill
2311        // had not landed when it rendered.
2312        {
2313            let sent = recording.0.lock().unwrap();
2314            let rhema_core::Content::Text(text) = &sent[0][0].content[0] else {
2315                panic!("text view message");
2316            };
2317            assert!(!text.contains("worker wrote this"), "{text}");
2318        }
2319
2320        // The background fill upgrades every section.
2321        wait_for(|| {
2322            transcript
2323                .lock()
2324                .unwrap()
2325                .sections
2326                .iter()
2327                .all(|s| s.origin == SectionOrigin::Model)
2328        })
2329        .await;
2330
2331        // The guard drops at the brace: the runtime is current-thread,
2332        // so the next request cannot take the lock while it is held.
2333        {
2334            let mirror = transcript.lock().unwrap();
2335            let stats = mirror.stats();
2336            assert!(stats.summarizer_calls > 0);
2337            assert_eq!(stats.summarizer_failures, 0);
2338            assert!(
2339                mirror
2340                    .sections
2341                    .iter()
2342                    .all(|s| s.text.contains("worker wrote this"))
2343            );
2344        }
2345
2346        // The next request carries the dense text.
2347        let req = rhema_core::ModelRequest {
2348            system: None,
2349            messages: long_history(30),
2350            tools: Vec::new(),
2351            params: rhema_core::ChatParams::new("m"),
2352        };
2353        let mut sink = NoopSink;
2354        view.complete(req, &mut sink).await.unwrap();
2355        let sent = recording.0.lock().unwrap();
2356        let rhema_core::Content::Text(text) = &sent[1][0].content[0] else {
2357            panic!("text view message");
2358        };
2359        assert!(text.contains("worker wrote this"), "{text}");
2360    }
2361
2362    #[tokio::test]
2363    async fn a_failing_summarizer_never_blocks_the_request() {
2364        struct Failing;
2365        #[async_trait]
2366        impl ModelProvider for Failing {
2367            async fn complete(
2368                &self,
2369                _req: rhema_core::ModelRequest,
2370                _sink: &mut dyn EventSink,
2371            ) -> Result<ModelOutput, ProviderError> {
2372                Err(ProviderError::Timeout)
2373            }
2374        }
2375
2376        let recording = Arc::new(Recording(StdMutex::new(Vec::new())));
2377        let transcript = Arc::new(Mutex::new(Transcript::new(settings(20_000))));
2378        let view = TranscriptView::with_summarizer(
2379            recording.clone(),
2380            transcript.clone(),
2381            Arc::new(compact::ModelSummarizer::new(Arc::new(Failing), "cheap")),
2382        );
2383        let req = rhema_core::ModelRequest {
2384            system: None,
2385            messages: long_history(30),
2386            tools: Vec::new(),
2387            params: rhema_core::ChatParams::new("m"),
2388        };
2389        let mut sink = NoopSink;
2390        // The main call went out with the extractive stand-ins, and
2391        // never waited on the worker: the failure is counted by the
2392        // background fill, after the response.
2393        view.complete(req, &mut sink).await.unwrap();
2394        {
2395            // The guard drops before the wait: no lock is held across
2396            // an await.
2397            let sent = recording.0.lock().unwrap();
2398            assert_eq!(sent.len(), 1);
2399        }
2400        wait_for(|| transcript.lock().unwrap().stats().summarizer_calls > 0).await;
2401        let mirror = transcript.lock().unwrap();
2402        assert_eq!(
2403            mirror.stats().summarizer_failures,
2404            mirror.stats().summarizer_calls
2405        );
2406        assert!(
2407            mirror
2408                .sections
2409                .iter()
2410                .all(|s| s.origin == SectionOrigin::Extractive)
2411        );
2412    }
2413
2414    /// A summarizer worker that answers only once its gate opens; it
2415    /// spins on yields, so an inline await of it would hang the
2416    /// current-thread runtime.
2417    struct Gated(Arc<AtomicBool>);
2418
2419    #[async_trait]
2420    impl ModelProvider for Gated {
2421        async fn complete(
2422            &self,
2423            _req: rhema_core::ModelRequest,
2424            _sink: &mut dyn EventSink,
2425        ) -> Result<ModelOutput, ProviderError> {
2426            while !self.0.load(Ordering::SeqCst) {
2427                tokio::task::yield_now().await;
2428            }
2429            Ok(ModelOutput {
2430                message: Message::text(Role::Assistant, "## Goals Met\n- late but dense"),
2431                stop_reason: rhema_core::StopReason::EndTurn,
2432                usage: Usage::default(),
2433            })
2434        }
2435    }
2436
2437    #[tokio::test]
2438    async fn a_slow_summarizer_never_delays_the_request() {
2439        let gate = Arc::new(AtomicBool::new(false));
2440        let recording = Arc::new(Recording(StdMutex::new(Vec::new())));
2441        let transcript = Arc::new(Mutex::new(Transcript::new(settings(20_000))));
2442        let view = TranscriptView::with_summarizer(
2443            recording.clone(),
2444            transcript.clone(),
2445            Arc::new(compact::ModelSummarizer::new(
2446                Arc::new(Gated(Arc::clone(&gate))),
2447                "cheap",
2448            )),
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 turn = tokio::spawn(async move {
2457            let mut sink = NoopSink;
2458            view.complete(req, &mut sink).await.unwrap();
2459        });
2460
2461        // The request goes out, and the turn finishes, while the worker
2462        // is still gated: the fill never sat in the request path.
2463        wait_for(|| !recording.0.lock().unwrap().is_empty()).await;
2464        wait_for(|| turn.is_finished()).await;
2465        assert!(
2466            !gate.load(Ordering::SeqCst),
2467            "the request waited on the gated worker"
2468        );
2469
2470        // Then the fill lands, and the section upgrades.
2471        gate.store(true, Ordering::SeqCst);
2472        wait_for(|| {
2473            transcript
2474                .lock()
2475                .unwrap()
2476                .sections
2477                .iter()
2478                .all(|s| s.origin == SectionOrigin::Model)
2479        })
2480        .await;
2481        let mirror = transcript.lock().unwrap();
2482        assert!(
2483            mirror
2484                .sections
2485                .iter()
2486                .all(|s| s.text.contains("late but dense")),
2487            "{:?}",
2488            mirror.sections
2489        );
2490    }
2491
2492    struct NoopSink;
2493
2494    impl EventSink for NoopSink {
2495        fn emit(&mut self, _event: rhema_core::Event<'_>) {}
2496    }
2497}