1use std::path::PathBuf;
2
3use crate::core::config::CompressionLevel;
4use crate::core::graph_context;
5
6use super::paths::{
7 escape_xml_attr, file_stem_search_pattern, parent_dir_slash, sessions_dir, shorten_path,
8};
9use super::types::SessionState;
10
11fn session_context_tag(level: &CompressionLevel) -> Option<String> {
13 if !level.is_active() {
14 return None;
15 }
16 Some(format!("<config compression=\"{}\" />", level.label()))
17}
18
19fn resume_block_hint(level: &CompressionLevel) -> Option<String> {
21 match level {
22 CompressionLevel::Off => None,
23 CompressionLevel::Lite => Some(
24 "[COMPRESSION: lite] Keep responses concise. Bullet points, avoid filler.".to_string(),
25 ),
26 CompressionLevel::Standard => Some(
27 "[COMPRESSION: standard] Dense output. Atomic fact lines, abbreviations, diff-only code.".to_string(),
28 ),
29 CompressionLevel::Max | CompressionLevel::Raw => Some(
30 "[COMPRESSION: max] Expert-terse mode. Telegraph format, symbolic vocabulary, zero narration.".to_string(),
31 ),
32 }
33}
34
35impl SessionState {
36 pub fn format_compact(&self) -> String {
38 let duration = self.updated_at - self.started_at;
39 let hours = duration.num_hours();
40 let mins = duration.num_minutes() % 60;
41 let duration_str = if hours > 0 {
42 format!("{hours}h {mins}m")
43 } else {
44 format!("{mins}m")
45 };
46
47 let mut lines = Vec::new();
48 if self
49 .evidence
50 .iter()
51 .any(|item| item.key == "personal_context_copy")
52 {
53 lines.push("COPIED CONTEXT: historical user notes; not verified facts, execution approvals or source-access grants.".into());
54 }
55 if self.last_save_failed {
56 lines.push(
57 "PERSISTENCE FAILED: unsaved changes retained; resolve conflict or retry storage."
58 .into(),
59 );
60 }
61 lines.push(format!(
62 "SESSION v{} | {} | {} calls | {} tok saved",
63 self.version, duration_str, self.stats.total_tool_calls, self.stats.total_tokens_saved
64 ));
65
66 if let Some(ref task) = self.task {
67 let pct = task
68 .progress_pct
69 .map_or(String::new(), |p| format!(" [{p}%]"));
70 lines.push(format!("Task: {}{pct}", task.description));
71 }
72
73 if let Some(ref root) = self.project_root {
74 lines.push(format!("Root: {}", shorten_path(root)));
75 }
76
77 if !self.findings.is_empty() {
78 let items: Vec<String> = self
79 .findings
80 .iter()
81 .rev()
82 .take(5)
83 .map(|f| {
84 let loc = match (&f.file, f.line) {
85 (Some(file), Some(line)) => format!("{}:{line}", shorten_path(file)),
86 (Some(file), None) => shorten_path(file),
87 _ => String::new(),
88 };
89 if loc.is_empty() {
90 f.summary.clone()
91 } else {
92 format!("{loc} \u{2014} {}", f.summary)
93 }
94 })
95 .collect();
96 lines.push(format!(
97 "Findings ({}): {}",
98 self.findings.len(),
99 items.join(" | ")
100 ));
101 }
102
103 if !self.decisions.is_empty() {
104 let items: Vec<&str> = self
105 .decisions
106 .iter()
107 .rev()
108 .take(3)
109 .map(|d| d.summary.as_str())
110 .collect();
111 lines.push(format!("Decisions: {}", items.join(" | ")));
112 }
113
114 if !self.files_touched.is_empty() {
115 let items: Vec<String> = self
116 .files_touched
117 .iter()
118 .rev()
119 .take(10)
120 .map(|f| {
121 let status = if f.modified { "mod" } else { &f.last_mode };
122 let r = f.file_ref.as_deref().unwrap_or("?");
123 format!("[{r} {} {status}]", shorten_path(&f.path))
124 })
125 .collect();
126 lines.push(format!(
127 "Files ({}): {}",
128 self.files_touched.len(),
129 items.join(" ")
130 ));
131 }
132
133 if let Some(ref tests) = self.test_results {
134 lines.push(format!(
135 "Tests: {}/{} pass ({})",
136 tests.passed, tests.total, tests.command
137 ));
138 }
139
140 if !self.next_steps.is_empty() {
141 lines.push(format!("Next: {}", self.next_steps.join(" | ")));
142 }
143
144 let playbook_block = self.playbook.render(12);
148 if !playbook_block.is_empty() {
149 lines.push(playbook_block.trim_end().to_string());
150 }
151
152 lines.join("\n")
153 }
154
155 pub fn build_compaction_snapshot(&self) -> String {
157 const MAX_SNAPSHOT_BYTES: usize = 2048;
158
159 let mut sections: Vec<(u8, String)> = Vec::new();
160
161 let level = crate::core::config::CompressionLevel::from_str_label(&self.compression_level)
162 .unwrap_or_default();
163 if let Some(tag) = session_context_tag(&level) {
164 sections.push((0, tag));
165 }
166
167 if let Some(ref task) = self.task {
168 let pct = task
169 .progress_pct
170 .map_or(String::new(), |p| format!(" [{p}%]"));
171 sections.push((1, format!("<task>{}{pct}</task>", task.description)));
172 }
173
174 if !self.files_touched.is_empty() {
175 let modified: Vec<&str> = self
176 .files_touched
177 .iter()
178 .filter(|f| f.modified)
179 .map(|f| f.path.as_str())
180 .collect();
181 let read_only: Vec<&str> = self
182 .files_touched
183 .iter()
184 .filter(|f| !f.modified)
185 .take(10)
186 .map(|f| f.path.as_str())
187 .collect();
188 let mut files_section = String::new();
189 if !modified.is_empty() {
190 files_section.push_str(&format!("Modified: {}", modified.join(", ")));
191 }
192 if !read_only.is_empty() {
193 if !files_section.is_empty() {
194 files_section.push_str(" | ");
195 }
196 files_section.push_str(&format!("Read: {}", read_only.join(", ")));
197 }
198 sections.push((1, format!("<files>{files_section}</files>")));
199 }
200
201 if !self.decisions.is_empty() {
202 let items: Vec<&str> = self.decisions.iter().map(|d| d.summary.as_str()).collect();
203 sections.push((2, format!("<decisions>{}</decisions>", items.join(" | "))));
204 }
205
206 if !self.findings.is_empty() {
207 let items: Vec<String> = self
208 .findings
209 .iter()
210 .rev()
211 .take(5)
212 .map(|f| f.summary.clone())
213 .collect();
214 sections.push((2, format!("<findings>{}</findings>", items.join(" | "))));
215 }
216
217 if !self.progress.is_empty() {
218 let items: Vec<String> = self
219 .progress
220 .iter()
221 .rev()
222 .take(5)
223 .map(|p| {
224 let detail = p.detail.as_deref().unwrap_or("");
225 if detail.is_empty() {
226 p.action.clone()
227 } else {
228 format!("{}: {detail}", p.action)
229 }
230 })
231 .collect();
232 sections.push((2, format!("<progress>{}</progress>", items.join(" | "))));
233 }
234
235 if let Some(ref tests) = self.test_results {
236 sections.push((
237 3,
238 format!(
239 "<tests>{}/{} pass ({})</tests>",
240 tests.passed, tests.total, tests.command
241 ),
242 ));
243 }
244
245 if !self.next_steps.is_empty() {
246 sections.push((
247 3,
248 format!("<next_steps>{}</next_steps>", self.next_steps.join(" | ")),
249 ));
250 }
251
252 sections.push((
253 4,
254 format!(
255 "<stats>calls={} saved={}tok</stats>",
256 self.stats.total_tool_calls, self.stats.total_tokens_saved
257 ),
258 ));
259
260 sections.sort_by_key(|(priority, _)| *priority);
261
262 const SNAPSHOT_HARD_CAP: usize = 2200;
263 const CLOSE_TAG: &str = "</session_snapshot>";
264 let open_len = "<session_snapshot>\n".len();
265 let reserve_body = SNAPSHOT_HARD_CAP.saturating_sub(open_len + CLOSE_TAG.len());
266
267 let mut snapshot = String::from("<session_snapshot>\n");
268 for (_, section) in §ions {
269 if snapshot.len() + section.len() + 25 > MAX_SNAPSHOT_BYTES {
270 break;
271 }
272 snapshot.push_str(section);
273 snapshot.push('\n');
274 }
275
276 let used = snapshot.len().saturating_sub(open_len);
277 let suffix_budget = reserve_body.saturating_sub(used).saturating_sub(1);
278 if suffix_budget > 64 {
279 let suffix = self.build_compaction_structured_suffix(suffix_budget);
280 if !suffix.is_empty() {
281 snapshot.push_str(&suffix);
282 if !suffix.ends_with('\n') {
283 snapshot.push('\n');
284 }
285 }
286 }
287
288 snapshot.push_str(CLOSE_TAG);
289 snapshot
290 }
291
292 fn build_compaction_structured_suffix(&self, max_bytes: usize) -> String {
293 if max_bytes <= 64 {
294 return String::new();
295 }
296
297 let mut recovery_queries: Vec<String> = Vec::new();
298 for ft in self.files_touched.iter().rev().take(12) {
299 let path_esc = escape_xml_attr(&ft.path);
300 let mode = if ft.last_mode.is_empty() {
301 "map".to_string()
302 } else {
303 escape_xml_attr(&ft.last_mode)
304 };
305 recovery_queries.push(format!(
306 r#"<query tool="ctx_read" path="{path_esc}" mode="{mode}" />"#,
307 ));
308 let pattern = file_stem_search_pattern(&ft.path);
309 if !pattern.is_empty() {
310 let search_dir = parent_dir_slash(&ft.path);
311 let pat_esc = escape_xml_attr(&pattern);
312 let dir_esc = escape_xml_attr(&search_dir);
313 recovery_queries.push(format!(
314 r#"<query tool="ctx_search" pattern="{pat_esc}" path="{dir_esc}" />"#,
315 ));
316 }
317 }
318
319 let mut parts: Vec<String> = Vec::new();
320 if !recovery_queries.is_empty() {
321 parts.push(format!(
322 "<recovery_queries>\n{}\n</recovery_queries>",
323 recovery_queries.join("\n")
324 ));
325 }
326
327 let knowledge_ok = !self.findings.is_empty() || !self.decisions.is_empty();
328 if knowledge_ok && let Some(q) = self.knowledge_recall_query_stem() {
329 let q_esc = escape_xml_attr(&q);
330 parts.push(format!(
331 "<knowledge_context>\n<recall query=\"{q_esc}\" />\n</knowledge_context>",
332 ));
333 }
334
335 if let Some(root) = self
336 .project_root
337 .as_deref()
338 .filter(|r| !r.trim().is_empty())
339 {
340 let root_trim = root.trim_end_matches('/');
341 let mut cluster_lines: Vec<String> = Vec::new();
342 for ft in self.files_touched.iter().rev().take(3) {
343 let primary_esc = escape_xml_attr(&ft.path);
344 let abs_primary = format!("{root_trim}/{}", ft.path.trim_start_matches('/'));
345 let related_csv =
346 graph_context::build_related_paths_csv(&abs_primary, root_trim, 8)
347 .map(|s| escape_xml_attr(&s))
348 .unwrap_or_default();
349 if related_csv.is_empty() {
350 continue;
351 }
352 cluster_lines.push(format!(
353 r#"<cluster primary="{primary_esc}" related="{related_csv}" />"#,
354 ));
355 }
356 if !cluster_lines.is_empty() {
357 parts.push(format!(
358 "<graph_context>\n{}\n</graph_context>",
359 cluster_lines.join("\n")
360 ));
361 }
362 }
363
364 Self::shrink_structured_suffix_parts(&mut parts, max_bytes)
365 }
366
367 fn shrink_structured_suffix_parts(parts: &mut Vec<String>, max_bytes: usize) -> String {
368 let mut out = parts.join("\n");
369 while out.len() > max_bytes && !parts.is_empty() {
370 parts.pop();
371 out = parts.join("\n");
372 }
373 if out.len() <= max_bytes {
374 return out;
375 }
376 if let Some(idx) = parts
377 .iter()
378 .position(|p| p.starts_with("<recovery_queries>"))
379 {
380 let mut lines: Vec<String> = parts[idx]
381 .lines()
382 .filter(|l| l.starts_with("<query "))
383 .map(str::to_string)
384 .collect();
385 while !lines.is_empty() && out.len() > max_bytes {
386 if lines.len() == 1 {
387 parts.remove(idx);
388 out = parts.join("\n");
389 break;
390 }
391 lines.truncate(lines.len().saturating_sub(2));
392 parts[idx] = format!(
393 "<recovery_queries>\n{}\n</recovery_queries>",
394 lines.join("\n")
395 );
396 out = parts.join("\n");
397 }
398 }
399 if out.len() > max_bytes {
400 return String::new();
401 }
402 out
403 }
404
405 fn knowledge_recall_query_stem(&self) -> Option<String> {
406 let mut bits: Vec<String> = Vec::new();
407 if let Some(ref t) = self.task {
408 bits.push(Self::task_keyword_stem(&t.description));
409 }
410 if bits.iter().all(std::string::String::is_empty) {
411 if let Some(f) = self.findings.last() {
412 bits.push(Self::task_keyword_stem(&f.summary));
413 } else if let Some(d) = self.decisions.last() {
414 bits.push(Self::task_keyword_stem(&d.summary));
415 }
416 }
417 let q = bits.join(" ").trim().to_string();
418 if q.is_empty() { None } else { Some(q) }
419 }
420
421 fn task_keyword_stem(text: &str) -> String {
422 const STOP: &[&str] = &[
423 "the", "a", "an", "and", "or", "to", "for", "of", "in", "on", "with", "is", "are",
424 "be", "this", "that", "it", "as", "at", "by", "from",
425 ];
426 text.split_whitespace()
427 .filter_map(|w| {
428 let w = w.trim_matches(|c: char| !c.is_alphanumeric());
429 if w.len() < 3 {
430 return None;
431 }
432 let lower = w.to_lowercase();
433 if STOP.contains(&lower.as_str()) {
434 return None;
435 }
436 Some(w.to_string())
437 })
438 .take(8)
439 .collect::<Vec<_>>()
440 .join(" ")
441 }
442
443 pub fn save_compaction_snapshot(&self) -> Result<String, String> {
445 let snapshot = self.build_compaction_snapshot();
446 let dir = sessions_dir().ok_or("cannot determine home directory")?;
447 if !dir.exists() {
448 std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
449 }
450 let path = dir.join(format!("{}_snapshot.txt", self.id));
451 crate::core::atomic_fs::write_bytes_with_fallback(&path, snapshot.as_bytes(), None)?;
452 #[cfg(unix)]
453 {
454 use std::os::unix::fs::PermissionsExt;
455 let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
456 }
457 Ok(snapshot)
458 }
459
460 pub fn load_compaction_snapshot(session_id: &str) -> Option<String> {
462 let dir = sessions_dir()?;
463 let path = dir.join(format!("{session_id}_snapshot.txt"));
464 std::fs::read_to_string(&path).ok()
465 }
466
467 pub fn load_latest_snapshot() -> Option<String> {
473 let dir = sessions_dir()?;
474 let project_root = std::env::current_dir()
475 .ok()
476 .map(|p| p.to_string_lossy().to_string());
477
478 let mut snapshots: Vec<(std::time::SystemTime, PathBuf)> = std::fs::read_dir(&dir)
479 .ok()?
480 .filter_map(std::result::Result::ok)
481 .filter(|e| e.path().to_string_lossy().ends_with("_snapshot.txt"))
482 .filter_map(|e| {
483 let meta = e.metadata().ok()?;
484 let modified = meta.modified().ok()?;
485
486 if let Some(ref root) = project_root {
487 let content = std::fs::read_to_string(e.path()).ok()?;
488 if !content.contains(root) {
489 return None;
490 }
491 }
492
493 Some((modified, e.path()))
494 })
495 .collect();
496
497 snapshots.sort_by_key(|x| std::cmp::Reverse(x.0));
498 snapshots
499 .first()
500 .and_then(|(_, path)| std::fs::read_to_string(path).ok())
501 }
502
503 pub fn build_resume_block(&self) -> String {
506 let mut parts: Vec<String> = Vec::new();
507
508 let level = crate::core::config::CompressionLevel::from_str_label(&self.compression_level)
509 .unwrap_or_default();
510 if let Some(hint) = resume_block_hint(&level) {
511 parts.push(hint);
512 }
513
514 if let Some(ref root) = self.project_root {
515 let short = root.rsplit('/').next().unwrap_or(root);
516 parts.push(format!("Project: {short}"));
517 }
518
519 if let Some(ref task) = self.task {
520 let pct = task
521 .progress_pct
522 .map_or(String::new(), |p| format!(" [{p}%]"));
523 parts.push(format!("Task: {}{pct}", task.description));
524 }
525
526 if !self.decisions.is_empty() {
527 let items: Vec<&str> = self
528 .decisions
529 .iter()
530 .rev()
531 .take(5)
532 .map(|d| d.summary.as_str())
533 .collect();
534 parts.push(format!("Decisions: {}", items.join("; ")));
535 }
536
537 if !self.files_touched.is_empty() {
538 let modified: Vec<String> = self
539 .files_touched
540 .iter()
541 .filter(|f| f.modified)
542 .take(10)
543 .map(|f| {
544 f.summary
545 .as_deref()
546 .map_or_else(|| f.path.clone(), |s| format!("{} ({})", f.path, s))
547 })
548 .collect();
549 if !modified.is_empty() {
550 parts.push(format!("Modified: {}", modified.join(", ")));
551 }
552 }
553
554 if !self.findings.is_empty() {
555 let recent: Vec<&str> = self
556 .findings
557 .iter()
558 .rev()
559 .take(5)
560 .map(|f| f.summary.as_str())
561 .collect();
562 parts.push(format!("Key findings: {}", recent.join("; ")));
563 }
564
565 if !self.next_steps.is_empty() {
566 let steps: Vec<&str> = self
567 .next_steps
568 .iter()
569 .take(3)
570 .map(std::string::String::as_str)
571 .collect();
572 parts.push(format!("Next: {}", steps.join("; ")));
573 }
574
575 let archives = crate::core::archive::list_entries(Some(&self.id));
576 if !archives.is_empty() {
577 let hints: Vec<String> = archives
578 .iter()
579 .take(5)
580 .map(|a| format!("{}({})", a.id, a.tool))
581 .collect();
582 parts.push(format!("Archives: {}", hints.join(", ")));
583 }
584
585 parts.push(format!(
586 "Stats: {} calls, {} tok saved",
587 self.stats.total_tool_calls, self.stats.total_tokens_saved
588 ));
589
590 format!(
591 "--- SESSION RESUME (post-compaction) ---\n{}\n---",
592 parts.join("\n")
593 )
594 }
595}