Skip to main content

aither_agent/context/
compaction.rs

1//! Asynchronous compaction into a typed handoff document.
2//!
3//! Compaction used to be a stop-the-world event: the run halted, the model
4//! summarized its own transcript, and only then did work resume. That is the
5//! worst possible moment to spend a full request, because the window is
6//! already near its limit and the user is already waiting.
7//!
8//! Here it is forked instead. At a request boundary the window is snapshotted
9//! together with the sequence number of the next item — the *fork point* —
10//! and a handoff request goes out alongside the normal turns. The fork
11//! reproduces the main request's prefix byte for byte, so the provider serves
12//! it from the same cache the run just paid for. When the handoff lands, the
13//! next request boundary applies it: the conversation is replaced by the
14//! document, and every item numbered at or above the fork point is kept
15//! verbatim because the document cannot possibly describe it.
16//!
17//! The result is a *typed* document rather than prose, and the type is the
18//! embedder's: a [`HandoffSchema`] gives the schema the model fills, the
19//! instruction that asks for it, and the text it renders back into the
20//! conversation. aither reads from it only what restoration needs, the
21//! [`Restoration`]. [`HandoffDocument`] is the schema aither ships.
22//!
23//! Structured output is tried first; a model that ignores the schema gets
24//! exactly one corrective retry quoting its own failure, and then the
25//! compaction is reported as failed instead of silently storing something
26//! unusable.
27
28use std::future::Future;
29use std::marker::PhantomData;
30use std::pin::Pin;
31
32use aither_core::llm::{Classify, Event, Failure, LLMRequest, Message, Role};
33use aither_core::{LanguageModel, llm::GenerateError};
34use askama::Template;
35use futures_lite::StreamExt as _;
36use schemars::JsonSchema;
37use serde::de::DeserializeOwned;
38use serde::{Deserialize, Serialize};
39use sync_wrapper::SyncWrapper;
40
41/// A handoff document type a compaction asks the model to fill.
42///
43/// The type's JSON schema is the structured output the compaction requests,
44/// so its fields are what the model writes. The rest is what the embedder
45/// decides about its handoff: the instruction that asks for it, the
46/// corrective prompt after an unusable answer, what makes a document
47/// unusable, and the text the conversation reads in place of everything the
48/// handoff replaced.
49///
50/// aither needs only the [`Restoration`] from it — the file ranges and
51/// skills to put back in view — and builds the index of on-disk materials
52/// itself, passing it to [`render`](Self::render).
53pub trait HandoffSchema: JsonSchema + DeserializeOwned + Send + 'static {
54    /// The instruction appended to the conversation to ask for this
55    /// document.
56    fn instruction(prompt: &HandoffPrompt<'_>) -> String;
57
58    /// The corrective prompt sent once after a response that did not parse
59    /// or validate; `reason` says what was wrong with it.
60    fn retry(reason: &str) -> String;
61
62    /// Checks a parsed document before it is accepted.
63    ///
64    /// # Errors
65    ///
66    /// Returns [`InvalidHandoff`] when the document is unusable; its reason
67    /// is quoted to the model in the retry.
68    fn validate(&self) -> Result<(), InvalidHandoff> {
69        Ok(())
70    }
71
72    /// Renders the document as the text the conversation reads from now on.
73    ///
74    /// `file_index` is the mechanical index of on-disk materials the
75    /// compacted conversation produced (`path — description` entries); the
76    /// model does not write it, because a missing entry means redone work.
77    fn render(&self, file_index: &[String]) -> String;
78
79    /// Takes out what restoration puts back in view.
80    fn into_restoration(self) -> Restoration;
81}
82
83/// What the instruction of a compaction is rendered from.
84#[derive(Debug, Clone, Copy)]
85pub struct HandoffPrompt<'a> {
86    /// What the handoff should focus on, when a caller said; trimmed and
87    /// never empty.
88    pub focus: Option<&'a str>,
89    /// The session's skills the handoff may name for restoration.
90    pub skills: &'a [SkillCatalogEntry],
91    /// The attachments of the user messages below the fork the handoff may
92    /// name to keep.
93    pub attachments: &'a [AttachmentCatalogEntry],
94}
95
96/// What a handoff asks to be put back in view after compaction.
97#[derive(Debug, Clone, Default, PartialEq, Eq)]
98pub struct Restoration {
99    /// File ranges restored verbatim, in order.
100    pub context_files: Vec<ContextFile>,
101    /// Names of catalog skills whose instructions are restored; a name not
102    /// in the catalog is reported instead.
103    pub skills: Vec<String>,
104    /// Ids of catalog attachments kept in their user messages; an id not
105    /// in the catalog is reported instead.
106    pub attachments: Vec<String>,
107}
108
109/// Why a parsed handoff document is unusable.
110#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
111#[error("{reason}")]
112pub struct InvalidHandoff {
113    /// What is wrong with the document, as the retry quotes it.
114    pub reason: String,
115}
116
117impl InvalidHandoff {
118    /// An invalid handoff for `reason`.
119    pub fn new(reason: impl Into<String>) -> Self {
120        Self {
121            reason: reason.into(),
122        }
123    }
124}
125
126impl From<InvalidHandoff> for CompactionError {
127    fn from(error: InvalidHandoff) -> Self {
128        Self::Invalid {
129            reason: error.reason,
130        }
131    }
132}
133
134/// The handoff schema aither ships: the task, decisions, errors, pending
135/// work and recovery hints, plus the files and skills to restore.
136#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
137pub struct HandoffDocument {
138    /// What the user asked for, and how far it has got.
139    pub current_task: String,
140    /// Decisions, constraints and patterns that must survive.
141    pub key_decisions: Vec<String>,
142    /// File ranges the next turns need in view, restored verbatim on apply.
143    #[serde(default)]
144    pub context_files: Vec<ContextFile>,
145    /// Errors encountered and how they were resolved.
146    pub errors_fixes: Vec<String>,
147    /// Remaining work, in order, starting with the next action.
148    pub pending_work: Vec<String>,
149    /// Where the rest of the state can be recovered from.
150    pub recovery_hints: Vec<String>,
151    /// Session skills whose instructions the next turns need in view,
152    /// chosen from the catalog the instruction lists.
153    #[serde(default)]
154    pub skills: Vec<String>,
155    /// Attachments of user messages the next turns must see again, by
156    /// their id in the catalog the instruction lists; every other
157    /// attachment below the fork is stripped on apply.
158    #[serde(default)]
159    pub attachments: Vec<KeptAttachment>,
160}
161
162/// A file range the next turns need in view, named by the handoff.
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
164pub struct ContextFile {
165    /// Path to the file, as it appears on disk.
166    pub path: String,
167    /// The 1-based inclusive line range to restore; absent restores the
168    /// whole file.
169    pub lines: Option<LineRange>,
170    /// Why the next turns need this file in view.
171    pub why: String,
172}
173
174/// An attachment the next turns must see again, named by the id the
175/// instruction's catalog gave it.
176#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
177pub struct KeptAttachment {
178    /// The attachment's id in the catalog the instruction listed.
179    pub id: String,
180    /// What in it the remaining work must match or inspect.
181    pub why: String,
182}
183
184/// A 1-based inclusive line range inside a file.
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
186pub struct LineRange {
187    /// First line to restore.
188    pub start: u32,
189    /// Last line to restore.
190    pub end: u32,
191}
192
193/// A skill the handoff may name for restoration.
194///
195/// The session's skill catalog is offered to the summarising model so it can
196/// name skills by their registry name; on apply, only names found in the
197/// catalog are restored, and the rest are reported.
198#[derive(Debug, Clone, PartialEq, Eq)]
199pub struct SkillCatalogEntry {
200    /// The name the handoff names.
201    pub name: String,
202    /// What the skill is for, shown in the compaction prompt.
203    pub description: String,
204    /// The text restored into `<restored_context>`.
205    pub instructions: String,
206}
207
208/// A catalog attachment's place in the window.
209///
210/// The sequence number identifies the user message carrying it; the index
211/// its position in that message's attachments.
212#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
213pub struct AttachmentRef {
214    /// Sequence number of the user message carrying the attachment.
215    pub seq: u64,
216    /// Index of the attachment within that message.
217    pub index: usize,
218}
219
220/// An attachment of a user message below the fork, offered to the
221/// compaction model so the handoff can name it to be kept.
222///
223/// The catalog is built when the fork is taken and the instruction renders
224/// exactly it, so on apply a named id resolves against what the model saw
225/// and the attachment stays in the message it came with.
226#[derive(Debug, Clone, PartialEq, Eq)]
227pub struct AttachmentCatalogEntry {
228    /// The id the handoff names, `attachment-N` in conversation order.
229    pub id: String,
230    /// The attachment's media type.
231    pub media_type: String,
232    /// The beginning of the user message the attachment came with, empty
233    /// when the message has no text.
234    pub excerpt: String,
235    /// Where the attachment sits in the window.
236    pub reference: AttachmentRef,
237}
238
239#[derive(Template)]
240#[template(path = "handoff_document.md", escape = "none")]
241struct HandoffDocumentTemplate<'a> {
242    handoff: &'a HandoffDocument,
243    file_index: &'a [String],
244}
245
246#[derive(Template)]
247#[template(path = "compaction_instruction.txt", escape = "none")]
248struct CompactionInstruction<'a> {
249    focus: Option<&'a str>,
250    skills: &'a [SkillCatalogEntry],
251    attachments: &'a [AttachmentCatalogEntry],
252}
253
254#[derive(Template)]
255#[template(path = "compaction_retry.txt", escape = "none")]
256struct CompactionRetry<'a> {
257    reason: &'a str,
258}
259
260impl HandoffSchema for HandoffDocument {
261    /// Asks for every field, offering the skill catalog by name.
262    ///
263    /// # Panics
264    ///
265    /// Panics if the bundled instruction template cannot be rendered, which
266    /// is a build-time error in the template rather than a runtime condition.
267    fn instruction(prompt: &HandoffPrompt<'_>) -> String {
268        CompactionInstruction {
269            focus: prompt.focus,
270            skills: prompt.skills,
271            attachments: prompt.attachments,
272        }
273        .render()
274        .expect("compaction instruction template must render")
275    }
276
277    /// Quotes `reason` and restates the keys.
278    ///
279    /// # Panics
280    ///
281    /// Panics if the bundled retry template cannot be rendered.
282    fn retry(reason: &str) -> String {
283        CompactionRetry { reason }
284            .render()
285            .expect("compaction retry template must render")
286    }
287
288    /// Rejects an empty `current_task`: a handoff without it tells the next
289    /// instance nothing about what it is supposed to be doing, and is worse
290    /// than no handoff at all.
291    fn validate(&self) -> Result<(), InvalidHandoff> {
292        if self.current_task.trim().is_empty() {
293            return Err(InvalidHandoff::new("current_task must not be empty"));
294        }
295        Ok(())
296    }
297
298    /// Renders the document as Markdown, one section per field.
299    ///
300    /// # Panics
301    ///
302    /// Panics if the bundled handoff template cannot be rendered.
303    fn render(&self, file_index: &[String]) -> String {
304        HandoffDocumentTemplate {
305            handoff: self,
306            file_index,
307        }
308        .render()
309        .expect("handoff document template must render")
310    }
311
312    fn into_restoration(self) -> Restoration {
313        Restoration {
314            context_files: self.context_files,
315            skills: self.skills,
316            attachments: self.attachments.into_iter().map(|kept| kept.id).collect(),
317        }
318    }
319}
320
321/// Why a compaction could not produce a usable handoff document.
322#[derive(Debug, Clone, thiserror::Error)]
323pub enum CompactionError {
324    /// The provider failed before producing a response.
325    #[error("compaction request failed: {message}")]
326    Provider {
327        /// The provider's error message.
328        message: String,
329        /// How the provider error classifies.
330        failure: Failure,
331    },
332
333    /// The model answered, but not with a usable handoff document.
334    #[error("compaction produced an invalid handoff document: {reason}")]
335    Invalid {
336        /// What was wrong with the document.
337        reason: String,
338    },
339
340    /// There was nothing to compact.
341    #[error("compaction found no conversation to summarize")]
342    Empty,
343}
344
345/// Joins an index entry's path to its description.
346const INDEX_SEPARATOR: &str = " — ";
347
348/// The handoff a [`Context`](crate::context::Context) carries between
349/// compactions: the text the conversation reads in place of what it
350/// replaced, and the file index the next compaction extends.
351#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
352pub struct Handoff {
353    /// The rendered handoff, as the conversation reads it.
354    text: String,
355    /// The mechanical index of on-disk materials, carried into the next
356    /// compaction so a file indexed once stays indexed.
357    file_index: Vec<String>,
358}
359
360impl Handoff {
361    /// A handoff of plain `text`, with no file index.
362    #[must_use]
363    pub fn new(text: impl Into<String>) -> Self {
364        Self {
365            text: text.into(),
366            file_index: Vec::new(),
367        }
368    }
369
370    /// A handoff of `text` that carries `file_index`.
371    #[must_use]
372    pub const fn with_file_index(text: String, file_index: Vec<String>) -> Self {
373        Self { text, file_index }
374    }
375
376    /// The handoff text, as the conversation reads it.
377    #[must_use]
378    pub fn text(&self) -> &str {
379        &self.text
380    }
381
382    /// The file index entries this handoff carries.
383    #[must_use]
384    pub fn file_index(&self) -> &[String] {
385        &self.file_index
386    }
387}
388
389/// Finds the files a tool result names, for the handoff's file index.
390///
391/// What counts as a file the model may want restored after a compaction is
392/// the embedder's decision: aither knows nothing of the paths its tools
393/// print. An agent built without one indexes nothing.
394pub trait FileReferences: Send + Sync + 'static {
395    /// The files `output`, one tool result, names: paths or URLs the
396    /// restoration can read back.
397    fn files(&self, output: &str) -> Vec<String>;
398}
399
400/// A shared [`FileReferences`], carried by the agent and its compactions.
401#[derive(Clone)]
402pub struct AnyFileReferences(std::sync::Arc<dyn FileReferences>);
403
404impl AnyFileReferences {
405    /// Shares `references`.
406    #[must_use]
407    pub fn new(references: impl FileReferences) -> Self {
408        Self(std::sync::Arc::new(references))
409    }
410}
411
412impl std::fmt::Debug for AnyFileReferences {
413    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
414        formatter.debug_struct("AnyFileReferences").finish()
415    }
416}
417
418/// Builds the mechanical file index for a handoff from conversation messages.
419///
420/// Asks `references` for the files each tool result names and pairs each with
421/// the description of the tool call that produced it. `previous` is the file
422/// index of the handoff being replaced: its entries are kept, so a file
423/// indexed by an earlier compaction stays indexed. Later mentions of the same
424/// path win.
425#[must_use]
426pub fn build_file_index(
427    previous: &[String],
428    messages: &[Message],
429    references: Option<&AnyFileReferences>,
430) -> Vec<String> {
431    use std::collections::HashMap;
432
433    let mut call_description: HashMap<&str, &str> = HashMap::new();
434    for message in messages {
435        for call in message.tool_calls() {
436            if let Some(description) = call.arguments.get("description").and_then(|v| v.as_str()) {
437                call_description.insert(call.id.as_str(), description);
438            }
439        }
440    }
441
442    let mut index: indexmap::IndexMap<String, Option<String>> = indexmap::IndexMap::new();
443    for entry in previous {
444        match entry.split_once(INDEX_SEPARATOR) {
445            Some((path, description)) => {
446                index.insert(path.to_string(), Some(description.to_string()));
447            }
448            None => {
449                index.insert(entry.clone(), None);
450            }
451        }
452    }
453    for message in messages {
454        let Message::Tool {
455            content,
456            tool_call_id,
457        } = message
458        else {
459            continue;
460        };
461        let description = call_description
462            .get(tool_call_id.as_str())
463            .map(|description| (*description).to_string());
464        for file in references.iter().flat_map(|found| found.0.files(content)) {
465            index.insert(file, description.clone());
466        }
467    }
468
469    index
470        .into_iter()
471        .map(|(path, description)| match description {
472            Some(description) => format!("{path}{INDEX_SEPARATOR}{description}"),
473            None => path,
474        })
475        .collect()
476}
477
478/// A compaction snapshot taken at a request boundary, asking for a `D`.
479pub struct CompactionFork<D> {
480    /// Sequence number of the first item the handoff will *not* describe.
481    fork_point: u64,
482    /// The file index of the handoff this compaction replaces.
483    previous_file_index: Vec<String>,
484    /// Finds the files the conversation's tool results name, for the file
485    /// index.
486    references: Option<AnyFileReferences>,
487    /// The attachment catalog the instruction renders, carried to the
488    /// completed compaction so apply resolves the handoff's names against
489    /// exactly what the model saw.
490    attachment_catalog: Vec<AttachmentCatalogEntry>,
491    /// The main request, source blocks, tools and cache parameters included,
492    /// with the handoff instruction appended to its messages. Replaying it is
493    /// what lets the provider serve the compaction from the same prefix
494    /// cache the run just paid for.
495    request: LLMRequest,
496    /// The schema the model fills; no `D` is held.
497    schema: PhantomData<fn() -> D>,
498}
499
500impl<D> std::fmt::Debug for CompactionFork<D> {
501    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
502        formatter
503            .debug_struct("CompactionFork")
504            .field("fork_point", &self.fork_point)
505            .field("schema", &std::any::type_name::<D>())
506            .finish_non_exhaustive()
507    }
508}
509
510impl<D: HandoffSchema> CompactionFork<D> {
511    /// Forks `request` — the exact request the run is about to send — into a
512    /// compaction request for a `D`, optionally focused by `focus`.
513    /// `previous_file_index` is the file index of the handoff the result
514    /// will replace, and `attachments` the catalog of attachments the user
515    /// messages below `fork_point` carry, which the instruction offers for
516    /// the handoff to name.
517    ///
518    /// The instruction [`D::instruction`](HandoffSchema::instruction)
519    /// renders is *appended* and the tool definitions and parameters are
520    /// reused untouched: everything up to the instruction is byte-for-byte
521    /// what the main request sent, so the provider's prefix cache still
522    /// applies.
523    ///
524    /// # Errors
525    ///
526    /// Returns [`CompactionError::Empty`] when the request carries no
527    /// conversation to summarize.
528    pub fn new(
529        request: &LLMRequest,
530        fork_point: u64,
531        previous_file_index: &[String],
532        focus: Option<&str>,
533        skills: &[SkillCatalogEntry],
534        attachments: &[AttachmentCatalogEntry],
535    ) -> Result<Self, CompactionError> {
536        if request
537            .messages()
538            .iter()
539            .all(|message| message.role() == Role::System)
540        {
541            return Err(CompactionError::Empty);
542        }
543        let focus = focus.map(str::trim).filter(|focus| !focus.is_empty());
544        let instruction = D::instruction(&HandoffPrompt {
545            focus,
546            skills,
547            attachments,
548        });
549        let mut messages = request.messages().to_vec();
550        messages.push(Message::user(instruction));
551        Ok(Self {
552            fork_point,
553            previous_file_index: previous_file_index.to_vec(),
554            references: None,
555            attachment_catalog: attachments.to_vec(),
556            request: LLMRequest::new(messages)
557                .with_parameters(request.parameters().clone())
558                .with_tool_definitions(request.tool_definitions().to_vec()),
559            schema: PhantomData,
560        })
561    }
562
563    /// Sets how the file index finds the files the conversation's tool
564    /// results name.
565    #[must_use]
566    pub fn with_file_references(mut self, references: Option<AnyFileReferences>) -> Self {
567        self.references = references;
568        self
569    }
570
571    /// The sequence number items must reach to survive this compaction.
572    #[must_use]
573    pub const fn fork_point(&self) -> u64 {
574        self.fork_point
575    }
576
577    /// The request the fork replays, instruction included.
578    #[must_use]
579    pub const fn request(&self) -> &LLMRequest {
580        &self.request
581    }
582
583    /// Runs the compaction against `model`.
584    ///
585    /// Structured output is attempted first. A schema mismatch — the common
586    /// failure for models without native structured output — or a document
587    /// [`D::validate`](HandoffSchema::validate) rejects earns one corrective
588    /// retry, [`D::retry`](HandoffSchema::retry), that quotes the failure
589    /// back to the model. The accepted document is rendered with the file
590    /// index and split into the handoff and its restoration.
591    ///
592    /// # Errors
593    ///
594    /// Returns [`CompactionError`] when the provider fails, or when the
595    /// retry also fails to produce a valid document.
596    pub async fn run<M: LanguageModel>(
597        self,
598        model: M,
599    ) -> Result<CompletedCompaction, CompactionError> {
600        let Self {
601            fork_point,
602            request,
603            previous_file_index,
604            references,
605            attachment_catalog,
606            ..
607        } = self;
608        let file_index = build_file_index(
609            &previous_file_index,
610            request.messages(),
611            references.as_ref(),
612        );
613        let reason = match model.generate::<D>(request.clone()).await {
614            Ok(document) => match document.validate() {
615                Ok(()) => {
616                    return Ok(CompletedCompaction::new(
617                        fork_point,
618                        document,
619                        file_index,
620                        attachment_catalog,
621                    ));
622                }
623                Err(error) => error.reason,
624            },
625            Err(GenerateError::Provider(error)) => {
626                return Err(CompactionError::Provider {
627                    message: error.to_string(),
628                    failure: error.failure(),
629                });
630            }
631            Err(error @ GenerateError::Parse { .. }) => error.to_string(),
632        };
633
634        tracing::warn!(reason = %reason, "retrying compaction with a corrective prompt");
635        let (mut messages, parameters, definitions) = request.into_parts();
636        messages.push(Message::user(D::retry(&reason)));
637        let retry_request = LLMRequest::new(messages)
638            .with_parameters(parameters)
639            .with_tool_definitions(definitions);
640        let response = collect_text(&model, retry_request).await?;
641        let document = parse_handoff::<D>(&response)?;
642        document.validate()?;
643        Ok(CompletedCompaction::new(
644            fork_point,
645            document,
646            file_index,
647            attachment_catalog,
648        ))
649    }
650}
651
652impl CompletedCompaction {
653    /// Splits an accepted `document` into the handoff it renders to, with
654    /// `file_index`, and its restoration; `attachment_catalog` is the
655    /// catalog the instruction offered the document's attachments against.
656    pub(crate) fn new<D: HandoffSchema>(
657        fork_point: u64,
658        document: D,
659        file_index: Vec<String>,
660        attachment_catalog: Vec<AttachmentCatalogEntry>,
661    ) -> Self {
662        let text = document.render(&file_index);
663        Self {
664            fork_point,
665            handoff: Handoff::with_file_index(text, file_index),
666            restoration: document.into_restoration(),
667            attachment_catalog,
668        }
669    }
670}
671
672/// A compaction that has landed but not yet been folded into the window.
673///
674/// The handoff is applied at the next request boundary rather than the moment
675/// it arrives: mid-turn the conversation holds tool calls whose results have
676/// not been appended yet, and replacing it there would strand them.
677#[derive(Debug, Clone, PartialEq, Eq)]
678pub struct CompletedCompaction {
679    /// Sequence number items must reach to survive the handoff.
680    pub fork_point: u64,
681    /// The handoff that replaces everything older than the fork point.
682    pub handoff: Handoff,
683    /// What the handoff asked to put back in view.
684    pub restoration: Restoration,
685    /// The attachment catalog the instruction offered, so the ids the
686    /// handoff named resolve against what the model saw.
687    pub attachment_catalog: Vec<AttachmentCatalogEntry>,
688}
689
690/// The owned, `'static` future a forked compaction runs as.
691type CompactionFuture =
692    Pin<Box<dyn Future<Output = Result<CompletedCompaction, CompactionError>> + Send>>;
693
694/// A compaction that is in flight while the run continues.
695///
696/// The future is owned and `'static`, which is what lets it be carried across
697/// turn boundaries and polled next to the model stream without an executor:
698/// the agent races the two with [`futures_lite::future::or`] and keeps
699/// whichever finishes.
700pub struct PendingCompaction {
701    fork_point: u64,
702    /// The compaction in flight.
703    ///
704    /// A future built from provider futures is `Send` but says nothing about
705    /// `Sync`, and the agent that owns this has to stay `Sync` to live inside
706    /// a tool. [`SyncWrapper`] grants exactly that: `Sync` in exchange for
707    /// `&mut`-only access, which is all polling ever needs.
708    future: SyncWrapper<CompactionFuture>,
709}
710
711impl std::fmt::Debug for PendingCompaction {
712    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
713        formatter
714            .debug_struct("PendingCompaction")
715            .field("fork_point", &self.fork_point)
716            .finish_non_exhaustive()
717    }
718}
719
720impl PendingCompaction {
721    /// Starts `fork` against an owned `model`.
722    #[must_use]
723    pub fn start<D: HandoffSchema, M: LanguageModel + 'static>(
724        fork: CompactionFork<D>,
725        model: M,
726    ) -> Self {
727        let fork_point = fork.fork_point();
728        Self {
729            fork_point,
730            future: SyncWrapper::new(Box::pin(fork.run(model))),
731        }
732    }
733
734    /// The sequence number items must reach to survive this compaction.
735    #[must_use]
736    pub const fn fork_point(&self) -> u64 {
737        self.fork_point
738    }
739
740    /// Awaits the completed compaction.
741    pub fn wait(
742        &mut self,
743    ) -> impl Future<Output = Result<CompletedCompaction, CompactionError>> + '_ {
744        self.future.get_mut()
745    }
746}
747
748/// Parses a handoff document from a raw model response.
749///
750/// Models wrap JSON in prose and code fences no matter what the prompt says,
751/// so the outermost braces are located rather than trusting the whole body.
752fn parse_handoff<D: DeserializeOwned>(response: &str) -> Result<D, CompactionError> {
753    let trimmed = response.trim();
754    if trimmed.is_empty() {
755        return Err(CompactionError::Invalid {
756            reason: "the model returned an empty response".to_string(),
757        });
758    }
759    let json = match (trimmed.find('{'), trimmed.rfind('}')) {
760        (Some(start), Some(end)) if end > start => &trimmed[start..=end],
761        _ => trimmed,
762    };
763    serde_json::from_str(json).map_err(|error| CompactionError::Invalid {
764        reason: error.to_string(),
765    })
766}
767
768/// Collects the text of a non-streaming completion.
769async fn collect_text<M: LanguageModel>(
770    model: &M,
771    request: LLMRequest,
772) -> Result<String, CompactionError> {
773    let stream = model.respond(request);
774    futures_lite::pin!(stream);
775    let mut text = String::new();
776    while let Some(event) = stream.next().await {
777        match event {
778            Ok(Event::Text(chunk)) => text.push_str(&chunk),
779            Ok(_) => {}
780            Err(error) => {
781                return Err(CompactionError::Provider {
782                    message: error.to_string(),
783                    failure: error.failure(),
784                });
785            }
786        }
787    }
788    Ok(text)
789}
790
791#[cfg(test)]
792mod tests {
793    use super::*;
794    use aither_core::llm::ToolCall;
795
796    /// Names every word that is a path under `outputs/` or `artifacts/`.
797    struct UnderDirectories;
798
799    impl FileReferences for UnderDirectories {
800        fn files(&self, output: &str) -> Vec<String> {
801            output
802                .split_whitespace()
803                .filter(|word| word.starts_with("outputs/") || word.starts_with("artifacts/"))
804                .map(str::to_string)
805                .collect()
806        }
807    }
808
809    fn references() -> AnyFileReferences {
810        AnyFileReferences::new(UnderDirectories)
811    }
812
813    #[test]
814    fn build_file_index_pairs_outputs_with_call_descriptions() {
815        let messages = vec![
816            Message::assistant_with_tool_calls(
817                "",
818                vec![ToolCall::new(
819                    "call_1",
820                    "terminal",
821                    serde_json::json!({
822                        "description": "Fetch WebGPU status pages",
823                        "script": "webfetch https://caniuse.com"
824                    }),
825                )],
826            ),
827            Message::tool(
828                "call_1",
829                "Output saved to outputs/river.txt (100 lines, 5000 bytes)",
830            ),
831            Message::assistant_with_tool_calls(
832                "",
833                vec![ToolCall::new(
834                    "call_2",
835                    "terminal",
836                    serde_json::json!({"description": "Write deck", "script": "tee artifacts/slides.md"}),
837                )],
838            ),
839            Message::tool("call_2", "wrote artifacts/slides.md"),
840        ];
841
842        let index = build_file_index(&[], &messages, Some(&references()));
843        assert_eq!(index.len(), 2);
844        assert!(
845            index[0].contains("outputs/river.txt")
846                && index[0].contains("Fetch WebGPU status pages"),
847            "index entry should pair path with description: {index:?}"
848        );
849        assert!(index[1].contains("artifacts/slides.md") && index[1].contains("Write deck"));
850    }
851
852    #[test]
853    fn build_file_index_keeps_latest_description_per_path() {
854        let messages = vec![
855            Message::assistant_with_tool_calls(
856                "",
857                vec![ToolCall::new(
858                    "call_1",
859                    "terminal",
860                    serde_json::json!({"description": "first pass"}),
861                )],
862            ),
863            Message::tool("call_1", "see artifacts/report.md"),
864            Message::assistant_with_tool_calls(
865                "",
866                vec![ToolCall::new(
867                    "call_2",
868                    "terminal",
869                    serde_json::json!({"description": "final revision"}),
870                )],
871            ),
872            Message::tool("call_2", "updated artifacts/report.md"),
873        ];
874
875        let index = build_file_index(&[], &messages, Some(&references()));
876        assert_eq!(index.len(), 1);
877        assert!(index[0].contains("final revision"));
878    }
879
880    fn read_file_messages(id: &str, description: &str, path: &str) -> Vec<Message> {
881        vec![
882            Message::assistant_with_tool_calls(
883                "",
884                vec![ToolCall::new(
885                    id,
886                    "terminal",
887                    serde_json::json!({"description": description}),
888                )],
889            ),
890            Message::tool(id, format!("saved {path}")),
891        ]
892    }
893
894    /// Compacts `context` the way a run does: indexes the conversation seeded
895    /// with the current handoff's index, then folds the result into the window.
896    fn compact(context: &mut crate::context::Context) -> Vec<String> {
897        let file_index = build_file_index(
898            context.handoff_file_index(),
899            &context.build_request(&[]),
900            Some(&references()),
901        );
902        context.apply_handoff(
903            Handoff::with_file_index("task".to_string(), file_index.clone()),
904            u64::MAX,
905            0,
906            &std::collections::HashSet::new(),
907        );
908        file_index
909    }
910
911    #[test]
912    fn the_second_handoff_keeps_files_indexed_by_the_first() {
913        let mut context = crate::context::Context::new();
914        for message in read_file_messages("call_1", "Fetch notes", "artifacts/notes.md") {
915            context.push(message);
916        }
917        let first = compact(&mut context);
918        assert_eq!(first, ["artifacts/notes.md — Fetch notes"]);
919
920        for message in read_file_messages("call_2", "Write deck", "artifacts/slides.md") {
921            context.push(message);
922        }
923        let second = compact(&mut context);
924        assert_eq!(
925            second,
926            [
927                "artifacts/notes.md — Fetch notes",
928                "artifacts/slides.md — Write deck"
929            ]
930        );
931
932        for message in read_file_messages("call_3", "Revised notes", "artifacts/notes.md") {
933            context.push(message);
934        }
935        let third = compact(&mut context);
936        assert_eq!(
937            third,
938            [
939                "artifacts/notes.md — Revised notes",
940                "artifacts/slides.md — Write deck"
941            ]
942        );
943    }
944
945    #[test]
946    fn handoff_markdown_renders_file_index_section() {
947        let handoff = HandoffDocument {
948            current_task: "task".to_string(),
949            ..HandoffDocument::default()
950        };
951        let markdown = handoff.render(&["outputs/a-b-c-d.txt — research notes".to_string()]);
952        assert!(markdown.contains("Materials Already On Disk"));
953        assert!(markdown.contains("outputs/a-b-c-d.txt — research notes"));
954        assert!(markdown.contains("Read the file instead of redoing the work"));
955    }
956
957    #[test]
958    fn a_handoff_without_a_current_task_is_rejected() {
959        let error = HandoffDocument::default()
960            .validate()
961            .expect_err("empty current_task must not validate");
962        assert!(error.reason.contains("current_task"));
963    }
964
965    /// A PNG screenshot the way a host attaches one to a user message.
966    fn screenshot(name: &str) -> aither_core::llm::Attachment {
967        aither_core::llm::Attachment::new(
968            format!("https://files.example.com/{name}.png")
969                .parse()
970                .expect("url"),
971            "image/png".parse().expect("media type"),
972        )
973    }
974
975    /// The instruction offers the catalog the window built: each entry's
976    /// id, media type and the excerpt of its message, cut to a character
977    /// boundary on Chinese, Japanese and Korean text.
978    #[test]
979    fn the_instruction_renders_the_attachment_catalog() {
980        let mut context = crate::context::Context::new();
981        let cjk = "把这张截图里的页眉配色套用到报表页,このスクリーンショットのヘッダー配色をレポートページに適用して,이 스크린샷의 헤더 색상을 보고서 페이지에 적용해 주세요";
982        context.push(Message::user(cjk).with_attachment(screenshot("header-colors")));
983        context.push(Message::user("").with_attachment(screenshot("bare")));
984        let catalog = context.attachment_catalog(context.fork_point());
985
986        let instruction = HandoffDocument::instruction(&HandoffPrompt {
987            focus: None,
988            skills: &[],
989            attachments: &catalog,
990        });
991
992        assert!(instruction.contains("`attachments`: {`id`: string, `why`: string}[]"));
993        assert!(
994            instruction.contains("`attachment-1`: image/png, sent with the user message beginning"),
995            "{instruction}"
996        );
997        let excerpt = catalog[0].excerpt.clone();
998        assert!(excerpt.chars().count() <= 80 && excerpt.starts_with('把'));
999        assert!(instruction.contains(&format!("\"{excerpt}\"")));
1000        assert!(
1001            instruction
1002                .contains("`attachment-2`: image/png, sent with a user message that has no text"),
1003            "{instruction}"
1004        );
1005    }
1006
1007    #[test]
1008    fn the_instruction_marks_an_empty_attachment_catalog() {
1009        let instruction = HandoffDocument::instruction(&HandoffPrompt {
1010            focus: None,
1011            skills: &[],
1012            attachments: &[],
1013        });
1014
1015        assert!(
1016            instruction.contains("(the conversation has no attachments; leave the list empty)")
1017        );
1018    }
1019
1020    #[test]
1021    fn a_stored_handoff_without_attachments_still_deserializes() {
1022        let json = r#"{"current_task":"restyle the header","key_decisions":[],"context_files":[],"errors_fixes":[],"pending_work":["update the palette"],"recovery_hints":[],"skills":[]}"#;
1023        let document: HandoffDocument = serde_json::from_str(json).expect("stored handoff parses");
1024        assert_eq!(document.attachments, Vec::new());
1025    }
1026
1027    #[test]
1028    fn handoff_markdown_renders_the_attachments_section() {
1029        let handoff = HandoffDocument {
1030            current_task: "restyle the header".to_string(),
1031            attachments: vec![KeptAttachment {
1032                id: "attachment-2".to_string(),
1033                why: "the palette the header must match".to_string(),
1034            }],
1035            ..HandoffDocument::default()
1036        };
1037
1038        let markdown = handoff.render(&[]);
1039        assert!(markdown.contains("## Attachments"));
1040        assert!(markdown.contains("- the palette the header must match"));
1041        assert!(
1042            !markdown.contains("attachment-2"),
1043            "the catalog id means nothing after apply"
1044        );
1045
1046        let markdown = HandoffDocument {
1047            current_task: "restyle the header".to_string(),
1048            ..HandoffDocument::default()
1049        }
1050        .render(&[]);
1051        assert!(
1052            !markdown.contains("## Attachments"),
1053            "the section is omitted when the handoff names none"
1054        );
1055    }
1056
1057    #[test]
1058    fn handoff_parsing_tolerates_fences_and_commentary() {
1059        let response = "Sure! Here you go:\n```json\n{\"current_task\": \"ship it\", \
1060            \"key_decisions\": [], \"files_paths\": [], \"errors_fixes\": [], \
1061            \"pending_work\": [], \"recovery_hints\": []}\n```\nHope that helps.";
1062        let document = parse_handoff::<HandoffDocument>(response).expect("handoff parses");
1063        assert_eq!(document.current_task, "ship it");
1064    }
1065
1066    #[test]
1067    fn empty_responses_are_reported_as_invalid() {
1068        let error =
1069            parse_handoff::<HandoffDocument>("   ").expect_err("empty response must not parse");
1070        assert!(matches!(error, CompactionError::Invalid { .. }));
1071    }
1072
1073    #[test]
1074    fn forking_an_empty_context_is_an_error() {
1075        let request = LLMRequest::new(vec![Message::system("only the prefix")]);
1076        assert!(matches!(
1077            CompactionFork::<HandoffDocument>::new(&request, 0, &[], None, &[], &[]),
1078            Err(CompactionError::Empty)
1079        ));
1080    }
1081
1082    #[test]
1083    fn the_fork_reproduces_the_main_request_and_appends_the_instruction() {
1084        use aither_core::llm::model::Parameters;
1085
1086        let parameters = Parameters {
1087            temperature: Some(0.3),
1088            ..Parameters::default()
1089        };
1090        let main = LLMRequest::new(vec![
1091            Message::system("be useful"),
1092            Message::system("<tool-outputs>tail block</tool-outputs>"),
1093            Message::user("do the thing"),
1094        ])
1095        .with_parameters(parameters);
1096
1097        let skills = [SkillCatalogEntry {
1098            name: "pdf".to_string(),
1099            description: "read PDFs".to_string(),
1100            instructions: "how to read PDFs".to_string(),
1101        }];
1102        let fork = CompactionFork::<HandoffDocument>::new(
1103            &main,
1104            7,
1105            &[],
1106            Some("the failing test"),
1107            &skills,
1108            &[],
1109        )
1110        .expect("fork");
1111
1112        assert_eq!(fork.fork_point(), 7);
1113        assert_eq!(
1114            fork.request().parameters().temperature,
1115            main.parameters().temperature,
1116            "the compaction request reuses the main parameters"
1117        );
1118        assert_eq!(
1119            fork.request().tool_definitions().len(),
1120            main.tool_definitions().len(),
1121            "the compaction request carries the same tools"
1122        );
1123        assert_eq!(fork.request().messages().len(), main.messages().len() + 1);
1124        for (index, message) in main.messages().iter().enumerate() {
1125            assert_eq!(
1126                message.content(),
1127                fork.request().messages()[index].content(),
1128                "fork perturbed prefix message {index}"
1129            );
1130        }
1131        let instruction = fork
1132            .request()
1133            .messages()
1134            .last()
1135            .expect("instruction")
1136            .content();
1137        assert!(instruction.contains("Focus the handoff on: the failing test"));
1138        assert!(instruction.contains("pdf"), "the skill catalog is offered");
1139    }
1140
1141    #[derive(Debug)]
1142    struct NoError;
1143
1144    impl std::fmt::Display for NoError {
1145        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1146            f.write_str("never fails")
1147        }
1148    }
1149
1150    impl std::error::Error for NoError {}
1151
1152    impl aither_core::llm::Classify for NoError {
1153        fn failure(&self) -> aither_core::llm::Failure {
1154            aither_core::llm::Failure::permanent()
1155        }
1156    }
1157
1158    /// Answers every request with a handoff and records it.
1159    struct CapturingModel {
1160        seen: std::sync::Mutex<Vec<LLMRequest>>,
1161    }
1162
1163    impl LanguageModel for CapturingModel {
1164        type Error = NoError;
1165
1166        fn respond(
1167            &self,
1168            request: LLMRequest,
1169        ) -> impl futures_lite::Stream<Item = Result<Event, Self::Error>> + Send {
1170            self.seen.lock().unwrap().push(request);
1171            futures_lite::stream::iter([Ok(Event::Text(
1172                r#"{"current_task":"keep going","key_decisions":[],"context_files":[],"errors_fixes":[],"pending_work":["continue"],"recovery_hints":[],"skills":[]}"#
1173                    .to_string(),
1174            ))])
1175        }
1176
1177        fn profile(
1178            &self,
1179        ) -> impl std::future::Future<
1180            Output = Result<aither_core::llm::model::Profile, Self::Error>,
1181        > + Send {
1182            std::future::ready(Ok(aither_core::llm::model::Profile::new(
1183                "capture",
1184                "test",
1185                "capture",
1186                "capturing model",
1187                1_000_000,
1188            )))
1189        }
1190    }
1191
1192    /// The compaction request must reach the provider with the session's
1193    /// cache controls and the structured-output flag `generate` sets.
1194    #[tokio::test]
1195    async fn the_compaction_request_keeps_the_cache_controls_beside_structured_outputs() {
1196        use aither_core::llm::model::{
1197            ClaudeCacheBreakpointTarget, ClaudePromptCacheStrategy, OpenAIPromptCacheRetention,
1198            Parameters,
1199        };
1200
1201        let messages = vec![
1202            Message::system("prefix"),
1203            Message::user("hello"),
1204            Message::assistant("hi"),
1205            Message::system("live tail"),
1206        ];
1207        let parameters = crate::context::PromptCache::new("session-1").apply(
1208            Parameters::default(),
1209            &messages,
1210            false,
1211            false,
1212        );
1213        let main = LLMRequest::new(messages).with_parameters(parameters);
1214        let fork =
1215            CompactionFork::<HandoffDocument>::new(&main, 0, &[], None, &[], &[]).expect("fork");
1216        let model = CapturingModel {
1217            seen: std::sync::Mutex::default(),
1218        };
1219        fork.run(&model).await.expect("compaction");
1220
1221        let request = model.seen.lock().unwrap().remove(0);
1222        let parameters = request.parameters();
1223        assert!(parameters.structured_outputs);
1224        let openai = parameters.cache.openai.as_ref().expect("openai cache");
1225        assert_eq!(openai.key.as_deref(), Some("session-1:0"));
1226        assert_eq!(openai.retention, Some(OpenAIPromptCacheRetention::Hours24));
1227        let ClaudePromptCacheStrategy::Explicit(breakpoints) =
1228            parameters.cache.claude.expect("claude cache").strategy
1229        else {
1230            panic!("expected explicit claude breakpoints");
1231        };
1232        assert_eq!(
1233            breakpoints.first.target,
1234            ClaudeCacheBreakpointTarget::LastSystem
1235        );
1236    }
1237}