Skip to main content

aither_agent/
context.rs

1//! Unified context manager for agent conversation state.
2//!
3//! The [`Context`] struct owns the entire context window state: persistent
4//! system blocks (stable cacheable prefix), ephemeral reminders, compaction
5//! handoff, and recent conversation messages.
6
7use std::hash::{Hash, Hasher};
8
9use indexmap::IndexMap;
10use serde::{Deserialize, Serialize};
11
12use aither_core::llm::{Message, Role};
13
14use crate::handoff::HandoffDocument;
15
16#[derive(Serialize)]
17struct TextBlock<'a> {
18    #[serde(rename = "$text")]
19    content: &'a str,
20}
21
22/// The entire context window state. Fully serializable for persistence.
23#[derive(Debug, Clone, Default, Serialize, Deserialize)]
24pub struct Context {
25    /// Persistent system blocks keyed by `snake_case` type name.
26    ///
27    /// These survive compaction and are rendered as a single cacheable system
28    /// prefix message.
29    system_blocks: IndexMap<String, String>,
30
31    /// Staged replacements for system blocks, applied on the next
32    /// [`reassemble`](Self::reassemble).
33    ///
34    /// Rewriting a system block mid-session invalidates the KV-cache prefix.
35    /// Hosts stage the new content here (surfacing the change to the model as
36    /// an appended diff alert instead) and let reassembly fold it in once the
37    /// cache is already going to be invalidated.
38    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
39    staged_system_updates: IndexMap<String, String>,
40
41    /// Compaction handoff document from previous context compaction.
42    ///
43    /// This is rendered immediately after the stable system prefix.
44    handoff: Option<String>,
45
46    /// Ordered runtime items rendered after the optional handoff anchor.
47    runtime_items: Vec<ContextCheckpointItem>,
48}
49
50/// Outcome of a [`Context::reassemble`] pass.
51#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
52pub struct ReassemblyReport {
53    /// Ephemeral reminders removed.
54    pub reminders_cleared: usize,
55    /// Recent system messages (system alerts) removed.
56    pub system_messages_pruned: usize,
57    /// Tool results replaced with a tombstone because a later identical call
58    /// holds the current result.
59    pub tool_results_deduped: usize,
60    /// Staged system block updates folded into the stable prefix.
61    pub staged_updates_applied: usize,
62    /// Estimated bytes freed from the assembled window.
63    pub bytes_freed: usize,
64}
65
66impl ReassemblyReport {
67    /// Whether the pass changed anything.
68    #[must_use]
69    pub const fn changed(&self) -> bool {
70        self.reminders_cleared > 0
71            || self.system_messages_pruned > 0
72            || self.tool_results_deduped > 0
73            || self.staged_updates_applied > 0
74    }
75}
76
77/// Tombstone text left in place of a superseded tool result.
78const SUPERSEDED_TOOL_RESULT: &str =
79    "(superseded: an identical later call in this conversation holds the current result)";
80
81/// Ordered runtime items stored after the fixed handoff anchor.
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
83pub enum ContextCheckpointItem {
84    /// A reminder rendered as a system message.
85    Reminder(String),
86    /// A regular conversation message.
87    Message(Message),
88}
89
90impl Context {
91    /// Creates a new empty context.
92    #[must_use]
93    pub fn new() -> Self {
94        Self::default()
95    }
96
97    // ── System blocks (stable, cacheable prefix) ──────────────────────
98
99    /// Inserts or replaces a persistent system block.
100    ///
101    /// Identity is derived from the `snake_case` type name of `T`.
102    pub fn insert_system<T: Serialize>(&mut self, value: &T) {
103        let tag = snake_case_type_name::<T>();
104        let xml = serialize_xml(&tag, value);
105        self.system_blocks.insert(tag, xml);
106    }
107
108    /// Inserts or replaces a persistent system block with an explicit tag.
109    pub fn insert_system_named(&mut self, tag: impl Into<String>, content: impl Into<String>) {
110        let tag = tag.into();
111        let content = content.into();
112        let xml = serialize_xml(&tag, &TextBlock { content: &content });
113        self.system_blocks.insert(tag, xml);
114    }
115
116    /// Removes a persistent system block by type.
117    pub fn remove_system<T>(&mut self) {
118        let tag = snake_case_type_name::<T>();
119        self.system_blocks.shift_remove(&tag);
120    }
121
122    /// Removes a persistent system block by explicit tag.
123    pub fn remove_system_named(&mut self, tag: &str) {
124        self.system_blocks.shift_remove(tag);
125    }
126
127    /// Returns the number of persistent system blocks.
128    #[must_use]
129    pub fn system_block_count(&self) -> usize {
130        self.system_blocks.len()
131    }
132
133    /// Returns whether a persistent system block with `tag` exists.
134    #[must_use]
135    pub fn has_system_block(&self, tag: &str) -> bool {
136        self.system_blocks.contains_key(tag)
137    }
138
139    /// Returns an immutable view of persistent system blocks.
140    #[must_use]
141    pub const fn system_blocks(&self) -> &IndexMap<String, String> {
142        &self.system_blocks
143    }
144
145    /// Returns a mutable view of persistent system blocks.
146    #[must_use]
147    pub const fn system_blocks_mut(&mut self) -> &mut IndexMap<String, String> {
148        &mut self.system_blocks
149    }
150
151    /// Inserts or replaces a persistent system block with raw text.
152    ///
153    /// Unlike [`insert_system`](Self::insert_system) and
154    /// [`insert_system_named`](Self::insert_system_named), the `content` is
155    /// stored verbatim without any XML wrapping. This is the preferred entry
156    /// point for prose system blocks such as workspace descriptions, runtime
157    /// metadata, and environment hints, where XML structure adds tokens
158    /// without providing semantic value.
159    ///
160    /// Use [`insert_system`](Self::insert_system) only when the block is a
161    /// structured payload that genuinely needs XML delimiters to separate
162    /// context from instructions (for example, attached documents).
163    pub fn insert_system_text(&mut self, tag: impl Into<String>, content: impl Into<String>) {
164        self.system_blocks.insert(tag.into(), content.into());
165    }
166
167    /// Returns a stable fingerprint of the current system blocks in order.
168    ///
169    /// The fingerprint changes if and only if the ordered set of
170    /// `(tag, content)` pairs changes. Hosts can use this to detect
171    /// cache-invalidating modifications to the stable system prefix
172    /// (for example, to track KV-cache hit rate over time).
173    #[must_use]
174    pub fn stable_prefix_fingerprint(&self) -> u64 {
175        let mut hasher = std::collections::hash_map::DefaultHasher::new();
176        for (tag, content) in &self.system_blocks {
177            tag.hash(&mut hasher);
178            content.hash(&mut hasher);
179        }
180        hasher.finish()
181    }
182
183    // ── Reminders (ephemeral) ─────────────────────────────────────────
184
185    /// Inserts an ephemeral reminder.
186    pub fn insert_reminder<T: Serialize>(&mut self, value: &T) {
187        let tag = snake_case_type_name::<T>();
188        let xml = serialize_xml(&tag, value);
189        self.runtime_items
190            .push(ContextCheckpointItem::Reminder(xml));
191    }
192
193    /// Clears all ephemeral reminders.
194    pub fn clear_reminders(&mut self) {
195        self.runtime_items
196            .retain(|item| !matches!(item, ContextCheckpointItem::Reminder(_)));
197    }
198
199    /// Returns current reminders.
200    #[must_use]
201    pub fn reminders(&self) -> Vec<&str> {
202        self.runtime_items
203            .iter()
204            .filter_map(|item| match item {
205                ContextCheckpointItem::Reminder(content) => Some(content.as_str()),
206                ContextCheckpointItem::Message(_) => None,
207            })
208            .collect()
209    }
210
211    // ── Handoff ───────────────────────────────────────────────────────
212
213    /// Sets or replaces the compaction handoff document.
214    pub fn set_handoff(&mut self, handoff: impl Into<String>) {
215        let handoff = handoff.into();
216        self.handoff = Some(serialize_xml("handoff", &TextBlock { content: &handoff }));
217    }
218
219    /// Sets the compaction handoff document from a structured handoff artifact.
220    pub fn set_handoff_document(&mut self, handoff: &HandoffDocument) {
221        self.handoff = Some(serialize_xml("handoff", handoff));
222    }
223
224    /// Clears the compaction handoff document.
225    pub fn clear_handoff(&mut self) {
226        self.handoff = None;
227    }
228
229    /// Returns the current compaction handoff document.
230    #[must_use]
231    pub fn handoff(&self) -> Option<&str> {
232        self.handoff.as_deref()
233    }
234
235    // ── Recent conversation ───────────────────────────────────────────
236
237    /// Appends a message to recent conversation.
238    pub fn push(&mut self, message: Message) {
239        self.runtime_items
240            .push(ContextCheckpointItem::Message(message));
241    }
242
243    /// Extends recent conversation with multiple messages.
244    pub fn extend(&mut self, messages: impl IntoIterator<Item = Message>) {
245        self.runtime_items
246            .extend(messages.into_iter().map(ContextCheckpointItem::Message));
247    }
248
249    /// Returns number of recent conversation messages.
250    #[must_use]
251    pub fn len_recent(&self) -> usize {
252        self.runtime_items
253            .iter()
254            .filter(|item| matches!(item, ContextCheckpointItem::Message(_)))
255            .count()
256    }
257
258    /// Returns the number of recent system messages.
259    #[must_use]
260    pub fn count_recent_system_messages(&self) -> usize {
261        self.runtime_items
262            .iter()
263            .filter(|item| {
264                matches!(
265                    item,
266                    ContextCheckpointItem::Message(message) if message.role() == Role::System
267                )
268            })
269            .count()
270    }
271
272    /// Returns recent conversation messages.
273    #[must_use]
274    pub fn recent(&self) -> Vec<&Message> {
275        self.runtime_items
276            .iter()
277            .filter_map(|item| match item {
278                ContextCheckpointItem::Reminder(_) => None,
279                ContextCheckpointItem::Message(message) => Some(message),
280            })
281            .collect()
282    }
283
284    /// Returns the latest recent message.
285    #[must_use]
286    pub fn last(&self) -> Option<&Message> {
287        self.runtime_items.iter().rev().find_map(|item| match item {
288            ContextCheckpointItem::Reminder(_) => None,
289            ContextCheckpointItem::Message(message) => Some(message),
290        })
291    }
292
293    /// Returns whether recent conversation is empty.
294    #[must_use]
295    pub fn is_conversation_empty(&self) -> bool {
296        self.len_recent() == 0
297    }
298
299    /// Drains oldest recent messages while keeping the latest `keep` messages.
300    pub fn drain_oldest(&mut self, keep: usize) -> Vec<Message> {
301        let remove_count = self.len_recent().saturating_sub(keep);
302        if remove_count == 0 {
303            return Vec::new();
304        }
305        let mut removed = Vec::with_capacity(remove_count);
306        let mut removed_messages = 0usize;
307        let mut retained = Vec::with_capacity(self.runtime_items.len());
308        for item in self.runtime_items.drain(..) {
309            match item {
310                ContextCheckpointItem::Message(message) if removed_messages < remove_count => {
311                    removed.push(message);
312                    removed_messages += 1;
313                }
314                other => retained.push(other),
315            }
316        }
317        self.runtime_items = retained;
318        removed
319    }
320
321    /// Returns recent conversation messages cloned.
322    #[must_use]
323    pub fn conversation_messages(&self) -> Vec<Message> {
324        self.runtime_items
325            .iter()
326            .filter_map(|item| match item {
327                ContextCheckpointItem::Reminder(_) => None,
328                ContextCheckpointItem::Message(message) => Some(message.clone()),
329            })
330            .collect()
331    }
332
333    // ── Message assembly ───────────────────────────────────────────────
334
335    /// Builds the full LLM message list.
336    ///
337    /// Layout:
338    /// 1. Persistent system blocks (single cacheable prefix)
339    /// 2. Compaction handoff (optional system message)
340    /// 3. Additional transient system messages for the current request
341    /// 4. Ordered runtime items (reminders and conversation messages)
342    #[must_use]
343    pub fn build_messages(&self) -> Vec<Message> {
344        self.build_messages_with_transient_system(&[])
345    }
346
347    /// Builds the full LLM message list with additional transient system messages.
348    ///
349    /// Transient system messages are appended immediately after the fixed handoff
350    /// anchor and before ordered runtime items. They are not
351    /// stored inside the context and therefore are not checkpointed.
352    #[must_use]
353    pub fn build_messages_with_transient_system(
354        &self,
355        transient_system: &[String],
356    ) -> Vec<Message> {
357        let mut messages = Vec::new();
358
359        if !self.system_blocks.is_empty() {
360            let system_xml = self
361                .system_blocks
362                .values()
363                .cloned()
364                .collect::<Vec<_>>()
365                .join("\n");
366            messages.push(Message::system(system_xml));
367        }
368
369        if let Some(handoff) = &self.handoff {
370            messages.push(Message::system(handoff));
371        }
372
373        for content in transient_system {
374            messages.push(Message::system(content.clone()));
375        }
376
377        messages.extend(self.runtime_items.iter().cloned().map(|item| match item {
378            ContextCheckpointItem::Reminder(content) => Message::system(content),
379            ContextCheckpointItem::Message(message) => message,
380        }));
381        messages
382    }
383
384    // ── Lifecycle ─────────────────────────────────────────────────────
385
386    /// Clears only recent conversation messages.
387    pub fn clear_recent(&mut self) {
388        self.runtime_items
389            .retain(|item| !matches!(item, ContextCheckpointItem::Message(_)));
390    }
391
392    /// Clears all non-persistent context: reminders, handoff, recent conversation.
393    pub fn clear_history(&mut self) {
394        self.handoff = None;
395        self.runtime_items.clear();
396    }
397
398    /// Clears everything, including persistent system blocks.
399    pub fn clear_all(&mut self) {
400        self.system_blocks.clear();
401        self.clear_history();
402    }
403
404    /// Clones the context.
405    #[must_use]
406    pub fn fork(&self) -> Self {
407        self.clone()
408    }
409
410    /// Creates a checkpoint that can be restored later.
411    #[must_use]
412    pub fn checkpoint(&self) -> ContextCheckpoint {
413        ContextCheckpoint {
414            handoff: self.handoff.clone(),
415            items: self.runtime_items.clone(),
416        }
417    }
418
419    /// Restores reminders, handoff, and recent conversation from checkpoint.
420    pub fn restore(&mut self, checkpoint: ContextCheckpoint) {
421        self.handoff = checkpoint.handoff;
422        self.runtime_items = checkpoint.items;
423    }
424
425    // ── Staged system block updates ───────────────────────────────────
426
427    /// Stages a replacement for a system block, deferring the cache-invalidating
428    /// rewrite until the next [`reassemble`](Self::reassemble).
429    ///
430    /// If no block with `tag` exists yet, the content is inserted immediately
431    /// (nothing to preserve in the cache) and `false` is returned. Otherwise the
432    /// update is staged and `true` is returned; the host should surface the
433    /// change to the model as an appended diff alert.
434    pub fn stage_system_text(
435        &mut self,
436        tag: impl Into<String>,
437        content: impl Into<String>,
438    ) -> bool {
439        let tag = tag.into();
440        let content = content.into();
441        if let Some(existing) = self.system_blocks.get(&tag) {
442            if *existing == content {
443                self.staged_system_updates.shift_remove(&tag);
444                return false;
445            }
446            self.staged_system_updates.insert(tag, content);
447            true
448        } else {
449            self.system_blocks.insert(tag, content);
450            false
451        }
452    }
453
454    /// Returns the staged replacement for `tag`, if any.
455    #[must_use]
456    pub fn staged_system_update(&self, tag: &str) -> Option<&str> {
457        self.staged_system_updates.get(tag).map(String::as_str)
458    }
459
460    // ── Reassembly (lightweight, non-LLM context rewrite) ────────────
461
462    /// Performs a lightweight context reassembly.
463    ///
464    /// This rewrites the window without calling any LLM:
465    /// 1. folds staged system block updates into the stable prefix,
466    /// 2. clears all ephemeral reminders,
467    /// 3. removes recent system messages (system alerts),
468    /// 4. tombstones tool results superseded by a later identical call or an
469    ///    identical later result.
470    ///
471    /// Reassembly invalidates the KV-cache prefix, so hosts should run it when
472    /// the cache is already cold (idle gap) or right before compaction.
473    pub fn reassemble(&mut self) -> ReassemblyReport {
474        let mut report = ReassemblyReport::default();
475
476        for (tag, content) in std::mem::take(&mut self.staged_system_updates) {
477            if let Some(existing) = self.system_blocks.get_mut(&tag) {
478                report.bytes_freed += existing.len().saturating_sub(content.len());
479                *existing = content;
480            } else {
481                self.system_blocks.insert(tag, content);
482            }
483            report.staged_updates_applied += 1;
484        }
485
486        let mut removed_bytes = 0usize;
487        let mut reminders_cleared = 0usize;
488        let mut system_messages_pruned = 0usize;
489        self.runtime_items.retain(|item| match item {
490            ContextCheckpointItem::Reminder(content) => {
491                reminders_cleared += 1;
492                removed_bytes += content.len();
493                false
494            }
495            ContextCheckpointItem::Message(message) if message.role() == Role::System => {
496                system_messages_pruned += 1;
497                removed_bytes += message.content().len();
498                false
499            }
500            ContextCheckpointItem::Message(_) => true,
501        });
502        report.reminders_cleared = reminders_cleared;
503        report.system_messages_pruned = system_messages_pruned;
504        report.bytes_freed += removed_bytes;
505
506        let (deduped, dedupe_bytes) = self.tombstone_superseded_tool_results();
507        report.tool_results_deduped = deduped;
508        report.bytes_freed += dedupe_bytes;
509
510        report
511    }
512
513    /// Estimates how many bytes a [`reassemble`](Self::reassemble) would free,
514    /// without mutating the context.
515    #[must_use]
516    pub fn estimate_reassembly_savings(&self) -> usize {
517        let alerts: usize = self
518            .runtime_items
519            .iter()
520            .map(|item| match item {
521                ContextCheckpointItem::Reminder(content) => content.len(),
522                ContextCheckpointItem::Message(message) if message.role() == Role::System => {
523                    message.content().len()
524                }
525                ContextCheckpointItem::Message(_) => 0,
526            })
527            .sum();
528        let (_, dedupe_bytes) = self.find_superseded_tool_results();
529        alerts + dedupe_bytes
530    }
531
532    /// Identifies tool results superseded by a later identical call (same tool
533    /// name and arguments) or an identical later result.
534    ///
535    /// Returns the indices to tombstone and the bytes that doing so would free.
536    fn find_superseded_tool_results(&self) -> (Vec<usize>, usize) {
537        use std::collections::HashMap;
538
539        // Map call id → identity key of (tool name, canonical arguments).
540        let mut call_identity: HashMap<&str, String> = HashMap::new();
541        for item in &self.runtime_items {
542            let ContextCheckpointItem::Message(message) = item else {
543                continue;
544            };
545            for call in message.tool_calls() {
546                call_identity.insert(
547                    call.id.as_str(),
548                    format!("{}\u{0}{}", call.name, call.arguments),
549                );
550            }
551        }
552
553        // Last occurrence per identity key and per exact result content.
554        let mut last_by_call: HashMap<&str, usize> = HashMap::new();
555        let mut last_by_content: HashMap<&str, usize> = HashMap::new();
556        for (index, item) in self.runtime_items.iter().enumerate() {
557            let ContextCheckpointItem::Message(Message::Tool {
558                content,
559                tool_call_id,
560            }) = item
561            else {
562                continue;
563            };
564            if let Some(identity) = call_identity.get(tool_call_id.as_str()) {
565                last_by_call.insert(identity.as_str(), index);
566            }
567            last_by_content.insert(content.as_str(), index);
568        }
569
570        let mut indices = Vec::new();
571        let mut bytes = 0usize;
572        for (index, item) in self.runtime_items.iter().enumerate() {
573            let ContextCheckpointItem::Message(Message::Tool {
574                content,
575                tool_call_id,
576            }) = item
577            else {
578                continue;
579            };
580            if content.len() <= SUPERSEDED_TOOL_RESULT.len() {
581                continue;
582            }
583            let superseded_by_call = call_identity
584                .get(tool_call_id.as_str())
585                .and_then(|identity| last_by_call.get(identity.as_str()))
586                .is_some_and(|&last| last > index);
587            let superseded_by_content = last_by_content
588                .get(content.as_str())
589                .is_some_and(|&last| last > index);
590            if superseded_by_call || superseded_by_content {
591                indices.push(index);
592                bytes += content.len() - SUPERSEDED_TOOL_RESULT.len();
593            }
594        }
595        (indices, bytes)
596    }
597
598    /// Applies [`find_superseded_tool_results`](Self::find_superseded_tool_results).
599    fn tombstone_superseded_tool_results(&mut self) -> (usize, usize) {
600        let (indices, bytes) = self.find_superseded_tool_results();
601        for &index in &indices {
602            if let Some(ContextCheckpointItem::Message(Message::Tool { content, .. })) =
603                self.runtime_items.get_mut(index)
604            {
605                *content = SUPERSEDED_TOOL_RESULT.to_string();
606            }
607        }
608        (indices.len(), bytes)
609    }
610
611    /// Removes recent system messages and returns how many were pruned.
612    pub fn prune_recent_system_messages(&mut self) -> usize {
613        let before = self.len_recent();
614        self.runtime_items.retain(|item| {
615            !matches!(
616                item,
617                ContextCheckpointItem::Message(message) if message.role() == Role::System
618            )
619        });
620        before - self.len_recent()
621    }
622
623    /// Restores runtime-managed state from another serialized context while
624    /// preserving the current persistent system blocks.
625    pub fn restore_runtime_state(&mut self, restored: Self) {
626        self.handoff = restored.handoff;
627        self.runtime_items = restored.runtime_items;
628    }
629}
630
631/// A snapshot of non-persistent context state that can be restored.
632#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
633pub struct ContextCheckpoint {
634    handoff: Option<String>,
635    items: Vec<ContextCheckpointItem>,
636}
637
638impl ContextCheckpoint {
639    /// Creates a structured runtime checkpoint.
640    #[must_use]
641    pub const fn new(handoff: Option<String>, items: Vec<ContextCheckpointItem>) -> Self {
642        Self { handoff, items }
643    }
644
645    /// Returns the number of recent messages in this checkpoint.
646    #[must_use]
647    pub fn len_recent(&self) -> usize {
648        self.items
649            .iter()
650            .filter(|item| matches!(item, ContextCheckpointItem::Message(_)))
651            .count()
652    }
653
654    /// Returns the current handoff document, if present.
655    #[must_use]
656    pub fn handoff(&self) -> Option<&str> {
657        self.handoff.as_deref()
658    }
659
660    /// Returns ordered runtime checkpoint items.
661    #[must_use]
662    pub fn items(&self) -> &[ContextCheckpointItem] {
663        &self.items
664    }
665
666    /// Returns whether this checkpoint has no handoff and no runtime items.
667    #[must_use]
668    pub const fn is_empty(&self) -> bool {
669        self.handoff.is_none() && self.items.is_empty()
670    }
671}
672
673// ── Helpers ───────────────────────────────────────────────────────────
674
675fn snake_case_type_name<T>() -> String {
676    let full = std::any::type_name::<T>();
677    let short = full.rsplit("::").next().unwrap_or(full);
678    heck::AsSnakeCase(short).to_string()
679}
680
681pub fn serialize_xml<T: Serialize>(tag: &str, value: &T) -> String {
682    let mut buffer = String::new();
683    let serializer = quick_xml::se::Serializer::with_root(&mut buffer, Some(tag))
684        .unwrap_or_else(|error| panic!("failed to create XML serializer for tag '{tag}': {error}"));
685
686    value
687        .serialize(serializer)
688        .unwrap_or_else(|error| panic!("failed to serialize XML for tag '{tag}': {error}"));
689
690    buffer
691}
692
693#[cfg(test)]
694mod tests {
695    use super::*;
696
697    #[derive(Serialize)]
698    struct Memory {
699        #[serde(rename = "$text")]
700        content: String,
701    }
702
703    #[derive(Serialize)]
704    struct Reminder {
705        #[serde(rename = "$text")]
706        content: String,
707    }
708
709    #[derive(Serialize)]
710    struct Workspace {
711        sandbox: String,
712        cwd: String,
713    }
714
715    #[test]
716    fn snake_case_type_name_uses_short_struct_name() {
717        assert_eq!(snake_case_type_name::<Memory>(), "memory");
718    }
719
720    #[test]
721    fn serialize_xml_renders_text_content() {
722        let xml = serialize_xml(
723            "memory",
724            &Memory {
725                content: "remember this".to_string(),
726            },
727        );
728        assert!(xml.contains("<memory>"));
729        assert!(xml.contains("remember this"));
730        assert!(xml.contains("</memory>"));
731    }
732
733    #[test]
734    fn serialize_xml_renders_struct_fields() {
735        let xml = serialize_xml(
736            "workspace",
737            &Workspace {
738                sandbox: "/tmp/sandbox".to_string(),
739                cwd: "/home/user".to_string(),
740            },
741        );
742        assert!(xml.contains("<workspace>"));
743        assert!(xml.contains("<sandbox>"));
744        assert!(xml.contains("/tmp/sandbox"));
745        assert!(xml.contains("</workspace>"));
746    }
747
748    #[test]
749    fn insert_system_text_stores_raw_content() {
750        let mut context = Context::new();
751        context.insert_system_text("workspace", "Environment: local\nCWD: /tmp");
752
753        assert_eq!(context.system_block_count(), 1);
754        let messages = context.build_messages();
755        assert_eq!(messages.len(), 1);
756        let rendered = messages[0].content();
757        assert!(rendered.contains("Environment: local"));
758        assert!(rendered.contains("CWD: /tmp"));
759        assert!(
760            !rendered.contains("<workspace>"),
761            "insert_system_text must not add XML tags: {rendered}"
762        );
763    }
764
765    #[test]
766    fn insert_system_text_replaces_by_tag() {
767        let mut context = Context::new();
768        context.insert_system_text("workspace", "old");
769        context.insert_system_text("workspace", "new");
770
771        assert_eq!(context.system_block_count(), 1);
772        let messages = context.build_messages();
773        assert!(messages[0].content().contains("new"));
774        assert!(!messages[0].content().contains("old"));
775    }
776
777    #[test]
778    fn stable_prefix_fingerprint_reflects_block_changes() {
779        let mut context = Context::new();
780        let empty = context.stable_prefix_fingerprint();
781
782        context.insert_system_text("workspace", "a");
783        let after_insert = context.stable_prefix_fingerprint();
784        assert_ne!(empty, after_insert);
785
786        context.insert_system_text("workspace", "b");
787        let after_edit = context.stable_prefix_fingerprint();
788        assert_ne!(after_insert, after_edit);
789
790        context.remove_system_named("workspace");
791        assert_eq!(context.stable_prefix_fingerprint(), empty);
792    }
793
794    #[test]
795    fn stable_prefix_fingerprint_is_order_sensitive() {
796        let mut a = Context::new();
797        a.insert_system_text("one", "1");
798        a.insert_system_text("two", "2");
799
800        let mut b = Context::new();
801        b.insert_system_text("two", "2");
802        b.insert_system_text("one", "1");
803
804        assert_ne!(
805            a.stable_prefix_fingerprint(),
806            b.stable_prefix_fingerprint(),
807            "insertion order must be part of the fingerprint to reflect KV-cache prefix stability"
808        );
809    }
810
811    #[test]
812    fn insert_system_replaces_existing_block() {
813        let mut context = Context::new();
814        context.insert_system(&Memory {
815            content: "old".to_string(),
816        });
817        context.insert_system(&Memory {
818            content: "new".to_string(),
819        });
820
821        assert_eq!(context.system_block_count(), 1);
822        let messages = context.build_messages();
823        assert_eq!(messages.len(), 1);
824        assert!(messages[0].content().contains("new"));
825        assert!(!messages[0].content().contains("old"));
826    }
827
828    #[test]
829    fn build_messages_has_expected_layout() {
830        let mut context = Context::new();
831        context.insert_system(&Memory {
832            content: "base".to_string(),
833        });
834        context.insert_reminder(&Reminder {
835            content: "todo".to_string(),
836        });
837        context.set_handoff("summary");
838        context.push(Message::user("hello"));
839
840        let messages = context.build_messages();
841        assert_eq!(messages.len(), 4);
842        assert!(messages[0].content().contains("base"));
843        assert!(messages[1].content().contains("handoff"));
844        assert!(messages[2].content().contains("todo"));
845        assert!(messages[3].content().contains("hello"));
846    }
847
848    #[test]
849    fn transient_system_messages_are_inserted_before_recent_conversation() {
850        let mut context = Context::new();
851        context.insert_system(&Memory {
852            content: "base".to_string(),
853        });
854        context.insert_reminder(&Reminder {
855            content: "todo".to_string(),
856        });
857        context.set_handoff("summary");
858        context.push(Message::user("hello"));
859
860        let messages = context.build_messages_with_transient_system(&["hidden".to_string()]);
861        assert_eq!(messages.len(), 5);
862        assert!(messages[0].content().contains("base"));
863        assert!(messages[1].content().contains("handoff"));
864        assert_eq!(messages[2].content(), "hidden");
865        assert!(messages[3].content().contains("todo"));
866        assert!(messages[4].content().contains("hello"));
867    }
868
869    #[test]
870    fn clear_history_preserves_system_blocks() {
871        let mut context = Context::new();
872        context.insert_system(&Memory {
873            content: "persist".to_string(),
874        });
875        context.insert_reminder(&Reminder {
876            content: "ephemeral".to_string(),
877        });
878        context.set_handoff("summary");
879        context.push(Message::assistant("recent"));
880
881        context.clear_history();
882
883        assert_eq!(context.system_block_count(), 1);
884        assert!(context.reminders().is_empty());
885        assert!(context.handoff().is_none());
886        assert_eq!(context.len_recent(), 0);
887    }
888
889    #[test]
890    fn checkpoint_restore_roundtrip() {
891        let mut context = Context::new();
892        context.insert_reminder(&Reminder {
893            content: "before".to_string(),
894        });
895        context.set_handoff("before");
896        context.push(Message::user("first"));
897
898        let checkpoint = context.checkpoint();
899
900        context.clear_history();
901        context.insert_reminder(&Reminder {
902            content: "after".to_string(),
903        });
904        context.push(Message::user("second"));
905
906        context.restore(checkpoint);
907
908        assert_eq!(context.reminders().len(), 1);
909        assert!(context.handoff().is_some());
910        assert_eq!(context.len_recent(), 1);
911        assert_eq!(context.recent()[0].content(), "first");
912    }
913
914    #[test]
915    fn restore_runtime_state_preserves_system_blocks() {
916        let mut current = Context::new();
917        current.insert_system(&Memory {
918            content: "fresh".to_string(),
919        });
920
921        let mut restored = Context::new();
922        restored.insert_system(&Memory {
923            content: "stale".to_string(),
924        });
925        restored.insert_reminder(&Reminder {
926            content: "ephemeral".to_string(),
927        });
928        restored.set_handoff("summary");
929        restored.push(Message::user("hello"));
930
931        current.restore_runtime_state(restored);
932
933        let messages = current.build_messages();
934        assert!(messages[0].content().contains("fresh"));
935        assert!(!messages[0].content().contains("stale"));
936        assert_eq!(current.reminders().len(), 1);
937        assert!(current.handoff().is_some());
938        assert_eq!(current.len_recent(), 1);
939    }
940
941    #[test]
942    fn prune_recent_system_messages_removes_only_system_entries() {
943        let mut context = Context::new();
944        context.push(Message::user("user"));
945        context.push(Message::system("system"));
946        context.push(Message::assistant("assistant"));
947        context.push(Message::system("system-2"));
948
949        let removed = context.prune_recent_system_messages();
950
951        assert_eq!(removed, 2);
952        assert_eq!(context.len_recent(), 2);
953        assert_eq!(context.recent()[0].content(), "user");
954        assert_eq!(context.recent()[1].content(), "assistant");
955    }
956
957    #[test]
958    fn stage_system_text_defers_existing_block_rewrite() {
959        let mut context = Context::new();
960        context.insert_system_text("memory", "v1");
961
962        assert!(context.stage_system_text("memory", "v2"));
963        // The live block is untouched until reassembly (cache-friendly).
964        assert!(context.build_messages()[0].content().contains("v1"));
965        assert_eq!(context.staged_system_update("memory"), Some("v2"));
966
967        let report = context.reassemble();
968        assert_eq!(report.staged_updates_applied, 1);
969        assert!(context.build_messages()[0].content().contains("v2"));
970        assert_eq!(context.staged_system_update("memory"), None);
971    }
972
973    #[test]
974    fn stage_system_text_inserts_directly_when_block_missing() {
975        let mut context = Context::new();
976        assert!(!context.stage_system_text("memory", "fresh"));
977        assert!(context.build_messages()[0].content().contains("fresh"));
978    }
979
980    #[test]
981    fn reassemble_clears_alerts_and_tombstones_superseded_results() {
982        use aither_core::llm::ToolCall;
983
984        let mut context = Context::new();
985        context.insert_reminder(&Reminder {
986            content: "alert".to_string(),
987        });
988        context.push(Message::system("system alert"));
989
990        let args = serde_json::json!({"script": "cat skills/slide/SKILL.md"});
991        let long_result = "the full skill document ".repeat(20);
992        context.push(Message::assistant_with_tool_calls(
993            "",
994            vec![ToolCall::new("call_1", "terminal", args.clone())],
995        ));
996        context.push(Message::tool("call_1", long_result.clone()));
997        context.push(Message::assistant_with_tool_calls(
998            "",
999            vec![ToolCall::new("call_2", "terminal", args)],
1000        ));
1001        context.push(Message::tool("call_2", long_result.clone()));
1002
1003        let estimated = context.estimate_reassembly_savings();
1004        assert!(estimated > 0);
1005
1006        let report = context.reassemble();
1007        assert_eq!(report.reminders_cleared, 1);
1008        assert_eq!(report.system_messages_pruned, 1);
1009        assert_eq!(report.tool_results_deduped, 1);
1010        assert_eq!(report.bytes_freed, estimated);
1011
1012        let recent = context.recent();
1013        // First (superseded) result is tombstoned; the latest keeps full content.
1014        assert!(recent[1].content().contains("superseded"));
1015        assert_eq!(recent[3].content(), long_result);
1016    }
1017
1018    #[test]
1019    fn reassemble_tombstones_identical_result_content_across_different_calls() {
1020        use aither_core::llm::ToolCall;
1021
1022        let mut context = Context::new();
1023        let duplicated = "identical output body ".repeat(10);
1024        context.push(Message::assistant_with_tool_calls(
1025            "",
1026            vec![ToolCall::new(
1027                "call_1",
1028                "terminal",
1029                serde_json::json!({"script": "cat a.txt"}),
1030            )],
1031        ));
1032        context.push(Message::tool("call_1", duplicated.clone()));
1033        context.push(Message::assistant_with_tool_calls(
1034            "",
1035            vec![ToolCall::new(
1036                "call_2",
1037                "terminal",
1038                serde_json::json!({"script": "sed -n 1,200p a.txt"}),
1039            )],
1040        ));
1041        context.push(Message::tool("call_2", duplicated.clone()));
1042
1043        let report = context.reassemble();
1044        assert_eq!(report.tool_results_deduped, 1);
1045        let recent = context.recent();
1046        assert!(recent[1].content().contains("superseded"));
1047        assert_eq!(recent[3].content(), duplicated);
1048    }
1049
1050    #[test]
1051    fn serde_roundtrip_preserves_message_layout() {
1052        let mut context = Context::new();
1053        context.insert_system(&Memory {
1054            content: "persist".to_string(),
1055        });
1056        context.insert_reminder(&Reminder {
1057            content: "ephemeral".to_string(),
1058        });
1059        context.set_handoff("summary");
1060        context.push(Message::user("hello"));
1061        context.push(Message::assistant("world"));
1062
1063        let expected_messages = context.build_messages();
1064        let encoded = serde_json::to_string(&context)
1065            .unwrap_or_else(|error| panic!("failed to serialize context: {error}"));
1066        let decoded: Context = serde_json::from_str(&encoded)
1067            .unwrap_or_else(|error| panic!("failed to deserialize context: {error}"));
1068        let actual_messages = decoded.build_messages();
1069
1070        assert_eq!(actual_messages, expected_messages);
1071    }
1072}