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