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    ///
187    /// Reminders are transient by design: `clear_reminders` runs at the top of
188    /// every request's reminder repopulation, so a reminder reaches the model
189    /// only when it is (re)generated inside that populate pass. Anything the
190    /// agent must actually deliver — mid-turn corrections, queued alerts —
191    /// belongs in [`push_alert`](Self::push_alert), which survives
192    /// repopulation and is pruned by reassembly/compaction instead.
193    pub fn insert_reminder<T: Serialize>(&mut self, value: &T) {
194        let tag = snake_case_type_name::<T>();
195        let xml = serialize_xml(&tag, value);
196        self.runtime_items
197            .push(ContextCheckpointItem::Reminder(xml));
198    }
199
200    /// Pushes a durable system alert, rendered like a reminder.
201    ///
202    /// The alert enters the conversation stream as a `system` message and
203    /// stays there until reassembly or compaction prunes system alerts — the
204    /// channel to use for content that must reach the next request rather
205    /// than being regenerated by reminder repopulation.
206    pub fn push_alert<T: Serialize>(&mut self, value: &T) {
207        let tag = snake_case_type_name::<T>();
208        let xml = serialize_xml(&tag, value);
209        self.push(Message::system(xml));
210    }
211
212    /// Clears all ephemeral reminders.
213    pub fn clear_reminders(&mut self) {
214        self.runtime_items
215            .retain(|item| !matches!(item, ContextCheckpointItem::Reminder(_)));
216    }
217
218    /// Returns current reminders.
219    #[must_use]
220    pub fn reminders(&self) -> Vec<&str> {
221        self.runtime_items
222            .iter()
223            .filter_map(|item| match item {
224                ContextCheckpointItem::Reminder(content) => Some(content.as_str()),
225                ContextCheckpointItem::Message(_) => None,
226            })
227            .collect()
228    }
229
230    // ── Handoff ───────────────────────────────────────────────────────
231
232    /// Sets or replaces the compaction handoff document.
233    pub fn set_handoff(&mut self, handoff: impl Into<String>) {
234        let handoff = handoff.into();
235        self.handoff = Some(serialize_xml("handoff", &TextBlock { content: &handoff }));
236    }
237
238    /// Sets the compaction handoff document from a structured handoff artifact.
239    pub fn set_handoff_document(&mut self, handoff: &HandoffDocument) {
240        self.handoff = Some(serialize_xml("handoff", handoff));
241    }
242
243    /// Clears the compaction handoff document.
244    pub fn clear_handoff(&mut self) {
245        self.handoff = None;
246    }
247
248    /// Returns the current compaction handoff document.
249    #[must_use]
250    pub fn handoff(&self) -> Option<&str> {
251        self.handoff.as_deref()
252    }
253
254    // ── Recent conversation ───────────────────────────────────────────
255
256    /// Appends a message to recent conversation.
257    pub fn push(&mut self, message: Message) {
258        self.runtime_items
259            .push(ContextCheckpointItem::Message(message));
260    }
261
262    /// Extends recent conversation with multiple messages.
263    pub fn extend(&mut self, messages: impl IntoIterator<Item = Message>) {
264        self.runtime_items
265            .extend(messages.into_iter().map(ContextCheckpointItem::Message));
266    }
267
268    /// Returns number of recent conversation messages.
269    #[must_use]
270    pub fn len_recent(&self) -> usize {
271        self.runtime_items
272            .iter()
273            .filter(|item| matches!(item, ContextCheckpointItem::Message(_)))
274            .count()
275    }
276
277    /// Returns the number of recent system messages.
278    #[must_use]
279    pub fn count_recent_system_messages(&self) -> usize {
280        self.runtime_items
281            .iter()
282            .filter(|item| {
283                matches!(
284                    item,
285                    ContextCheckpointItem::Message(message) if message.role() == Role::System
286                )
287            })
288            .count()
289    }
290
291    /// Returns recent conversation messages.
292    #[must_use]
293    pub fn recent(&self) -> Vec<&Message> {
294        self.runtime_items
295            .iter()
296            .filter_map(|item| match item {
297                ContextCheckpointItem::Reminder(_) => None,
298                ContextCheckpointItem::Message(message) => Some(message),
299            })
300            .collect()
301    }
302
303    /// Returns the latest recent message.
304    #[must_use]
305    pub fn last(&self) -> Option<&Message> {
306        self.runtime_items.iter().rev().find_map(|item| match item {
307            ContextCheckpointItem::Reminder(_) => None,
308            ContextCheckpointItem::Message(message) => Some(message),
309        })
310    }
311
312    /// Returns whether recent conversation is empty.
313    #[must_use]
314    pub fn is_conversation_empty(&self) -> bool {
315        self.len_recent() == 0
316    }
317
318    /// Drains oldest recent messages while keeping the latest `keep` messages.
319    pub fn drain_oldest(&mut self, keep: usize) -> Vec<Message> {
320        let remove_count = self.len_recent().saturating_sub(keep);
321        if remove_count == 0 {
322            return Vec::new();
323        }
324        let mut removed = Vec::with_capacity(remove_count);
325        let mut removed_messages = 0usize;
326        let mut retained = Vec::with_capacity(self.runtime_items.len());
327        for item in self.runtime_items.drain(..) {
328            match item {
329                ContextCheckpointItem::Message(message) if removed_messages < remove_count => {
330                    removed.push(message);
331                    removed_messages += 1;
332                }
333                other => retained.push(other),
334            }
335        }
336        self.runtime_items = retained;
337        removed
338    }
339
340    /// Returns recent conversation messages cloned.
341    #[must_use]
342    pub fn conversation_messages(&self) -> Vec<Message> {
343        self.runtime_items
344            .iter()
345            .filter_map(|item| match item {
346                ContextCheckpointItem::Reminder(_) => None,
347                ContextCheckpointItem::Message(message) => Some(message.clone()),
348            })
349            .collect()
350    }
351
352    // ── Message assembly ───────────────────────────────────────────────
353
354    /// Builds the full LLM message list.
355    ///
356    /// Layout:
357    /// 1. Persistent system blocks (single cacheable prefix)
358    /// 2. Compaction handoff (optional system message)
359    /// 3. Ordered runtime items (reminders and conversation messages)
360    #[must_use]
361    pub fn build_messages(&self) -> Vec<Message> {
362        let mut messages = Vec::new();
363
364        if !self.system_blocks.is_empty() {
365            let system_xml = self
366                .system_blocks
367                .values()
368                .cloned()
369                .collect::<Vec<_>>()
370                .join("\n");
371            messages.push(Message::system(system_xml));
372        }
373
374        if let Some(handoff) = &self.handoff {
375            messages.push(Message::system(handoff));
376        }
377
378        messages.extend(self.runtime_items.iter().cloned().map(|item| match item {
379            ContextCheckpointItem::Reminder(content) => Message::system(content),
380            ContextCheckpointItem::Message(message) => message,
381        }));
382        messages
383    }
384
385    // ── Lifecycle ─────────────────────────────────────────────────────
386
387    /// Clears only recent conversation messages.
388    pub fn clear_recent(&mut self) {
389        self.runtime_items
390            .retain(|item| !matches!(item, ContextCheckpointItem::Message(_)));
391    }
392
393    /// Clears all non-persistent context: reminders, handoff, recent conversation.
394    pub fn clear_history(&mut self) {
395        self.handoff = None;
396        self.runtime_items.clear();
397    }
398
399    /// Clears everything, including persistent system blocks.
400    pub fn clear_all(&mut self) {
401        self.system_blocks.clear();
402        self.clear_history();
403    }
404
405    /// Clones the context.
406    #[must_use]
407    pub fn fork(&self) -> Self {
408        self.clone()
409    }
410
411    /// Creates a checkpoint that can be restored later.
412    #[must_use]
413    pub fn checkpoint(&self) -> ContextCheckpoint {
414        ContextCheckpoint {
415            handoff: self.handoff.clone(),
416            items: self.runtime_items.clone(),
417        }
418    }
419
420    /// Restores reminders, handoff, and recent conversation from checkpoint.
421    pub fn restore(&mut self, checkpoint: ContextCheckpoint) {
422        self.handoff = checkpoint.handoff;
423        self.runtime_items = checkpoint.items;
424    }
425
426    // ── Staged system block updates ───────────────────────────────────
427
428    /// Stages a replacement for a system block, deferring the cache-invalidating
429    /// rewrite until the next [`reassemble`](Self::reassemble).
430    ///
431    /// If no block with `tag` exists yet, the content is inserted immediately
432    /// (nothing to preserve in the cache) and `false` is returned. Otherwise the
433    /// update is staged and `true` is returned; the host should surface the
434    /// change to the model as an appended diff alert.
435    pub fn stage_system_text(
436        &mut self,
437        tag: impl Into<String>,
438        content: impl Into<String>,
439    ) -> bool {
440        let tag = tag.into();
441        let content = content.into();
442        if let Some(existing) = self.system_blocks.get(&tag) {
443            if *existing == content {
444                self.staged_system_updates.shift_remove(&tag);
445                return false;
446            }
447            self.staged_system_updates.insert(tag, content);
448            true
449        } else {
450            self.system_blocks.insert(tag, content);
451            false
452        }
453    }
454
455    /// Returns the staged replacement for `tag`, if any.
456    #[must_use]
457    pub fn staged_system_update(&self, tag: &str) -> Option<&str> {
458        self.staged_system_updates.get(tag).map(String::as_str)
459    }
460
461    // ── Reassembly (lightweight, non-LLM context rewrite) ────────────
462
463    /// Performs a lightweight context reassembly.
464    ///
465    /// This rewrites the window without calling any LLM:
466    /// 1. folds staged system block updates into the stable prefix,
467    /// 2. clears all ephemeral reminders,
468    /// 3. removes recent system messages (system alerts),
469    /// 4. tombstones tool results superseded by a later identical call or an
470    ///    identical later result.
471    ///
472    /// Reassembly invalidates the KV-cache prefix, so hosts should run it when
473    /// the cache is already cold (idle gap) or right before compaction.
474    pub fn reassemble(&mut self) -> ReassemblyReport {
475        let mut report = ReassemblyReport::default();
476
477        for (tag, content) in std::mem::take(&mut self.staged_system_updates) {
478            if let Some(existing) = self.system_blocks.get_mut(&tag) {
479                report.bytes_freed += existing.len().saturating_sub(content.len());
480                *existing = content;
481            } else {
482                self.system_blocks.insert(tag, content);
483            }
484            report.staged_updates_applied += 1;
485        }
486
487        let mut removed_bytes = 0usize;
488        let mut reminders_cleared = 0usize;
489        let mut system_messages_pruned = 0usize;
490        self.runtime_items.retain(|item| match item {
491            ContextCheckpointItem::Reminder(content) => {
492                reminders_cleared += 1;
493                removed_bytes += content.len();
494                false
495            }
496            ContextCheckpointItem::Message(message) if message.role() == Role::System => {
497                system_messages_pruned += 1;
498                removed_bytes += message.content().len();
499                false
500            }
501            ContextCheckpointItem::Message(_) => true,
502        });
503        report.reminders_cleared = reminders_cleared;
504        report.system_messages_pruned = system_messages_pruned;
505        report.bytes_freed += removed_bytes;
506
507        let (deduped, dedupe_bytes) = self.tombstone_superseded_tool_results();
508        report.tool_results_deduped = deduped;
509        report.bytes_freed += dedupe_bytes;
510
511        report
512    }
513
514    /// Estimates how many bytes a [`reassemble`](Self::reassemble) would free,
515    /// without mutating the context.
516    #[must_use]
517    pub fn estimate_reassembly_savings(&self) -> usize {
518        let alerts: usize = self
519            .runtime_items
520            .iter()
521            .map(|item| match item {
522                ContextCheckpointItem::Reminder(content) => content.len(),
523                ContextCheckpointItem::Message(message) if message.role() == Role::System => {
524                    message.content().len()
525                }
526                ContextCheckpointItem::Message(_) => 0,
527            })
528            .sum();
529        let (_, dedupe_bytes) = self.find_superseded_tool_results();
530        alerts + dedupe_bytes
531    }
532
533    /// Identifies tool results superseded by a later identical call (same tool
534    /// name and arguments) or an identical later result.
535    ///
536    /// Returns the indices to tombstone and the bytes that doing so would free.
537    fn find_superseded_tool_results(&self) -> (Vec<usize>, usize) {
538        use std::collections::HashMap;
539
540        // Map call id → identity key of (tool name, canonical arguments).
541        let mut call_identity: HashMap<&str, String> = HashMap::new();
542        for item in &self.runtime_items {
543            let ContextCheckpointItem::Message(message) = item else {
544                continue;
545            };
546            for call in message.tool_calls() {
547                call_identity.insert(
548                    call.id.as_str(),
549                    format!("{}\u{0}{}", call.name, call.arguments),
550                );
551            }
552        }
553
554        // Last occurrence per identity key and per exact result content.
555        let mut last_by_call: HashMap<&str, usize> = HashMap::new();
556        let mut last_by_content: HashMap<&str, usize> = HashMap::new();
557        for (index, item) in self.runtime_items.iter().enumerate() {
558            let ContextCheckpointItem::Message(Message::Tool {
559                content,
560                tool_call_id,
561            }) = item
562            else {
563                continue;
564            };
565            if let Some(identity) = call_identity.get(tool_call_id.as_str()) {
566                last_by_call.insert(identity.as_str(), index);
567            }
568            last_by_content.insert(content.as_str(), index);
569        }
570
571        let mut indices = Vec::new();
572        let mut bytes = 0usize;
573        for (index, item) in self.runtime_items.iter().enumerate() {
574            let ContextCheckpointItem::Message(Message::Tool {
575                content,
576                tool_call_id,
577            }) = item
578            else {
579                continue;
580            };
581            if content.len() <= SUPERSEDED_TOOL_RESULT.len() {
582                continue;
583            }
584            let superseded_by_call = call_identity
585                .get(tool_call_id.as_str())
586                .and_then(|identity| last_by_call.get(identity.as_str()))
587                .is_some_and(|&last| last > index);
588            let superseded_by_content = last_by_content
589                .get(content.as_str())
590                .is_some_and(|&last| last > index);
591            if superseded_by_call || superseded_by_content {
592                indices.push(index);
593                bytes += content.len() - SUPERSEDED_TOOL_RESULT.len();
594            }
595        }
596        (indices, bytes)
597    }
598
599    /// Applies [`find_superseded_tool_results`](Self::find_superseded_tool_results).
600    fn tombstone_superseded_tool_results(&mut self) -> (usize, usize) {
601        let (indices, bytes) = self.find_superseded_tool_results();
602        for &index in &indices {
603            if let Some(ContextCheckpointItem::Message(Message::Tool { content, .. })) =
604                self.runtime_items.get_mut(index)
605            {
606                *content = SUPERSEDED_TOOL_RESULT.to_string();
607            }
608        }
609        (indices.len(), bytes)
610    }
611
612    /// Removes recent system messages and returns how many were pruned.
613    pub fn prune_recent_system_messages(&mut self) -> usize {
614        let before = self.len_recent();
615        self.runtime_items.retain(|item| {
616            !matches!(
617                item,
618                ContextCheckpointItem::Message(message) if message.role() == Role::System
619            )
620        });
621        before - self.len_recent()
622    }
623
624    /// Restores runtime-managed state from another serialized context while
625    /// preserving the current persistent system blocks.
626    pub fn restore_runtime_state(&mut self, restored: Self) {
627        self.handoff = restored.handoff;
628        self.runtime_items = restored.runtime_items;
629    }
630}
631
632/// A snapshot of non-persistent context state that can be restored.
633#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
634pub struct ContextCheckpoint {
635    handoff: Option<String>,
636    items: Vec<ContextCheckpointItem>,
637}
638
639impl ContextCheckpoint {
640    /// Creates a structured runtime checkpoint.
641    #[must_use]
642    pub const fn new(handoff: Option<String>, items: Vec<ContextCheckpointItem>) -> Self {
643        Self { handoff, items }
644    }
645
646    /// Returns the number of recent messages in this checkpoint.
647    #[must_use]
648    pub fn len_recent(&self) -> usize {
649        self.items
650            .iter()
651            .filter(|item| matches!(item, ContextCheckpointItem::Message(_)))
652            .count()
653    }
654
655    /// Returns the current handoff document, if present.
656    #[must_use]
657    pub fn handoff(&self) -> Option<&str> {
658        self.handoff.as_deref()
659    }
660
661    /// Returns ordered runtime checkpoint items.
662    #[must_use]
663    pub fn items(&self) -> &[ContextCheckpointItem] {
664        &self.items
665    }
666
667    /// Returns whether this checkpoint has no handoff and no runtime items.
668    #[must_use]
669    pub const fn is_empty(&self) -> bool {
670        self.handoff.is_none() && self.items.is_empty()
671    }
672}
673
674// ── Helpers ───────────────────────────────────────────────────────────
675
676fn snake_case_type_name<T>() -> String {
677    let full = std::any::type_name::<T>();
678    let short = full.rsplit("::").next().unwrap_or(full);
679    heck::AsSnakeCase(short).to_string()
680}
681
682pub fn serialize_xml<T: Serialize>(tag: &str, value: &T) -> String {
683    let mut buffer = String::new();
684    let serializer = quick_xml::se::Serializer::with_root(&mut buffer, Some(tag))
685        .unwrap_or_else(|error| panic!("failed to create XML serializer for tag '{tag}': {error}"));
686
687    value
688        .serialize(serializer)
689        .unwrap_or_else(|error| panic!("failed to serialize XML for tag '{tag}': {error}"));
690
691    buffer
692}
693
694#[cfg(test)]
695mod tests {
696    use super::*;
697
698    #[derive(Serialize)]
699    struct Memory {
700        #[serde(rename = "$text")]
701        content: String,
702    }
703
704    #[derive(Serialize)]
705    struct Reminder {
706        #[serde(rename = "$text")]
707        content: String,
708    }
709
710    #[derive(Serialize)]
711    struct Workspace {
712        sandbox: String,
713        cwd: String,
714    }
715
716    #[test]
717    fn snake_case_type_name_uses_short_struct_name() {
718        assert_eq!(snake_case_type_name::<Memory>(), "memory");
719    }
720
721    #[test]
722    fn serialize_xml_renders_text_content() {
723        let xml = serialize_xml(
724            "memory",
725            &Memory {
726                content: "remember this".to_string(),
727            },
728        );
729        assert!(xml.contains("<memory>"));
730        assert!(xml.contains("remember this"));
731        assert!(xml.contains("</memory>"));
732    }
733
734    #[test]
735    fn serialize_xml_renders_struct_fields() {
736        let xml = serialize_xml(
737            "workspace",
738            &Workspace {
739                sandbox: "/tmp/sandbox".to_string(),
740                cwd: "/home/user".to_string(),
741            },
742        );
743        assert!(xml.contains("<workspace>"));
744        assert!(xml.contains("<sandbox>"));
745        assert!(xml.contains("/tmp/sandbox"));
746        assert!(xml.contains("</workspace>"));
747    }
748
749    #[test]
750    fn insert_system_text_stores_raw_content() {
751        let mut context = Context::new();
752        context.insert_system_text("workspace", "Environment: local\nCWD: /tmp");
753
754        assert_eq!(context.system_block_count(), 1);
755        let messages = context.build_messages();
756        assert_eq!(messages.len(), 1);
757        let rendered = messages[0].content();
758        assert!(rendered.contains("Environment: local"));
759        assert!(rendered.contains("CWD: /tmp"));
760        assert!(
761            !rendered.contains("<workspace>"),
762            "insert_system_text must not add XML tags: {rendered}"
763        );
764    }
765
766    #[test]
767    fn insert_system_text_replaces_by_tag() {
768        let mut context = Context::new();
769        context.insert_system_text("workspace", "old");
770        context.insert_system_text("workspace", "new");
771
772        assert_eq!(context.system_block_count(), 1);
773        let messages = context.build_messages();
774        assert!(messages[0].content().contains("new"));
775        assert!(!messages[0].content().contains("old"));
776    }
777
778    #[test]
779    fn stable_prefix_fingerprint_reflects_block_changes() {
780        let mut context = Context::new();
781        let empty = context.stable_prefix_fingerprint();
782
783        context.insert_system_text("workspace", "a");
784        let after_insert = context.stable_prefix_fingerprint();
785        assert_ne!(empty, after_insert);
786
787        context.insert_system_text("workspace", "b");
788        let after_edit = context.stable_prefix_fingerprint();
789        assert_ne!(after_insert, after_edit);
790
791        context.remove_system_named("workspace");
792        assert_eq!(context.stable_prefix_fingerprint(), empty);
793    }
794
795    #[test]
796    fn stable_prefix_fingerprint_is_order_sensitive() {
797        let mut a = Context::new();
798        a.insert_system_text("one", "1");
799        a.insert_system_text("two", "2");
800
801        let mut b = Context::new();
802        b.insert_system_text("two", "2");
803        b.insert_system_text("one", "1");
804
805        assert_ne!(
806            a.stable_prefix_fingerprint(),
807            b.stable_prefix_fingerprint(),
808            "insertion order must be part of the fingerprint to reflect KV-cache prefix stability"
809        );
810    }
811
812    #[test]
813    fn insert_system_replaces_existing_block() {
814        let mut context = Context::new();
815        context.insert_system(&Memory {
816            content: "old".to_string(),
817        });
818        context.insert_system(&Memory {
819            content: "new".to_string(),
820        });
821
822        assert_eq!(context.system_block_count(), 1);
823        let messages = context.build_messages();
824        assert_eq!(messages.len(), 1);
825        assert!(messages[0].content().contains("new"));
826        assert!(!messages[0].content().contains("old"));
827    }
828
829    #[test]
830    fn build_messages_has_expected_layout() {
831        let mut context = Context::new();
832        context.insert_system(&Memory {
833            content: "base".to_string(),
834        });
835        context.insert_reminder(&Reminder {
836            content: "todo".to_string(),
837        });
838        context.set_handoff("summary");
839        context.push(Message::user("hello"));
840
841        let messages = context.build_messages();
842        assert_eq!(messages.len(), 4);
843        assert!(messages[0].content().contains("base"));
844        assert!(messages[1].content().contains("handoff"));
845        assert!(messages[2].content().contains("todo"));
846        assert!(messages[3].content().contains("hello"));
847    }
848
849    #[test]
850    fn clear_history_preserves_system_blocks() {
851        let mut context = Context::new();
852        context.insert_system(&Memory {
853            content: "persist".to_string(),
854        });
855        context.insert_reminder(&Reminder {
856            content: "ephemeral".to_string(),
857        });
858        context.set_handoff("summary");
859        context.push(Message::assistant("recent"));
860
861        context.clear_history();
862
863        assert_eq!(context.system_block_count(), 1);
864        assert_eq!(context.reminders(), Vec::<&str>::new());
865        assert!(context.handoff().is_none());
866        assert_eq!(context.len_recent(), 0);
867    }
868
869    #[test]
870    fn checkpoint_restore_roundtrip() {
871        let mut context = Context::new();
872        context.insert_reminder(&Reminder {
873            content: "before".to_string(),
874        });
875        context.set_handoff("before");
876        context.push(Message::user("first"));
877
878        let checkpoint = context.checkpoint();
879
880        context.clear_history();
881        context.insert_reminder(&Reminder {
882            content: "after".to_string(),
883        });
884        context.push(Message::user("second"));
885
886        context.restore(checkpoint);
887
888        assert_eq!(context.reminders().len(), 1);
889        assert!(context.handoff().is_some());
890        assert_eq!(context.len_recent(), 1);
891        assert_eq!(context.recent()[0].content(), "first");
892    }
893
894    #[test]
895    fn restore_runtime_state_preserves_system_blocks() {
896        let mut current = Context::new();
897        current.insert_system(&Memory {
898            content: "fresh".to_string(),
899        });
900
901        let mut restored = Context::new();
902        restored.insert_system(&Memory {
903            content: "stale".to_string(),
904        });
905        restored.insert_reminder(&Reminder {
906            content: "ephemeral".to_string(),
907        });
908        restored.set_handoff("summary");
909        restored.push(Message::user("hello"));
910
911        current.restore_runtime_state(restored);
912
913        let messages = current.build_messages();
914        assert!(messages[0].content().contains("fresh"));
915        assert!(!messages[0].content().contains("stale"));
916        assert_eq!(current.reminders().len(), 1);
917        assert!(current.handoff().is_some());
918        assert_eq!(current.len_recent(), 1);
919    }
920
921    #[test]
922    fn prune_recent_system_messages_removes_only_system_entries() {
923        let mut context = Context::new();
924        context.push(Message::user("user"));
925        context.push(Message::system("system"));
926        context.push(Message::assistant("assistant"));
927        context.push(Message::system("system-2"));
928
929        let removed = context.prune_recent_system_messages();
930
931        assert_eq!(removed, 2);
932        assert_eq!(context.len_recent(), 2);
933        assert_eq!(context.recent()[0].content(), "user");
934        assert_eq!(context.recent()[1].content(), "assistant");
935    }
936
937    #[test]
938    fn stage_system_text_defers_existing_block_rewrite() {
939        let mut context = Context::new();
940        context.insert_system_text("memory", "v1");
941
942        assert!(context.stage_system_text("memory", "v2"));
943        // The live block is untouched until reassembly (cache-friendly).
944        assert!(context.build_messages()[0].content().contains("v1"));
945        assert_eq!(context.staged_system_update("memory"), Some("v2"));
946
947        let report = context.reassemble();
948        assert_eq!(report.staged_updates_applied, 1);
949        assert!(context.build_messages()[0].content().contains("v2"));
950        assert_eq!(context.staged_system_update("memory"), None);
951    }
952
953    #[test]
954    fn stage_system_text_inserts_directly_when_block_missing() {
955        let mut context = Context::new();
956        assert!(!context.stage_system_text("memory", "fresh"));
957        assert!(context.build_messages()[0].content().contains("fresh"));
958    }
959
960    #[test]
961    fn reassemble_clears_alerts_and_tombstones_superseded_results() {
962        use aither_core::llm::ToolCall;
963
964        let mut context = Context::new();
965        context.insert_reminder(&Reminder {
966            content: "alert".to_string(),
967        });
968        context.push(Message::system("system alert"));
969
970        let args = serde_json::json!({"script": "cat skills/slide/SKILL.md"});
971        let long_result = "the full skill document ".repeat(20);
972        context.push(Message::assistant_with_tool_calls(
973            "",
974            vec![ToolCall::new("call_1", "terminal", args.clone())],
975        ));
976        context.push(Message::tool("call_1", long_result.clone()));
977        context.push(Message::assistant_with_tool_calls(
978            "",
979            vec![ToolCall::new("call_2", "terminal", args)],
980        ));
981        context.push(Message::tool("call_2", long_result.clone()));
982
983        let estimated = context.estimate_reassembly_savings();
984        assert!(estimated > 0);
985
986        let report = context.reassemble();
987        assert_eq!(report.reminders_cleared, 1);
988        assert_eq!(report.system_messages_pruned, 1);
989        assert_eq!(report.tool_results_deduped, 1);
990        assert_eq!(report.bytes_freed, estimated);
991
992        let recent = context.recent();
993        // First (superseded) result is tombstoned; the latest keeps full content.
994        assert!(recent[1].content().contains("superseded"));
995        assert_eq!(recent[3].content(), long_result);
996    }
997
998    #[test]
999    fn reassemble_tombstones_identical_result_content_across_different_calls() {
1000        use aither_core::llm::ToolCall;
1001
1002        let mut context = Context::new();
1003        let duplicated = "identical output body ".repeat(10);
1004        context.push(Message::assistant_with_tool_calls(
1005            "",
1006            vec![ToolCall::new(
1007                "call_1",
1008                "terminal",
1009                serde_json::json!({"script": "cat a.txt"}),
1010            )],
1011        ));
1012        context.push(Message::tool("call_1", duplicated.clone()));
1013        context.push(Message::assistant_with_tool_calls(
1014            "",
1015            vec![ToolCall::new(
1016                "call_2",
1017                "terminal",
1018                serde_json::json!({"script": "sed -n 1,200p a.txt"}),
1019            )],
1020        ));
1021        context.push(Message::tool("call_2", duplicated.clone()));
1022
1023        let report = context.reassemble();
1024        assert_eq!(report.tool_results_deduped, 1);
1025        let recent = context.recent();
1026        assert!(recent[1].content().contains("superseded"));
1027        assert_eq!(recent[3].content(), duplicated);
1028    }
1029
1030    #[test]
1031    fn serde_roundtrip_preserves_message_layout() {
1032        let mut context = Context::new();
1033        context.insert_system(&Memory {
1034            content: "persist".to_string(),
1035        });
1036        context.insert_reminder(&Reminder {
1037            content: "ephemeral".to_string(),
1038        });
1039        context.set_handoff("summary");
1040        context.push(Message::user("hello"));
1041        context.push(Message::assistant("world"));
1042
1043        let expected_messages = context.build_messages();
1044        let encoded = serde_json::to_string(&context)
1045            .unwrap_or_else(|error| panic!("failed to serialize context: {error}"));
1046        let decoded: Context = serde_json::from_str(&encoded)
1047            .unwrap_or_else(|error| panic!("failed to deserialize context: {error}"));
1048        let actual_messages = decoded.build_messages();
1049
1050        assert_eq!(actual_messages, expected_messages);
1051    }
1052}