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_QUEUED_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| intents.into_iter().take(MAX_QUEUED_FOLLOW_UP_INTENTS).collect())
339 .or_else(|| pe.map(|envelope| envelope.pending_intents.clone()))
340 .unwrap_or_default();
341 let applied_intent_ids = merge_applied_intent_ids(
342 pe.map(|envelope| envelope.applied_intent_ids.as_slice()).unwrap_or(&[]),
343 &update.applied_intent_ids,
344 );
345
346 let live_objective = task_snapshot.objective.as_deref().map(str::trim).filter(|s| !s.is_empty());
350 let prior_objective = pe.and_then(|e| e.objective.as_deref()).map(str::trim).filter(|s| !s.is_empty());
351 let objective_changed = match (live_objective, prior_objective) {
352 (Some(live), Some(prior)) => live != prior,
353 (Some(_), None) => true,
354 (None, Some(_)) => false,
355 (None, None) => false,
356 };
357
358 let objective = update
359 .objective
360 .or_else(|| live_objective.map(ToOwned::to_owned))
361 .or_else(|| pe.and_then(|e| e.objective.clone()));
362
363 let task_summary = if objective_changed {
364 task_snapshot.summary.clone().filter(|s| !s.trim().is_empty())
366 } else {
367 pe.and_then(|e| e.task_summary.clone())
368 .or_else(|| task_snapshot.summary.clone())
369 };
370
371 let verification_todo = if objective_changed {
372 task_snapshot
374 .verification_todo
375 .iter()
376 .cloned()
377 .chain(update.verification_todo.iter().cloned())
378 .take(MEMORY_LIST_LIMIT)
379 .collect()
380 } else {
381 merge(
382 pe.map(|e| e.verification_todo.as_slice()).unwrap_or(&[]),
383 &task_snapshot
384 .verification_todo
385 .iter()
386 .cloned()
387 .chain(update.verification_todo)
388 .collect::<Vec<_>>(),
389 )
390 };
391
392 SessionMemoryEnvelope {
393 session_id: session_id.to_string(),
394 schema_version: Some(SESSION_MEMORY_ENVELOPE_SCHEMA_VERSION),
395 summary,
396 objective,
397 task_summary,
398 spec_summary,
399 evaluation_summary,
400 verification_summary: task_snapshot
401 .verification_summary
402 .clone()
403 .or_else(|| pe.and_then(|e| e.verification_summary.clone())),
404 constraints: merge(&constraints, &update.constraints),
405 grounded_facts: merge_grounded_facts(pe, original_history, &update.grounded_facts),
406 touched_files: merge_touched_files(
407 pe,
408 &touched_files.iter().cloned().chain(update.touched_files).collect::<Vec<_>>(),
409 ),
410 open_questions: merge(pe.map(|e| e.open_questions.as_slice()).unwrap_or(&[]), &update.open_questions),
411 verification_todo,
412 delegation_notes: merge(pe.map(|e| e.delegation_notes.as_slice()).unwrap_or(&[]), &update.delegation_notes),
413 pending_intents,
414 applied_intent_ids,
415 history_artifact_path: history_artifact_path
416 .map(|p| p.display().to_string())
417 .or_else(|| pe.and_then(|e| e.history_artifact_path.clone())),
418 generated_at: Utc::now().to_rfc3339(),
419 }
420}
421
422fn collect_zero_cost_retained_user_messages(
423 history: &[Message],
424 token_budget: usize,
425 max_messages: usize,
426) -> Vec<Message> {
427 if token_budget == 0 || max_messages == 0 {
428 return Vec::new();
429 }
430
431 let mut kept = Vec::new();
432 let mut remaining = token_budget;
433
434 for message in history.iter().rev() {
435 if kept.len() >= max_messages {
436 break;
437 }
438 if message.role != MessageRole::User || message.content.trim().is_empty() {
439 continue;
440 }
441
442 let estimated = message.estimate_tokens();
443 if estimated <= remaining {
444 kept.push(message.clone());
445 remaining = remaining.saturating_sub(estimated);
446 continue;
447 }
448
449 if remaining > 4 {
450 let truncated = truncate_to_token_limit(message.content.as_text().as_ref(), remaining.saturating_sub(4));
451 let trimmed = truncated.trim();
452 if !trimmed.is_empty() {
453 kept.push(Message::user(trimmed.to_string()));
454 }
455 }
456 break;
457 }
458
459 kept.reverse();
460 kept
461}
462
463pub fn build_zero_cost_summarized_fork_history(
464 source_history: &[Message],
465 source_envelope: Option<&SessionMemoryEnvelope>,
466 retained_user_messages: usize,
467) -> Vec<Message> {
468 let summary = source_envelope
469 .map(|envelope| normalize_whitespace(&envelope.summary))
470 .filter(|summary| !summary.is_empty())
471 .unwrap_or_else(|| derive_continuity_summary(source_history, source_envelope, &TaskTrackerSnapshot::default()));
472
473 let retained_users = collect_zero_cost_retained_user_messages(
474 source_history,
475 CompactionConfig::default().retained_user_message_tokens,
476 retained_user_messages,
477 );
478
479 let mut compacted = Vec::with_capacity(retained_users.len().saturating_add(1));
480 compacted.push(Message::system(format!("Previous conversation summary:\n{}", summary.trim())));
481 compacted.extend(retained_users);
482 compacted
483}
484
485#[derive(Debug, Clone, PartialEq, Eq, Hash)]
490struct FileReadDedupKey {
491 target: String,
492 start_line: Option<u64>,
493 end_line: Option<u64>,
494 spool_path: Option<String>,
495}
496
497#[derive(Debug, Clone, PartialEq, Eq)]
498struct FileReadDedupCandidate {
499 key: FileReadDedupKey,
500 placeholder_content: String,
501}
502
503#[derive(Debug, Clone, Copy, PartialEq, Eq)]
504enum FileReadToolKind {
505 ReadFile,
506 UnifiedFileRead,
507}
508
509fn is_read_file_tool_name(tool_name: &str) -> bool {
510 tool_name == tool_names::READ_FILE || tool_name.ends_with(".read_file")
511}
512
513fn collect_file_read_tool_kinds(history: &[Message]) -> HashMap<String, FileReadToolKind> {
514 let mut kinds = HashMap::new();
515 for message in history {
516 let Some(tool_calls) = message.tool_calls.as_ref() else {
517 continue;
518 };
519 for tc in tool_calls {
520 let Some(tn) = tc.tool_name() else {
521 continue;
522 };
523 let kind = if is_read_file_tool_name(tn) {
524 Some(FileReadToolKind::ReadFile)
525 } else if tn == tool_names::UNIFIED_FILE {
526 tc.execution_arguments().ok().and_then(|args| {
527 args.get("action")
528 .and_then(Value::as_str)
529 .filter(|a| *a == "read")
530 .map(|_| FileReadToolKind::UnifiedFileRead)
531 })
532 } else {
533 None
534 };
535 if let Some(k) = kind {
536 kinds.insert(tc.id.clone(), k);
537 }
538 }
539 }
540 kinds
541}
542
543fn normalize_file_read_target(value: &str) -> Option<String> {
544 let trimmed = value.trim();
545 (!trimmed.is_empty()).then(|| trimmed.replace('\\', "/"))
546}
547
548fn build_file_read_dedup_key(payload: &Value) -> Option<FileReadDedupKey> {
549 let obj = payload.as_object()?;
550 if obj.get("items").is_some()
551 || obj.get("error").is_some()
552 || obj.get("spool_chunked").and_then(Value::as_bool).unwrap_or(false)
553 || obj.get("has_more").and_then(Value::as_bool).unwrap_or(false)
554 {
555 return None;
556 }
557 let target = obj
558 .get("file_path")
559 .and_then(Value::as_str)
560 .or_else(|| obj.get("path").and_then(Value::as_str))
561 .and_then(normalize_file_read_target)?;
562 Some(FileReadDedupKey {
563 target,
564 start_line: obj.get("start_line").and_then(Value::as_u64),
565 end_line: obj.get("end_line").and_then(Value::as_u64),
566 spool_path: obj
567 .get("spool_path")
568 .and_then(Value::as_str)
569 .and_then(normalize_file_read_target),
570 })
571}
572
573fn build_file_read_placeholder_content(payload: &Value, key: &FileReadDedupKey) -> String {
574 let mut p = serde_json::Map::new();
575 p.insert("deduped_read".into(), Value::Bool(true));
576 p.insert("note".into(), Value::String(DEDUPED_FILE_READ_NOTE.to_string()));
577
578 fn maybe_str(p: &mut serde_json::Map<String, Value>, payload: &Value, key: &str) {
579 if let Some(s) = payload
580 .get(key)
581 .and_then(Value::as_str)
582 .map(str::trim)
583 .filter(|s| !s.is_empty())
584 {
585 p.insert(key.into(), Value::String(s.to_string()));
586 }
587 }
588
589 maybe_str(&mut p, payload, "file_path");
590 maybe_str(&mut p, payload, "path");
591 if let Some(sl) = key.start_line {
592 p.insert("start_line".into(), json!(sl));
593 }
594 if let Some(el) = key.end_line {
595 p.insert("end_line".into(), json!(el));
596 }
597 if let Some(sp) = key.spool_path.as_deref() {
598 p.insert("spool_path".into(), json!(sp));
599 }
600 Value::Object(p).to_string()
601}
602
603fn file_read_dedup_candidate(
604 message: &Message,
605 tool_kinds: &HashMap<String, FileReadToolKind>,
606) -> Option<FileReadDedupCandidate> {
607 if message.role != MessageRole::Tool {
608 return None;
609 }
610
611 let kind = message
612 .tool_call_id
613 .as_deref()
614 .and_then(|tool_call_id| tool_kinds.get(tool_call_id).copied())
615 .or_else(|| {
616 message
617 .origin_tool
618 .as_deref()
619 .and_then(|tool_name| is_read_file_tool_name(tool_name).then_some(FileReadToolKind::ReadFile))
620 })?;
621
622 if !matches!(kind, FileReadToolKind::ReadFile | FileReadToolKind::UnifiedFileRead) {
623 return None;
624 }
625
626 let payload: Value = serde_json::from_str(message.content.as_text().as_ref()).ok()?;
627 let key = build_file_read_dedup_key(&payload)?;
628
629 Some(FileReadDedupCandidate {
630 placeholder_content: build_file_read_placeholder_content(&payload, &key),
631 key,
632 })
633}
634
635pub fn dedup_repeated_file_reads_for_local_compaction(history: &[Message]) -> Vec<Message> {
636 let tool_kinds = collect_file_read_tool_kinds(history);
637 let mut last_idx = HashMap::new();
638 let mut candidates = Vec::new();
639 for (i, msg) in history.iter().enumerate() {
640 let Some(c) = file_read_dedup_candidate(msg, &tool_kinds) else {
641 continue;
642 };
643 last_idx.insert(c.key.clone(), i);
644 candidates.push((i, c));
645 }
646 let mut deduped = history.to_vec();
647 let mut changed = false;
648 for (idx, c) in candidates {
649 if last_idx.get(&c.key).copied() == Some(idx) {
650 continue;
651 }
652 if let Some(msg) = deduped.get_mut(idx) {
653 msg.content = c.placeholder_content.into();
654 changed = true;
655 }
656 }
657 if changed { deduped } else { history.to_vec() }
658}
659
660pub const DEFAULT_OUTPUT_RESERVE_TOKENS: usize = 4096;
666
667pub fn resolve_compaction_threshold(configured_threshold: Option<u64>, context_size: usize) -> Option<u64> {
669 resolve_compaction_threshold_with_reserve(configured_threshold, context_size, DEFAULT_OUTPUT_RESERVE_TOKENS)
670}
671
672pub fn resolve_compaction_threshold_with_reserve(
673 configured_threshold: Option<u64>,
674 context_size: usize,
675 reserved_output_tokens: usize,
676) -> Option<u64> {
677 let configured = configured_threshold.filter(|value| *value > 0);
678 if context_size == 0 {
679 return configured;
680 }
681 let prompt_budget = context_size.saturating_sub(reserved_output_tokens).max(1) as u64;
682 const TRIGGER_RATIO_PERCENT: u64 = 75;
689 let default_trigger = prompt_budget.saturating_mul(TRIGGER_RATIO_PERCENT) / 100;
690 let default_trigger = default_trigger.clamp(1, prompt_budget);
691 Some(configured.map_or(default_trigger, |value| value.min(prompt_budget)))
692}
693
694pub fn resolve_effective_compaction_threshold(
696 configured_threshold: Option<u64>,
697 provider_context_size: usize,
698 session_context_budget: usize,
699) -> Option<u64> {
700 resolve_compaction_threshold(
701 configured_threshold,
702 effective_session_context_budget(provider_context_size, session_context_budget),
703 )
704}
705
706#[must_use]
708pub fn effective_session_context_budget(provider_context_size: usize, session_context_budget: usize) -> usize {
709 match (provider_context_size > 0, session_context_budget > 0) {
710 (true, true) => provider_context_size.min(session_context_budget),
711 (true, false) => provider_context_size,
712 (false, true) => session_context_budget,
713 (false, false) => 0,
714 }
715}
716
717#[must_use]
719pub fn effective_context_budget(vt_cfg: Option<&VTCodeConfig>, provider: &dyn LLMProvider, model: &str) -> usize {
720 use crate::llm::model_resolver::{DynamicModelMeta, ModelResolver};
721
722 let provider_capacity = provider.effective_context_size(model);
723 let resolved_capacity = ModelResolver::resolve(
729 Some(provider.name()),
730 model,
731 &[],
732 Some(DynamicModelMeta {
733 display_name: model.to_owned(),
734 description: None,
735 context_window: (provider_capacity > 0).then_some(provider_capacity),
736 }),
737 )
738 .and_then(|resolved| resolved.context_window())
739 .unwrap_or(provider_capacity);
744 let capacity = effective_session_context_budget(resolved_capacity, provider_capacity);
745 let session_budget = vt_cfg.map_or_else(default_max_context_tokens, |cfg| cfg.context.max_context_tokens);
746 effective_session_context_budget(capacity, session_budget)
747}
748
749pub fn effective_compaction_threshold_with_reserve(
750 vt_cfg: Option<&VTCodeConfig>,
751 provider: &dyn LLMProvider,
752 model: &str,
753 reserved_output_tokens: usize,
754) -> Option<usize> {
755 resolve_compaction_threshold_with_reserve(
756 vt_cfg.and_then(|cfg| cfg.agent.harness.auto_compaction_threshold_tokens),
757 effective_context_budget(vt_cfg, provider, model),
758 reserved_output_tokens,
759 )
760 .and_then(|value| usize::try_from(value).ok())
761}
762
763pub fn effective_compaction_threshold(
764 vt_cfg: Option<&VTCodeConfig>,
765 provider: &dyn LLMProvider,
766 model: &str,
767) -> Option<usize> {
768 let reserve = provider
769 .sampling_overrides(model)
770 .max_tokens
771 .map_or(DEFAULT_OUTPUT_RESERVE_TOKENS, |value| value as usize);
772 effective_compaction_threshold_with_reserve(vt_cfg, provider, model, reserve)
773}
774
775#[cfg(test)]
776mod persistence_tests;
777
778#[cfg(test)]
779mod tests;