Skip to main content

rhema_transcript/
view.rs

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