1use 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
41pub trait HandoffSchema: JsonSchema + DeserializeOwned + Send + 'static {
54 fn instruction(prompt: &HandoffPrompt<'_>) -> String;
57
58 fn retry(reason: &str) -> String;
61
62 fn validate(&self) -> Result<(), InvalidHandoff> {
69 Ok(())
70 }
71
72 fn render(&self, file_index: &[String]) -> String;
78
79 fn into_restoration(self) -> Restoration;
81}
82
83#[derive(Debug, Clone, Copy)]
85pub struct HandoffPrompt<'a> {
86 pub focus: Option<&'a str>,
89 pub skills: &'a [SkillCatalogEntry],
91 pub attachments: &'a [AttachmentCatalogEntry],
94}
95
96#[derive(Debug, Clone, Default, PartialEq, Eq)]
98pub struct Restoration {
99 pub context_files: Vec<ContextFile>,
101 pub skills: Vec<String>,
104 pub attachments: Vec<String>,
107}
108
109#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
111#[error("{reason}")]
112pub struct InvalidHandoff {
113 pub reason: String,
115}
116
117impl InvalidHandoff {
118 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
137pub struct HandoffDocument {
138 pub current_task: String,
140 pub key_decisions: Vec<String>,
142 #[serde(default)]
144 pub context_files: Vec<ContextFile>,
145 pub errors_fixes: Vec<String>,
147 pub pending_work: Vec<String>,
149 pub recovery_hints: Vec<String>,
151 #[serde(default)]
154 pub skills: Vec<String>,
155 #[serde(default)]
159 pub attachments: Vec<KeptAttachment>,
160}
161
162#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
164pub struct ContextFile {
165 pub path: String,
167 pub lines: Option<LineRange>,
170 pub why: String,
172}
173
174#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
177pub struct KeptAttachment {
178 pub id: String,
180 pub why: String,
182}
183
184#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
186pub struct LineRange {
187 pub start: u32,
189 pub end: u32,
191}
192
193#[derive(Debug, Clone, PartialEq, Eq)]
199pub struct SkillCatalogEntry {
200 pub name: String,
202 pub description: String,
204 pub instructions: String,
206}
207
208#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
213pub struct AttachmentRef {
214 pub seq: u64,
216 pub index: usize,
218}
219
220#[derive(Debug, Clone, PartialEq, Eq)]
227pub struct AttachmentCatalogEntry {
228 pub id: String,
230 pub media_type: String,
232 pub excerpt: String,
235 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 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 fn retry(reason: &str) -> String {
283 CompactionRetry { reason }
284 .render()
285 .expect("compaction retry template must render")
286 }
287
288 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 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#[derive(Debug, Clone, thiserror::Error)]
323pub enum CompactionError {
324 #[error("compaction request failed: {message}")]
326 Provider {
327 message: String,
329 failure: Failure,
331 },
332
333 #[error("compaction produced an invalid handoff document: {reason}")]
335 Invalid {
336 reason: String,
338 },
339
340 #[error("compaction found no conversation to summarize")]
342 Empty,
343}
344
345const INDEX_SEPARATOR: &str = " — ";
347
348#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
352pub struct Handoff {
353 text: String,
355 file_index: Vec<String>,
358}
359
360impl Handoff {
361 #[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 #[must_use]
372 pub const fn with_file_index(text: String, file_index: Vec<String>) -> Self {
373 Self { text, file_index }
374 }
375
376 #[must_use]
378 pub fn text(&self) -> &str {
379 &self.text
380 }
381
382 #[must_use]
384 pub fn file_index(&self) -> &[String] {
385 &self.file_index
386 }
387}
388
389pub trait FileReferences: Send + Sync + 'static {
395 fn files(&self, output: &str) -> Vec<String>;
398}
399
400#[derive(Clone)]
402pub struct AnyFileReferences(std::sync::Arc<dyn FileReferences>);
403
404impl AnyFileReferences {
405 #[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#[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
478pub struct CompactionFork<D> {
480 fork_point: u64,
482 previous_file_index: Vec<String>,
484 references: Option<AnyFileReferences>,
487 attachment_catalog: Vec<AttachmentCatalogEntry>,
491 request: LLMRequest,
496 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 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 #[must_use]
566 pub fn with_file_references(mut self, references: Option<AnyFileReferences>) -> Self {
567 self.references = references;
568 self
569 }
570
571 #[must_use]
573 pub const fn fork_point(&self) -> u64 {
574 self.fork_point
575 }
576
577 #[must_use]
579 pub const fn request(&self) -> &LLMRequest {
580 &self.request
581 }
582
583 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 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#[derive(Debug, Clone, PartialEq, Eq)]
678pub struct CompletedCompaction {
679 pub fork_point: u64,
681 pub handoff: Handoff,
683 pub restoration: Restoration,
685 pub attachment_catalog: Vec<AttachmentCatalogEntry>,
688}
689
690type CompactionFuture =
692 Pin<Box<dyn Future<Output = Result<CompletedCompaction, CompactionError>> + Send>>;
693
694pub struct PendingCompaction {
701 fork_point: u64,
702 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 #[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 #[must_use]
736 pub const fn fork_point(&self) -> u64 {
737 self.fork_point
738 }
739
740 pub fn wait(
742 &mut self,
743 ) -> impl Future<Output = Result<CompletedCompaction, CompactionError>> + '_ {
744 self.future.get_mut()
745 }
746}
747
748fn 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
768async 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 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 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 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 #[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 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 #[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}