1use std::collections::HashMap;
9use std::fs;
10use std::path::{Path, PathBuf};
11
12use anyhow::Context;
13use chrono::Utc;
14use serde::{Deserialize, Serialize};
15use serde_json::{Value, json};
16use tokio::fs as async_fs;
17
18use vtcode_config::context::default_max_context_tokens;
19use vtcode_config::loader::VTCodeConfig;
20
21use crate::compaction::CompactionConfig;
22use crate::config::constants::tools as tool_names;
23use crate::context::history_files::{HistoryFileManager, messages_to_history_messages};
24use crate::core::agent::harness_artifacts::{
25 artifact_is_stale, current_evaluation_path, current_spec_path, current_task_path, read_evaluation_summary_fresh,
26 read_spec_summary_fresh, session_artifact_cutoff,
27};
28use crate::core::agent::steering::{
29 MAX_APPLIED_FOLLOW_UP_INTENT_IDS, MAX_PENDING_FOLLOW_UP_INTENTS, QueuedFollowUpIntent,
30};
31use crate::llm::provider::{LLMProvider, Message, MessageRole};
32use crate::llm::utils::truncate_to_token_limit;
33use crate::persistent_memory::{GroundedFactRecord, dedup_latest_facts, normalize_whitespace, truncate_for_fact};
34
35pub const MEMORY_ENVELOPE_HEADER: &str = "[Session Memory Envelope]";
36pub const MEMORY_ENVELOPE_SUFFIX: &str = ".memory.json";
37pub const SESSION_MEMORY_ENVELOPE_SCHEMA_VERSION: u32 = 3;
38pub const MEMORY_LIST_LIMIT: usize = 5;
39pub const APPLIED_INTENT_WINDOW: usize = MAX_APPLIED_FOLLOW_UP_INTENT_IDS;
40pub const DEDUPED_FILE_READ_NOTE: &str = "Older duplicate file read omitted during local compaction; a newer read of the same target slice is retained later in history.";
41
42mod persistence;
43#[cfg(test)]
44use persistence::{
45 collect_structured_verify_commands, extract_compaction_summary, extract_verification_summary,
46 parse_task_tracker_snapshot, split_verify_command_tail,
47};
48pub use persistence::{
49 configured_retained_user_messages, default_memory_envelope_path_for_session, has_latest_memory_envelope,
50 inject_latest_memory_envelope, insert_memory_envelope_message, latest_memory_envelope_path_for_session,
51 latest_memory_envelope_path_for_session_async, load_latest_memory_envelope, load_latest_memory_envelope_async,
52 local_compaction_config, memory_envelope_file_matches_session, persist_memory_envelope,
53 persist_memory_envelope_async, persist_memory_envelope_async_with_update, persist_memory_envelope_with_update,
54 read_task_tracker_snapshot, read_task_tracker_snapshot_async, sanitize_session_id, should_persist_memory_envelope,
55 strip_existing_memory_envelope, write_memory_envelope_to_path, write_memory_envelope_to_path_async,
56};
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum MemoryEnvelopePersistence {
60 PersistToDisk,
61 InMemoryOnly,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum MemoryEnvelopePlacement {
66 Start,
67 BeforeLastUserOrSummary,
68}
69
70#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
71pub struct SessionMemoryEnvelope {
72 #[serde(default)]
73 pub session_id: String,
74 #[serde(default)]
75 pub schema_version: Option<u32>,
76 pub summary: String,
77 #[serde(default)]
78 pub objective: Option<String>,
79 pub task_summary: Option<String>,
80 pub spec_summary: Option<String>,
81 pub evaluation_summary: Option<String>,
82 #[serde(default)]
83 pub verification_summary: Option<String>,
84 #[serde(default)]
85 pub constraints: Vec<String>,
86 pub grounded_facts: Vec<GroundedFactRecord>,
87 pub touched_files: Vec<String>,
88 #[serde(default)]
89 pub open_questions: Vec<String>,
90 #[serde(default)]
91 pub verification_todo: Vec<String>,
92 #[serde(default)]
93 pub delegation_notes: Vec<String>,
94 #[serde(default)]
97 pub pending_intents: Vec<QueuedFollowUpIntent>,
98 #[serde(default)]
101 pub applied_intent_ids: Vec<String>,
102 pub history_artifact_path: Option<String>,
103 pub generated_at: String,
104}
105
106impl SessionMemoryEnvelope {
107 pub fn is_content_equivalent_to(&self, other: &SessionMemoryEnvelope) -> bool {
111 self.session_id == other.session_id
112 && self.schema_version == other.schema_version
113 && self.summary == other.summary
114 && self.objective == other.objective
115 && self.task_summary == other.task_summary
116 && self.spec_summary == other.spec_summary
117 && self.evaluation_summary == other.evaluation_summary
118 && self.verification_summary == other.verification_summary
119 && self.constraints == other.constraints
120 && self.grounded_facts == other.grounded_facts
121 && self.touched_files == other.touched_files
122 && self.open_questions == other.open_questions
123 && self.verification_todo == other.verification_todo
124 && self.delegation_notes == other.delegation_notes
125 && self.pending_intents == other.pending_intents
126 && self.applied_intent_ids == other.applied_intent_ids
127 }
128}
129
130#[derive(Debug, Clone, Default, PartialEq, Eq)]
131pub struct SessionMemoryEnvelopeUpdate {
132 pub objective: Option<String>,
133 pub constraints: Vec<String>,
134 pub grounded_facts: Vec<GroundedFactRecord>,
135 pub touched_files: Vec<String>,
136 pub open_questions: Vec<String>,
137 pub verification_todo: Vec<String>,
138 pub delegation_notes: Vec<String>,
139 pub pending_intents: Option<Vec<QueuedFollowUpIntent>>,
141 pub applied_intent_ids: Vec<String>,
143}
144
145#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
146pub struct TaskTrackerSnapshot {
147 summary: Option<String>,
148 objective: Option<String>,
149 verification_summary: Option<String>,
150 verification_todo: Vec<String>,
151}
152
153fn merge_dedup_push<T, K, F>(prior: &[T], updates: impl IntoIterator<Item = T>, limit: usize, key_fn: F) -> Vec<T>
154where
155 K: PartialEq,
156 F: Fn(&T) -> K,
157 T: Clone,
158{
159 let mut merged = prior.to_vec();
160 for item in updates {
161 if let Some(idx) = merged.iter().position(|e| key_fn(e) == key_fn(&item)) {
162 merged.remove(idx);
163 }
164 merged.push(item);
165 }
166 let keep_from = merged.len().saturating_sub(limit);
167 merged.into_iter().skip(keep_from).collect()
168}
169
170fn merge_touched_files(prior_envelope: Option<&SessionMemoryEnvelope>, touched_files: &[String]) -> Vec<String> {
171 let prior = prior_envelope.map(|e| e.touched_files.as_slice()).unwrap_or(&[]);
172 merge_dedup_push(prior, touched_files.iter().cloned(), usize::MAX, |s| s.clone())
173}
174
175fn merge_recent_strings(prior: &[String], updates: &[String], limit: usize) -> Vec<String> {
176 let prior_normalized: Vec<_> = prior
177 .iter()
178 .map(|v| normalize_whitespace(v))
179 .filter(|v| !v.is_empty())
180 .collect();
181 let updates_normalized: Vec<_> = updates
182 .iter()
183 .map(|v| normalize_whitespace(v))
184 .filter(|v| !v.is_empty())
185 .collect();
186 merge_dedup_push(&prior_normalized, updates_normalized, limit, |s| s.to_ascii_lowercase())
187}
188
189fn merge_applied_intent_ids(prior: &[String], updates: &[String]) -> Vec<String> {
190 merge_dedup_push(prior, updates.iter().cloned(), APPLIED_INTENT_WINDOW, |id| id.clone())
191}
192
193fn extract_constraints_from_summary(text: Option<&str>) -> Vec<String> {
194 text.into_iter()
195 .flat_map(|value| value.split(" | "))
196 .map(normalize_whitespace)
197 .filter(|line| !line.is_empty())
198 .filter_map(|line| {
199 let line = line.as_str();
200 let line = match line.split_once(": ") {
204 Some((_, rest)) if rest.starts_with("- ") || rest.starts_with("* ") => rest,
205 _ => line,
206 };
207 if let Some(rest) = line.strip_prefix("- ") {
208 return Some(rest.trim().to_string());
209 }
210 line.strip_prefix("* ").map(|rest| rest.trim().to_string())
211 })
212 .take(MEMORY_LIST_LIMIT)
213 .collect()
214}
215
216pub fn derive_continuity_summary(
217 history: &[Message],
218 prior_envelope: Option<&SessionMemoryEnvelope>,
219 task_snapshot: &TaskTrackerSnapshot,
220) -> String {
221 let objective = task_snapshot
222 .objective
223 .as_deref()
224 .or_else(|| prior_envelope.and_then(|e| e.objective.as_deref()))
225 .filter(|s| !s.is_empty());
226
227 let latest = history
228 .iter()
229 .rev()
230 .filter(|message| message.role == MessageRole::User || message.role == MessageRole::Assistant)
231 .find_map(|message| {
232 let trimmed = normalize_whitespace(message.content.as_text().as_ref());
233 (!trimmed.is_empty()).then_some((message.role.as_generic_str(), truncate_for_fact(&trimmed, 140)))
234 });
235
236 match (objective, latest) {
237 (Some(obj), Some((role, text))) => {
238 format!("Working on: {obj}. Latest {role} action: {text}.")
239 }
240 (Some(obj), None) => format!("Working on: {obj}. Session continuity preserved."),
241 (None, Some((role, text))) => {
242 format!("Latest {role} action: {text}.")
243 }
244 (None, None) => prior_envelope
245 .map(|envelope| envelope.summary.clone())
246 .unwrap_or_else(|| "Session continuity facts preserved.".to_string()),
247 }
248}
249
250fn merge_grounded_facts(
251 prior_envelope: Option<&SessionMemoryEnvelope>,
252 original_history: &[Message],
253 updates: &[GroundedFactRecord],
254) -> Vec<GroundedFactRecord> {
255 let mut merged = prior_envelope
256 .map(|envelope| envelope.grounded_facts.clone())
257 .unwrap_or_default();
258
259 for fact in dedup_latest_facts(original_history, 5) {
260 let normalized = normalize_whitespace(&fact.fact).to_ascii_lowercase();
261 if let Some(existing_idx) = merged
262 .iter()
263 .position(|entry| normalize_whitespace(&entry.fact).to_ascii_lowercase() == normalized)
264 {
265 merged.remove(existing_idx);
266 }
267 merged.push(fact.clone());
268 }
269
270 for fact in updates {
271 let normalized = normalize_whitespace(&fact.fact).to_ascii_lowercase();
272 if let Some(existing_idx) = merged
273 .iter()
274 .position(|entry| normalize_whitespace(&entry.fact).to_ascii_lowercase() == normalized)
275 {
276 merged.remove(existing_idx);
277 }
278 merged.push(fact.clone());
279 }
280
281 let keep_from = merged.len().saturating_sub(5);
282 merged.into_iter().skip(keep_from).collect()
283}
284
285#[allow(
286 clippy::too_many_arguments,
287 reason = "Intentional compatibility, platform, or test-only suppression."
288)]
289#[must_use]
292pub fn build_session_memory_envelope(
293 session_id: &str,
294 workspace_root: &Path,
295 original_history: &[Message],
296 touched_files: &[String],
297 summary: String,
298 history_artifact_path: Option<&Path>,
299 prior_envelope: Option<&SessionMemoryEnvelope>,
300 task_snapshot: &TaskTrackerSnapshot,
301 envelope_update: Option<&SessionMemoryEnvelopeUpdate>,
302) -> SessionMemoryEnvelope {
303 let pe = prior_envelope;
304 let artifact_cutoff = session_artifact_cutoff(workspace_root, session_id);
305 let spec_present = current_spec_path(workspace_root).exists();
309 let evaluation_present = current_evaluation_path(workspace_root).exists();
310 let spec_summary = if spec_present {
311 read_spec_summary_fresh(workspace_root, artifact_cutoff)
312 } else {
313 pe.and_then(|e| e.spec_summary.clone())
314 };
315 let evaluation_summary = if evaluation_present {
316 read_evaluation_summary_fresh(workspace_root, artifact_cutoff)
317 } else {
318 pe.and_then(|e| e.evaluation_summary.clone())
319 };
320 let merge = |prior: &[String], updates: &[String]| merge_recent_strings(prior, updates, MEMORY_LIST_LIMIT);
321 let artifact_channel_reset = (spec_present
326 && artifact_is_stale(¤t_spec_path(workspace_root), artifact_cutoff))
327 || (evaluation_present && artifact_is_stale(¤t_evaluation_path(workspace_root), artifact_cutoff));
328 let prior_constraints: &[String] = if artifact_channel_reset {
329 &[]
330 } else {
331 pe.map(|e| e.constraints.as_slice()).unwrap_or(&[])
332 };
333 let constraints = merge(prior_constraints, &extract_constraints_from_summary(spec_summary.as_deref()));
334 let constraints = merge(&constraints, &extract_constraints_from_summary(evaluation_summary.as_deref()));
335 let update = envelope_update.cloned().unwrap_or_default();
336 let pending_intents = update
337 .pending_intents
338 .map(|intents| {
339 if intents.len() > MAX_PENDING_FOLLOW_UP_INTENTS {
340 tracing::warn!(
346 pending = intents.len(),
347 capacity = MAX_PENDING_FOLLOW_UP_INTENTS,
348 "pending follow-up intents exceed durable envelope capacity; dropping newest"
349 );
350 }
351 intents.into_iter().take(MAX_PENDING_FOLLOW_UP_INTENTS).collect()
352 })
353 .or_else(|| pe.map(|envelope| envelope.pending_intents.clone()))
354 .unwrap_or_default();
355 let applied_intent_ids = merge_applied_intent_ids(
356 pe.map(|envelope| envelope.applied_intent_ids.as_slice()).unwrap_or(&[]),
357 &update.applied_intent_ids,
358 );
359
360 let live_objective = task_snapshot.objective.as_deref().map(str::trim).filter(|s| !s.is_empty());
364 let prior_objective = pe.and_then(|e| e.objective.as_deref()).map(str::trim).filter(|s| !s.is_empty());
365 let objective_changed = match (live_objective, prior_objective) {
366 (Some(live), Some(prior)) => live != prior,
367 (Some(_), None) => true,
368 (None, Some(_)) => false,
369 (None, None) => false,
370 };
371
372 let objective = update
373 .objective
374 .or_else(|| live_objective.map(ToOwned::to_owned))
375 .or_else(|| pe.and_then(|e| e.objective.clone()));
376
377 let task_summary = if objective_changed {
378 task_snapshot.summary.clone().filter(|s| !s.trim().is_empty())
380 } else {
381 pe.and_then(|e| e.task_summary.clone())
382 .or_else(|| task_snapshot.summary.clone())
383 };
384
385 let verification_todo = if objective_changed {
386 task_snapshot
388 .verification_todo
389 .iter()
390 .cloned()
391 .chain(update.verification_todo.iter().cloned())
392 .take(MEMORY_LIST_LIMIT)
393 .collect()
394 } else {
395 merge(
396 pe.map(|e| e.verification_todo.as_slice()).unwrap_or(&[]),
397 &task_snapshot
398 .verification_todo
399 .iter()
400 .cloned()
401 .chain(update.verification_todo)
402 .collect::<Vec<_>>(),
403 )
404 };
405
406 SessionMemoryEnvelope {
407 session_id: session_id.to_string(),
408 schema_version: Some(SESSION_MEMORY_ENVELOPE_SCHEMA_VERSION),
409 summary,
410 objective,
411 task_summary,
412 spec_summary,
413 evaluation_summary,
414 verification_summary: task_snapshot
415 .verification_summary
416 .clone()
417 .or_else(|| pe.and_then(|e| e.verification_summary.clone())),
418 constraints: merge(&constraints, &update.constraints),
419 grounded_facts: merge_grounded_facts(pe, original_history, &update.grounded_facts),
420 touched_files: merge_touched_files(
421 pe,
422 &touched_files.iter().cloned().chain(update.touched_files).collect::<Vec<_>>(),
423 ),
424 open_questions: merge(pe.map(|e| e.open_questions.as_slice()).unwrap_or(&[]), &update.open_questions),
425 verification_todo,
426 delegation_notes: merge(pe.map(|e| e.delegation_notes.as_slice()).unwrap_or(&[]), &update.delegation_notes),
427 pending_intents,
428 applied_intent_ids,
429 history_artifact_path: history_artifact_path
430 .map(|p| p.display().to_string())
431 .or_else(|| pe.and_then(|e| e.history_artifact_path.clone())),
432 generated_at: Utc::now().to_rfc3339(),
433 }
434}
435
436fn collect_zero_cost_retained_user_messages(
437 history: &[Message],
438 token_budget: usize,
439 max_messages: usize,
440) -> Vec<Message> {
441 if token_budget == 0 || max_messages == 0 {
442 return Vec::new();
443 }
444
445 let mut kept = Vec::new();
446 let mut remaining = token_budget;
447
448 for message in history.iter().rev() {
449 if kept.len() >= max_messages {
450 break;
451 }
452 if message.role != MessageRole::User || message.content.trim().is_empty() {
453 continue;
454 }
455
456 let estimated = message.estimate_tokens();
457 if estimated <= remaining {
458 kept.push(message.clone());
459 remaining = remaining.saturating_sub(estimated);
460 continue;
461 }
462
463 if remaining > 4 {
464 let truncated = truncate_to_token_limit(message.content.as_text().as_ref(), remaining.saturating_sub(4));
465 let trimmed = truncated.trim();
466 if !trimmed.is_empty() {
467 kept.push(Message::user(trimmed.to_string()));
468 }
469 }
470 break;
471 }
472
473 kept.reverse();
474 kept
475}
476
477pub fn build_zero_cost_summarized_fork_history(
478 source_history: &[Message],
479 source_envelope: Option<&SessionMemoryEnvelope>,
480 retained_user_messages: usize,
481) -> Vec<Message> {
482 let summary = source_envelope
483 .map(|envelope| normalize_whitespace(&envelope.summary))
484 .filter(|summary| !summary.is_empty())
485 .unwrap_or_else(|| derive_continuity_summary(source_history, source_envelope, &TaskTrackerSnapshot::default()));
486
487 let retained_users = collect_zero_cost_retained_user_messages(
488 source_history,
489 CompactionConfig::default().retained_user_message_tokens,
490 retained_user_messages,
491 );
492
493 let mut compacted = Vec::with_capacity(retained_users.len().saturating_add(1));
494 compacted.push(Message::system(format!("Previous conversation summary:\n{}", summary.trim())));
495 compacted.extend(retained_users);
496 compacted
497}
498
499#[derive(Debug, Clone, PartialEq, Eq, Hash)]
504struct FileReadDedupKey {
505 target: String,
506 start_line: Option<u64>,
507 end_line: Option<u64>,
508 spool_path: Option<String>,
509}
510
511#[derive(Debug, Clone, PartialEq, Eq)]
512struct FileReadDedupCandidate {
513 key: FileReadDedupKey,
514 placeholder_content: String,
515}
516
517#[derive(Debug, Clone, Copy, PartialEq, Eq)]
518enum FileReadToolKind {
519 ReadFile,
520 UnifiedFileRead,
521}
522
523fn is_read_file_tool_name(tool_name: &str) -> bool {
524 tool_name == tool_names::READ_FILE || tool_name.ends_with(".read_file")
525}
526
527fn collect_file_read_tool_kinds(history: &[Message]) -> HashMap<String, FileReadToolKind> {
528 let mut kinds = HashMap::new();
529 for message in history {
530 let Some(tool_calls) = message.tool_calls.as_ref() else {
531 continue;
532 };
533 for tc in tool_calls {
534 let Some(tn) = tc.tool_name() else {
535 continue;
536 };
537 let kind = if is_read_file_tool_name(tn) {
538 Some(FileReadToolKind::ReadFile)
539 } else if tn == tool_names::UNIFIED_FILE {
540 tc.execution_arguments().ok().and_then(|args| {
541 args.get("action")
542 .and_then(Value::as_str)
543 .filter(|a| *a == "read")
544 .map(|_| FileReadToolKind::UnifiedFileRead)
545 })
546 } else {
547 None
548 };
549 if let Some(k) = kind {
550 kinds.insert(tc.id.clone(), k);
551 }
552 }
553 }
554 kinds
555}
556
557fn normalize_file_read_target(value: &str) -> Option<String> {
558 let trimmed = value.trim();
559 (!trimmed.is_empty()).then(|| trimmed.replace('\\', "/"))
560}
561
562fn build_file_read_dedup_key(payload: &Value) -> Option<FileReadDedupKey> {
563 let obj = payload.as_object()?;
564 if obj.get("items").is_some()
565 || obj.get("error").is_some()
566 || obj.get("spool_chunked").and_then(Value::as_bool).unwrap_or(false)
567 || obj.get("has_more").and_then(Value::as_bool).unwrap_or(false)
568 {
569 return None;
570 }
571 let target = obj
572 .get("file_path")
573 .and_then(Value::as_str)
574 .or_else(|| obj.get("path").and_then(Value::as_str))
575 .and_then(normalize_file_read_target)?;
576 Some(FileReadDedupKey {
577 target,
578 start_line: obj.get("start_line").and_then(Value::as_u64),
579 end_line: obj.get("end_line").and_then(Value::as_u64),
580 spool_path: obj
581 .get("spool_path")
582 .and_then(Value::as_str)
583 .and_then(normalize_file_read_target),
584 })
585}
586
587fn build_file_read_placeholder_content(payload: &Value, key: &FileReadDedupKey) -> String {
588 let mut p = serde_json::Map::new();
589 p.insert("deduped_read".into(), Value::Bool(true));
590 p.insert("note".into(), Value::String(DEDUPED_FILE_READ_NOTE.to_string()));
591
592 fn maybe_str(p: &mut serde_json::Map<String, Value>, payload: &Value, key: &str) {
593 if let Some(s) = payload
594 .get(key)
595 .and_then(Value::as_str)
596 .map(str::trim)
597 .filter(|s| !s.is_empty())
598 {
599 p.insert(key.into(), Value::String(s.to_string()));
600 }
601 }
602
603 maybe_str(&mut p, payload, "file_path");
604 maybe_str(&mut p, payload, "path");
605 if let Some(sl) = key.start_line {
606 p.insert("start_line".into(), json!(sl));
607 }
608 if let Some(el) = key.end_line {
609 p.insert("end_line".into(), json!(el));
610 }
611 if let Some(sp) = key.spool_path.as_deref() {
612 p.insert("spool_path".into(), json!(sp));
613 }
614 Value::Object(p).to_string()
615}
616
617fn file_read_dedup_candidate(
618 message: &Message,
619 tool_kinds: &HashMap<String, FileReadToolKind>,
620) -> Option<FileReadDedupCandidate> {
621 if message.role != MessageRole::Tool {
622 return None;
623 }
624
625 let kind = message
626 .tool_call_id
627 .as_deref()
628 .and_then(|tool_call_id| tool_kinds.get(tool_call_id).copied())
629 .or_else(|| {
630 message
631 .origin_tool
632 .as_deref()
633 .and_then(|tool_name| is_read_file_tool_name(tool_name).then_some(FileReadToolKind::ReadFile))
634 })?;
635
636 if !matches!(kind, FileReadToolKind::ReadFile | FileReadToolKind::UnifiedFileRead) {
637 return None;
638 }
639
640 let payload: Value = serde_json::from_str(message.content.as_text().as_ref()).ok()?;
641 let key = build_file_read_dedup_key(&payload)?;
642
643 Some(FileReadDedupCandidate {
644 placeholder_content: build_file_read_placeholder_content(&payload, &key),
645 key,
646 })
647}
648
649pub fn dedup_repeated_file_reads_for_local_compaction(history: &[Message]) -> Vec<Message> {
650 let tool_kinds = collect_file_read_tool_kinds(history);
651 let mut last_idx = HashMap::new();
652 let mut candidates = Vec::new();
653 for (i, msg) in history.iter().enumerate() {
654 let Some(c) = file_read_dedup_candidate(msg, &tool_kinds) else {
655 continue;
656 };
657 last_idx.insert(c.key.clone(), i);
658 candidates.push((i, c));
659 }
660 let mut deduped = history.to_vec();
661 let mut changed = false;
662 for (idx, c) in candidates {
663 if last_idx.get(&c.key).copied() == Some(idx) {
664 continue;
665 }
666 if let Some(msg) = deduped.get_mut(idx) {
667 msg.content = c.placeholder_content.into();
668 changed = true;
669 }
670 }
671 if changed { deduped } else { history.to_vec() }
672}
673
674pub const DEFAULT_OUTPUT_RESERVE_TOKENS: usize = 4096;
680
681pub fn resolve_compaction_threshold(configured_threshold: Option<u64>, context_size: usize) -> Option<u64> {
683 resolve_compaction_threshold_with_reserve(configured_threshold, context_size, DEFAULT_OUTPUT_RESERVE_TOKENS)
684}
685
686pub fn resolve_compaction_threshold_with_reserve(
687 configured_threshold: Option<u64>,
688 context_size: usize,
689 reserved_output_tokens: usize,
690) -> Option<u64> {
691 let configured = configured_threshold.filter(|value| *value > 0);
692 if context_size == 0 {
693 return configured;
694 }
695 let prompt_budget = context_size.saturating_sub(reserved_output_tokens).max(1) as u64;
696 const TRIGGER_RATIO_PERCENT: u64 = 75;
703 let default_trigger = prompt_budget.saturating_mul(TRIGGER_RATIO_PERCENT) / 100;
704 let default_trigger = default_trigger.clamp(1, prompt_budget);
705 Some(configured.map_or(default_trigger, |value| value.min(prompt_budget)))
706}
707
708pub fn resolve_effective_compaction_threshold(
710 configured_threshold: Option<u64>,
711 provider_context_size: usize,
712 session_context_budget: usize,
713) -> Option<u64> {
714 resolve_compaction_threshold(
715 configured_threshold,
716 effective_session_context_budget(provider_context_size, session_context_budget),
717 )
718}
719
720#[must_use]
722pub fn effective_session_context_budget(provider_context_size: usize, session_context_budget: usize) -> usize {
723 match (provider_context_size > 0, session_context_budget > 0) {
724 (true, true) => provider_context_size.min(session_context_budget),
725 (true, false) => provider_context_size,
726 (false, true) => session_context_budget,
727 (false, false) => 0,
728 }
729}
730
731#[must_use]
733pub fn effective_context_budget(vt_cfg: Option<&VTCodeConfig>, provider: &dyn LLMProvider, model: &str) -> usize {
734 use crate::llm::model_resolver::{DynamicModelMeta, ModelResolver};
735
736 let provider_capacity = provider.effective_context_size(model);
737 let resolved_capacity = ModelResolver::resolve(
743 Some(provider.name()),
744 model,
745 &[],
746 Some(DynamicModelMeta {
747 display_name: model.to_owned(),
748 description: None,
749 context_window: (provider_capacity > 0).then_some(provider_capacity),
750 }),
751 )
752 .and_then(|resolved| resolved.context_window())
753 .unwrap_or(provider_capacity);
758 let capacity = effective_session_context_budget(resolved_capacity, provider_capacity);
759 let session_budget = vt_cfg.map_or_else(default_max_context_tokens, |cfg| cfg.context.max_context_tokens);
760 effective_session_context_budget(capacity, session_budget)
761}
762
763pub fn effective_compaction_threshold_with_reserve(
764 vt_cfg: Option<&VTCodeConfig>,
765 provider: &dyn LLMProvider,
766 model: &str,
767 reserved_output_tokens: usize,
768) -> Option<usize> {
769 resolve_compaction_threshold_with_reserve(
770 vt_cfg.and_then(|cfg| cfg.agent.harness.auto_compaction_threshold_tokens),
771 effective_context_budget(vt_cfg, provider, model),
772 reserved_output_tokens,
773 )
774 .and_then(|value| usize::try_from(value).ok())
775}
776
777pub fn effective_compaction_threshold(
778 vt_cfg: Option<&VTCodeConfig>,
779 provider: &dyn LLMProvider,
780 model: &str,
781) -> Option<usize> {
782 let reserve = provider
783 .sampling_overrides(model)
784 .max_tokens
785 .map_or(DEFAULT_OUTPUT_RESERVE_TOKENS, |value| value as usize);
786 effective_compaction_threshold_with_reserve(vt_cfg, provider, model, reserve)
787}
788
789#[cfg(test)]
790mod persistence_tests;
791
792#[cfg(test)]
793mod tests;