1use askama::Template;
2use serde::{Deserialize, Serialize};
3
4use aither_core::llm::Message;
5
6#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8pub struct HandoffDocument {
9 pub current_task: String,
11 pub key_decisions: Vec<String>,
13 pub files_paths: Vec<String>,
15 pub errors_fixes: Vec<String>,
17 pub pending_work: Vec<String>,
19 pub recovery_hints: Vec<String>,
21 #[serde(default)]
29 pub file_index: Vec<String>,
30}
31
32#[must_use]
38pub fn build_file_index(messages: &[Message]) -> Vec<String> {
39 use std::collections::HashMap;
40
41 let mut call_description: HashMap<&str, &str> = HashMap::new();
42 for message in messages {
43 for call in message.tool_calls() {
44 if let Some(description) = call.arguments.get("description").and_then(|v| v.as_str()) {
45 call_description.insert(call.id.as_str(), description);
46 }
47 }
48 }
49
50 let mut index: indexmap::IndexMap<String, Option<&str>> = indexmap::IndexMap::new();
51 for message in messages {
52 let Message::Tool {
53 content,
54 tool_call_id,
55 } = message
56 else {
57 continue;
58 };
59 let description = call_description.get(tool_call_id.as_str()).copied();
60 for url in crate::compression::extract_referenced_urls(content) {
61 index.insert(url, description);
62 }
63 for word in content.split_whitespace() {
64 let word = word.trim_matches(|c: char| {
65 c == '"' || c == '\'' || c == '`' || c == ',' || c == ')' || c == ']' || c == ';'
66 });
67 if word.starts_with("artifacts/") && word.len() > "artifacts/".len() {
68 index.insert(word.to_string(), description);
69 }
70 }
71 }
72
73 index
74 .into_iter()
75 .map(|(path, description)| match description {
76 Some(description) => format!("{path} — {description}"),
77 None => path,
78 })
79 .collect()
80}
81
82#[derive(Template)]
83#[template(path = "handoff_document.md", escape = "none")]
84struct HandoffDocumentTemplate<'a> {
85 handoff: &'a HandoffDocument,
86}
87
88impl HandoffDocument {
89 pub fn validate(self) -> Result<Self, String> {
95 if self.current_task.trim().is_empty() {
96 return Err("handoff.current_task must not be empty".to_string());
97 }
98 Ok(self)
99 }
100
101 #[must_use]
107 pub fn render_markdown(&self) -> String {
108 HandoffDocumentTemplate { handoff: self }
109 .render()
110 .expect("handoff document template must render")
111 }
112}
113
114#[cfg(test)]
115mod tests {
116 use super::*;
117 use aither_core::llm::ToolCall;
118
119 #[test]
120 fn build_file_index_pairs_outputs_with_call_descriptions() {
121 let messages = vec![
122 Message::assistant_with_tool_calls(
123 "",
124 vec![ToolCall::new(
125 "call_1",
126 "terminal",
127 serde_json::json!({
128 "description": "Fetch WebGPU status pages",
129 "script": "webfetch https://caniuse.com"
130 }),
131 )],
132 ),
133 Message::tool(
134 "call_1",
135 "Output saved to outputs/amber-oak-swift-river.txt (100 lines, 5000 bytes)",
136 ),
137 Message::assistant_with_tool_calls(
138 "",
139 vec![ToolCall::new(
140 "call_2",
141 "terminal",
142 serde_json::json!({"description": "Write deck", "script": "tee artifacts/slides.md"}),
143 )],
144 ),
145 Message::tool("call_2", "wrote artifacts/slides.md"),
146 ];
147
148 let index = build_file_index(&messages);
149 assert_eq!(index.len(), 2);
150 assert!(
151 index[0].contains("outputs/amber-oak-swift-river.txt")
152 && index[0].contains("Fetch WebGPU status pages"),
153 "index entry should pair path with description: {index:?}"
154 );
155 assert!(index[1].contains("artifacts/slides.md") && index[1].contains("Write deck"));
156 }
157
158 #[test]
159 fn build_file_index_keeps_latest_description_per_path() {
160 let messages = vec![
161 Message::assistant_with_tool_calls(
162 "",
163 vec![ToolCall::new(
164 "call_1",
165 "terminal",
166 serde_json::json!({"description": "first pass"}),
167 )],
168 ),
169 Message::tool("call_1", "see artifacts/report.md"),
170 Message::assistant_with_tool_calls(
171 "",
172 vec![ToolCall::new(
173 "call_2",
174 "terminal",
175 serde_json::json!({"description": "final revision"}),
176 )],
177 ),
178 Message::tool("call_2", "updated artifacts/report.md"),
179 ];
180
181 let index = build_file_index(&messages);
182 assert_eq!(index.len(), 1);
183 assert!(index[0].contains("final revision"));
184 }
185
186 #[test]
187 fn handoff_markdown_renders_file_index_section() {
188 let handoff = HandoffDocument {
189 current_task: "task".to_string(),
190 key_decisions: Vec::new(),
191 files_paths: Vec::new(),
192 errors_fixes: Vec::new(),
193 pending_work: Vec::new(),
194 recovery_hints: Vec::new(),
195 file_index: vec!["outputs/a-b-c-d.txt — research notes".to_string()],
196 };
197 let markdown = handoff.render_markdown();
198 assert!(markdown.contains("Materials Already On Disk"));
199 assert!(markdown.contains("outputs/a-b-c-d.txt — research notes"));
200 assert!(markdown.contains("Read the file instead of redoing the work"));
201 }
202}