Skip to main content

vtcode_core/compaction/
memory_envelope.rs

1//! Session memory envelope + local compaction helpers, shared by every
2//! compaction path (auto, manual `/compact`, model-switch, recovery, fork).
3//!
4//! This module was extracted from the binary unified runloop so that both the
5//! binary runloop and the `vtcode-core` `AgentRunner` loop use a single
6//! compaction path with identical continuity behavior.
7
8use 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
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum MemoryEnvelopePersistence {
44    PersistToDisk,
45    InMemoryOnly,
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum MemoryEnvelopePlacement {
50    Start,
51    BeforeLastUserOrSummary,
52}
53
54#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
55pub struct SessionMemoryEnvelope {
56    #[serde(default)]
57    pub session_id: String,
58    #[serde(default)]
59    pub schema_version: Option<u32>,
60    pub summary: String,
61    #[serde(default)]
62    pub objective: Option<String>,
63    pub task_summary: Option<String>,
64    pub spec_summary: Option<String>,
65    pub evaluation_summary: Option<String>,
66    #[serde(default)]
67    pub verification_summary: Option<String>,
68    #[serde(default)]
69    pub constraints: Vec<String>,
70    pub grounded_facts: Vec<GroundedFactRecord>,
71    pub touched_files: Vec<String>,
72    #[serde(default)]
73    pub open_questions: Vec<String>,
74    #[serde(default)]
75    pub verification_todo: Vec<String>,
76    #[serde(default)]
77    pub delegation_notes: Vec<String>,
78    /// Follow-up steering intents accepted but not yet represented by a
79    /// tagged user message. The list is bounded to preserve FIFO recovery.
80    #[serde(default)]
81    pub pending_intents: Vec<QueuedFollowUpIntent>,
82    /// Recently applied steering IDs used to avoid replaying an already
83    /// durable instruction after restart or compaction.
84    #[serde(default)]
85    pub applied_intent_ids: Vec<String>,
86    pub history_artifact_path: Option<String>,
87    pub generated_at: String,
88}
89
90impl SessionMemoryEnvelope {
91    /// Returns true if this envelope carries the same meaningful content as
92    /// `other`. Generated timestamps and history artifact paths are ignored
93    /// because they change even when the underlying session state does not.
94    pub fn is_content_equivalent_to(&self, other: &SessionMemoryEnvelope) -> bool {
95        self.session_id == other.session_id
96            && self.schema_version == other.schema_version
97            && self.summary == other.summary
98            && self.objective == other.objective
99            && self.task_summary == other.task_summary
100            && self.spec_summary == other.spec_summary
101            && self.evaluation_summary == other.evaluation_summary
102            && self.verification_summary == other.verification_summary
103            && self.constraints == other.constraints
104            && self.grounded_facts == other.grounded_facts
105            && self.touched_files == other.touched_files
106            && self.open_questions == other.open_questions
107            && self.verification_todo == other.verification_todo
108            && self.delegation_notes == other.delegation_notes
109            && self.pending_intents == other.pending_intents
110            && self.applied_intent_ids == other.applied_intent_ids
111    }
112}
113
114#[derive(Debug, Clone, Default, PartialEq, Eq)]
115pub struct SessionMemoryEnvelopeUpdate {
116    pub objective: Option<String>,
117    pub constraints: Vec<String>,
118    pub grounded_facts: Vec<GroundedFactRecord>,
119    pub touched_files: Vec<String>,
120    pub open_questions: Vec<String>,
121    pub verification_todo: Vec<String>,
122    pub delegation_notes: Vec<String>,
123    /// Replace the durable pending-intent snapshot when supplied.
124    pub pending_intents: Option<Vec<QueuedFollowUpIntent>>,
125    /// IDs acknowledged since the previous envelope.
126    pub applied_intent_ids: Vec<String>,
127}
128
129#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
130pub struct TaskTrackerSnapshot {
131    summary: Option<String>,
132    objective: Option<String>,
133    verification_summary: Option<String>,
134    verification_todo: Vec<String>,
135}
136
137fn merge_dedup_push<T, K, F>(prior: &[T], updates: impl IntoIterator<Item = T>, limit: usize, key_fn: F) -> Vec<T>
138where
139    K: PartialEq,
140    F: Fn(&T) -> K,
141    T: Clone,
142{
143    let mut merged = prior.to_vec();
144    for item in updates {
145        if let Some(idx) = merged.iter().position(|e| key_fn(e) == key_fn(&item)) {
146            merged.remove(idx);
147        }
148        merged.push(item);
149    }
150    let keep_from = merged.len().saturating_sub(limit);
151    merged.into_iter().skip(keep_from).collect()
152}
153
154fn merge_touched_files(prior_envelope: Option<&SessionMemoryEnvelope>, touched_files: &[String]) -> Vec<String> {
155    let prior = prior_envelope.map(|e| e.touched_files.as_slice()).unwrap_or(&[]);
156    merge_dedup_push(prior, touched_files.iter().cloned(), usize::MAX, |s| s.clone())
157}
158
159fn merge_recent_strings(prior: &[String], updates: &[String], limit: usize) -> Vec<String> {
160    let prior_normalized: Vec<_> = prior
161        .iter()
162        .map(|v| normalize_whitespace(v))
163        .filter(|v| !v.is_empty())
164        .collect();
165    let updates_normalized: Vec<_> = updates
166        .iter()
167        .map(|v| normalize_whitespace(v))
168        .filter(|v| !v.is_empty())
169        .collect();
170    merge_dedup_push(&prior_normalized, updates_normalized, limit, |s| s.to_ascii_lowercase())
171}
172
173fn merge_applied_intent_ids(prior: &[String], updates: &[String]) -> Vec<String> {
174    merge_dedup_push(prior, updates.iter().cloned(), APPLIED_INTENT_WINDOW, |id| id.clone())
175}
176
177fn extract_constraints_from_summary(text: Option<&str>) -> Vec<String> {
178    text.into_iter()
179        .flat_map(|value| value.split(" | "))
180        .map(normalize_whitespace)
181        .filter(|line| !line.is_empty())
182        .filter_map(|line| {
183            let line = line.as_str();
184            // Artifact summaries join their lines as "Spec: - a | - b"; strip
185            // the label only when the payload keeps the bullet so ordinary
186            // "key: value" lines are never misread as constraint bullets.
187            let line = match line.split_once(": ") {
188                Some((_, rest)) if rest.starts_with("- ") || rest.starts_with("* ") => rest,
189                _ => line,
190            };
191            if let Some(rest) = line.strip_prefix("- ") {
192                return Some(rest.trim().to_string());
193            }
194            line.strip_prefix("* ").map(|rest| rest.trim().to_string())
195        })
196        .take(MEMORY_LIST_LIMIT)
197        .collect()
198}
199
200pub fn derive_continuity_summary(
201    history: &[Message],
202    prior_envelope: Option<&SessionMemoryEnvelope>,
203    task_snapshot: &TaskTrackerSnapshot,
204) -> String {
205    let objective = task_snapshot
206        .objective
207        .as_deref()
208        .or_else(|| prior_envelope.and_then(|e| e.objective.as_deref()))
209        .filter(|s| !s.is_empty());
210
211    let latest = history
212        .iter()
213        .rev()
214        .filter(|message| message.role == MessageRole::User || message.role == MessageRole::Assistant)
215        .find_map(|message| {
216            let trimmed = normalize_whitespace(message.content.as_text().as_ref());
217            (!trimmed.is_empty()).then_some((message.role.as_generic_str(), truncate_for_fact(&trimmed, 140)))
218        });
219
220    match (objective, latest) {
221        (Some(obj), Some((role, text))) => {
222            format!("Working on: {obj}. Latest {role} action: {text}.")
223        }
224        (Some(obj), None) => format!("Working on: {obj}. Session continuity preserved."),
225        (None, Some((role, text))) => {
226            format!("Latest {role} action: {text}.")
227        }
228        (None, None) => prior_envelope
229            .map(|envelope| envelope.summary.clone())
230            .unwrap_or_else(|| "Session continuity facts preserved.".to_string()),
231    }
232}
233
234fn merge_grounded_facts(
235    prior_envelope: Option<&SessionMemoryEnvelope>,
236    original_history: &[Message],
237    updates: &[GroundedFactRecord],
238) -> Vec<GroundedFactRecord> {
239    let mut merged = prior_envelope
240        .map(|envelope| envelope.grounded_facts.clone())
241        .unwrap_or_default();
242
243    for fact in dedup_latest_facts(original_history, 5) {
244        let normalized = normalize_whitespace(&fact.fact).to_ascii_lowercase();
245        if let Some(existing_idx) = merged
246            .iter()
247            .position(|entry| normalize_whitespace(&entry.fact).to_ascii_lowercase() == normalized)
248        {
249            merged.remove(existing_idx);
250        }
251        merged.push(fact.clone());
252    }
253
254    for fact in updates {
255        let normalized = normalize_whitespace(&fact.fact).to_ascii_lowercase();
256        if let Some(existing_idx) = merged
257            .iter()
258            .position(|entry| normalize_whitespace(&entry.fact).to_ascii_lowercase() == normalized)
259        {
260            merged.remove(existing_idx);
261        }
262        merged.push(fact.clone());
263    }
264
265    let keep_from = merged.len().saturating_sub(5);
266    merged.into_iter().skip(keep_from).collect()
267}
268
269#[allow(
270    clippy::too_many_arguments,
271    reason = "Intentional compatibility, platform, or test-only suppression."
272)]
273/// Builds an owned envelope; the optional history path is borrowed for display
274/// and is not opened by this function.
275#[must_use]
276pub fn build_session_memory_envelope(
277    session_id: &str,
278    workspace_root: &Path,
279    original_history: &[Message],
280    touched_files: &[String],
281    summary: String,
282    history_artifact_path: Option<&Path>,
283    prior_envelope: Option<&SessionMemoryEnvelope>,
284    task_snapshot: &TaskTrackerSnapshot,
285    envelope_update: Option<&SessionMemoryEnvelopeUpdate>,
286) -> SessionMemoryEnvelope {
287    let pe = prior_envelope;
288    let artifact_cutoff = session_artifact_cutoff(workspace_root, session_id);
289    // A present-but-stale artifact must not fall back to a prior envelope's
290    // copy (that re-adopts the same leftover). Only inherit prior when the
291    // file is absent.
292    let spec_present = current_spec_path(workspace_root).exists();
293    let evaluation_present = current_evaluation_path(workspace_root).exists();
294    let spec_summary = if spec_present {
295        read_spec_summary_fresh(workspace_root, artifact_cutoff)
296    } else {
297        pe.and_then(|e| e.spec_summary.clone())
298    };
299    let evaluation_summary = if evaluation_present {
300        read_evaluation_summary_fresh(workspace_root, artifact_cutoff)
301    } else {
302        pe.and_then(|e| e.evaluation_summary.clone())
303    };
304    let merge = |prior: &[String], updates: &[String]| merge_recent_strings(prior, updates, MEMORY_LIST_LIMIT);
305    // Constraints extracted from a dropped stale artifact must not re-enter via
306    // the prior envelope: a present artifact that failed the freshness check
307    // resets the channel. Fresh artifacts (or no artifact files) keep the
308    // continuity merge of inherited constraints.
309    let artifact_channel_reset = (spec_present
310        && artifact_is_stale(&current_spec_path(workspace_root), artifact_cutoff))
311        || (evaluation_present && artifact_is_stale(&current_evaluation_path(workspace_root), artifact_cutoff));
312    let prior_constraints: &[String] = if artifact_channel_reset {
313        &[]
314    } else {
315        pe.map(|e| e.constraints.as_slice()).unwrap_or(&[])
316    };
317    let constraints = merge(prior_constraints, &extract_constraints_from_summary(spec_summary.as_deref()));
318    let constraints = merge(&constraints, &extract_constraints_from_summary(evaluation_summary.as_deref()));
319    let update = envelope_update.cloned().unwrap_or_default();
320    let pending_intents = update
321        .pending_intents
322        .map(|intents| intents.into_iter().take(MAX_QUEUED_FOLLOW_UP_INTENTS).collect())
323        .or_else(|| pe.map(|envelope| envelope.pending_intents.clone()))
324        .unwrap_or_default();
325    let applied_intent_ids = merge_applied_intent_ids(
326        pe.map(|envelope| envelope.applied_intent_ids.as_slice()).unwrap_or(&[]),
327        &update.applied_intent_ids,
328    );
329
330    // Live task-tracker identity wins over a prior envelope from another
331    // session/task. Workspace-global `current_task.md` is a live snapshot
332    // source; inheriting a stale prior objective re-labels later sessions.
333    let live_objective = task_snapshot.objective.as_deref().map(str::trim).filter(|s| !s.is_empty());
334    let prior_objective = pe.and_then(|e| e.objective.as_deref()).map(str::trim).filter(|s| !s.is_empty());
335    let objective_changed = match (live_objective, prior_objective) {
336        (Some(live), Some(prior)) => live != prior,
337        (Some(_), None) => true,
338        (None, Some(_)) => false,
339        (None, None) => false,
340    };
341
342    let objective = update
343        .objective
344        .or_else(|| live_objective.map(ToOwned::to_owned))
345        .or_else(|| pe.and_then(|e| e.objective.clone()));
346
347    let task_summary = if objective_changed {
348        // Spec S2: never inherit another task's checklist narrative.
349        task_snapshot.summary.clone().filter(|s| !s.trim().is_empty())
350    } else {
351        pe.and_then(|e| e.task_summary.clone())
352            .or_else(|| task_snapshot.summary.clone())
353    };
354
355    let verification_todo = if objective_changed {
356        // Replace, do not union: prior-task open items are not this session's todos.
357        task_snapshot
358            .verification_todo
359            .iter()
360            .cloned()
361            .chain(update.verification_todo.iter().cloned())
362            .take(MEMORY_LIST_LIMIT)
363            .collect()
364    } else {
365        merge(
366            pe.map(|e| e.verification_todo.as_slice()).unwrap_or(&[]),
367            &task_snapshot
368                .verification_todo
369                .iter()
370                .cloned()
371                .chain(update.verification_todo)
372                .collect::<Vec<_>>(),
373        )
374    };
375
376    SessionMemoryEnvelope {
377        session_id: session_id.to_string(),
378        schema_version: Some(SESSION_MEMORY_ENVELOPE_SCHEMA_VERSION),
379        summary,
380        objective,
381        task_summary,
382        spec_summary,
383        evaluation_summary,
384        verification_summary: task_snapshot
385            .verification_summary
386            .clone()
387            .or_else(|| pe.and_then(|e| e.verification_summary.clone())),
388        constraints: merge(&constraints, &update.constraints),
389        grounded_facts: merge_grounded_facts(pe, original_history, &update.grounded_facts),
390        touched_files: merge_touched_files(
391            pe,
392            &touched_files.iter().cloned().chain(update.touched_files).collect::<Vec<_>>(),
393        ),
394        open_questions: merge(pe.map(|e| e.open_questions.as_slice()).unwrap_or(&[]), &update.open_questions),
395        verification_todo,
396        delegation_notes: merge(pe.map(|e| e.delegation_notes.as_slice()).unwrap_or(&[]), &update.delegation_notes),
397        pending_intents,
398        applied_intent_ids,
399        history_artifact_path: history_artifact_path
400            .map(|p| p.display().to_string())
401            .or_else(|| pe.and_then(|e| e.history_artifact_path.clone())),
402        generated_at: Utc::now().to_rfc3339(),
403    }
404}
405
406/// Persist the recoverable full-history artifact and build + inject a session
407/// memory envelope into the compacted history. Returns the envelope (with the
408/// artifact path) when one was produced.
409pub fn persist_memory_envelope(
410    workspace_root: &Path,
411    session_id: &str,
412    vt_cfg: Option<&VTCodeConfig>,
413    original_history: &[Message],
414    touched_files: &[String],
415    compacted: &mut Vec<Message>,
416    persistence: MemoryEnvelopePersistence,
417    placement: MemoryEnvelopePlacement,
418    seed_envelope: Option<&SessionMemoryEnvelope>,
419) -> anyhow::Result<Option<SessionMemoryEnvelope>> {
420    persist_memory_envelope_with_update(
421        workspace_root,
422        session_id,
423        vt_cfg,
424        original_history,
425        touched_files,
426        compacted,
427        persistence,
428        placement,
429        seed_envelope,
430        None,
431    )
432}
433
434/// Variant of [`persist_memory_envelope`] that applies a live session update
435/// while constructing the envelope. Keeping the compatibility wrapper above
436/// avoids changing synchronous callers that do not track steering state.
437#[allow(
438    clippy::too_many_arguments,
439    reason = "Intentional compatibility, platform, or test-only suppression."
440)]
441pub fn persist_memory_envelope_with_update(
442    workspace_root: &Path,
443    session_id: &str,
444    vt_cfg: Option<&VTCodeConfig>,
445    original_history: &[Message],
446    touched_files: &[String],
447    compacted: &mut Vec<Message>,
448    persistence: MemoryEnvelopePersistence,
449    placement: MemoryEnvelopePlacement,
450    seed_envelope: Option<&SessionMemoryEnvelope>,
451    envelope_update: Option<&SessionMemoryEnvelopeUpdate>,
452) -> anyhow::Result<Option<SessionMemoryEnvelope>> {
453    let should_persist = should_persist_memory_envelope(vt_cfg);
454    if original_history.is_empty() || (!should_persist && persistence == MemoryEnvelopePersistence::PersistToDisk) {
455        return Ok(None);
456    }
457
458    let task_snapshot = read_task_tracker_snapshot(workspace_root);
459    let history_artifact_path = if should_persist && persistence == MemoryEnvelopePersistence::PersistToDisk {
460        let mut hm = HistoryFileManager::new(workspace_root, session_id);
461        let hm2 = messages_to_history_messages(original_history, 0);
462        let hr = hm
463            .write_history_sync(&hm2, original_history.len(), "compaction", touched_files, &[])
464            .context("write compaction history artifact")?;
465        Some(hr.file_path)
466    } else {
467        None
468    };
469    let loaded = if seed_envelope.is_none() {
470        load_latest_memory_envelope(workspace_root, session_id)
471    } else {
472        None
473    };
474    let prior = seed_envelope.or(loaded.as_ref());
475    let envelope = build_session_memory_envelope(
476        session_id,
477        workspace_root,
478        original_history,
479        touched_files,
480        extract_compaction_summary(compacted, original_history),
481        history_artifact_path.as_deref(),
482        prior,
483        &task_snapshot,
484        envelope_update,
485    );
486
487    if let Some(hap) = history_artifact_path.as_ref() {
488        write_memory_envelope_to_path(&memory_envelope_path_from_history_path(workspace_root, hap), &envelope)?;
489    }
490    apply_memory_envelope(compacted, &envelope, placement);
491    Ok(Some(envelope))
492}
493
494/// Async counterpart to [`persist_memory_envelope`]. Compaction runs on the
495/// async agent loop, so filesystem work must not block the runtime while the
496/// recoverable history artifact or envelope is being written.
497pub async fn persist_memory_envelope_async(
498    workspace_root: &Path,
499    session_id: &str,
500    vt_cfg: Option<&VTCodeConfig>,
501    original_history: &[Message],
502    touched_files: &[String],
503    compacted: &mut Vec<Message>,
504    persistence: MemoryEnvelopePersistence,
505    placement: MemoryEnvelopePlacement,
506    seed_envelope: Option<&SessionMemoryEnvelope>,
507) -> anyhow::Result<Option<SessionMemoryEnvelope>> {
508    persist_memory_envelope_async_with_update(
509        workspace_root,
510        session_id,
511        vt_cfg,
512        original_history,
513        touched_files,
514        compacted,
515        persistence,
516        placement,
517        seed_envelope,
518        None,
519    )
520    .await
521}
522
523/// Async variant of [`persist_memory_envelope_async`] that applies a live
524/// session update while constructing the envelope.
525#[allow(
526    clippy::too_many_arguments,
527    reason = "Intentional compatibility, platform, or test-only suppression."
528)]
529pub async fn persist_memory_envelope_async_with_update(
530    workspace_root: &Path,
531    session_id: &str,
532    vt_cfg: Option<&VTCodeConfig>,
533    original_history: &[Message],
534    touched_files: &[String],
535    compacted: &mut Vec<Message>,
536    persistence: MemoryEnvelopePersistence,
537    placement: MemoryEnvelopePlacement,
538    seed_envelope: Option<&SessionMemoryEnvelope>,
539    envelope_update: Option<&SessionMemoryEnvelopeUpdate>,
540) -> anyhow::Result<Option<SessionMemoryEnvelope>> {
541    let should_persist = should_persist_memory_envelope(vt_cfg);
542    if original_history.is_empty() || (!should_persist && persistence == MemoryEnvelopePersistence::PersistToDisk) {
543        return Ok(None);
544    }
545
546    let task_snapshot = read_task_tracker_snapshot_async(workspace_root).await;
547    let history_artifact_path = if should_persist && persistence == MemoryEnvelopePersistence::PersistToDisk {
548        let mut history_manager = HistoryFileManager::new(workspace_root, session_id);
549        let history_messages = messages_to_history_messages(original_history, 0);
550        let history_result = history_manager
551            .write_history(&history_messages, original_history.len(), "compaction", touched_files, &[])
552            .await
553            .context("write compaction history artifact")?;
554        Some(history_result.file_path)
555    } else {
556        None
557    };
558
559    let loaded = if seed_envelope.is_none() {
560        load_latest_memory_envelope_async(workspace_root, session_id).await
561    } else {
562        None
563    };
564    let prior = seed_envelope.or(loaded.as_ref());
565    let envelope = build_session_memory_envelope(
566        session_id,
567        workspace_root,
568        original_history,
569        touched_files,
570        extract_compaction_summary(compacted, original_history),
571        history_artifact_path.as_deref(),
572        prior,
573        &task_snapshot,
574        envelope_update,
575    );
576
577    if let Some(history_path) = history_artifact_path.as_ref() {
578        write_memory_envelope_to_path_async(
579            &memory_envelope_path_from_history_path(workspace_root, history_path),
580            &envelope,
581        )
582        .await?;
583    }
584    apply_memory_envelope(compacted, &envelope, placement);
585    Ok(Some(envelope))
586}
587
588pub fn should_persist_memory_envelope(vt_cfg: Option<&VTCodeConfig>) -> bool {
589    vt_cfg.is_some_and(|cfg| cfg.context.dynamic.enabled && cfg.context.dynamic.persist_history)
590}
591
592fn memory_envelope_message(envelope: &SessionMemoryEnvelope) -> Message {
593    let mut sections = Vec::new();
594    sections.push(format!("{}\nSummary:\n{}", MEMORY_ENVELOPE_HEADER, envelope.summary.trim()));
595
596    fn maybe_section(prefix: &str, content: Option<&str>) -> Option<String> {
597        content
598            .map(str::trim)
599            .filter(|s| !s.is_empty())
600            .map(|s| format!("{prefix}\n{s}"))
601    }
602
603    fn list_section(prefix: &str, items: &[String]) -> Option<String> {
604        (!items.is_empty()).then(|| format!("{prefix}\n- {}", items.join("\n- ")))
605    }
606
607    if let Some(s) = maybe_section("Objective", envelope.objective.as_deref()) {
608        sections.push(s);
609    }
610    if let Some(s) = maybe_section("Task Tracker", envelope.task_summary.as_deref()) {
611        sections.push(s);
612    }
613    if let Some(s) = maybe_section("Spec Summary", envelope.spec_summary.as_deref()) {
614        sections.push(s);
615    }
616    if let Some(s) = maybe_section("Evaluation Summary", envelope.evaluation_summary.as_deref()) {
617        sections.push(s);
618    }
619    if let Some(s) = maybe_section("Verification Status", envelope.verification_summary.as_deref()) {
620        sections.push(s);
621    }
622    if let Some(s) = list_section("Constraints", &envelope.constraints) {
623        sections.push(s);
624    }
625    if let Some(s) = list_section("Touched Files", &envelope.touched_files) {
626        sections.push(s);
627    }
628
629    if !envelope.grounded_facts.is_empty() {
630        let facts: Vec<_> = envelope
631            .grounded_facts
632            .iter()
633            .map(|f| format!("[{}] {}", f.source, f.fact.trim()))
634            .collect();
635        sections.push(format!("Grounded Facts:\n{}", facts.join("\n")));
636    }
637    if let Some(s) = list_section("Open Questions", &envelope.open_questions) {
638        sections.push(s);
639    }
640    if let Some(s) = list_section("Verification Todo", &envelope.verification_todo) {
641        sections.push(s);
642    }
643    if let Some(s) = list_section("Delegation Notes", &envelope.delegation_notes) {
644        sections.push(s);
645    }
646    if let Some(s) = maybe_section("History Artifact", envelope.history_artifact_path.as_deref()) {
647        sections.push(s);
648    }
649
650    Message::system(sections.join("\n\n"))
651}
652
653fn is_compaction_summary_message(message: &Message) -> bool {
654    message.role == MessageRole::System && message.content.as_text().starts_with("Previous conversation summary:\n")
655}
656
657pub fn strip_existing_memory_envelope(history: &mut Vec<Message>) {
658    history.retain(|message| {
659        !(message.role == MessageRole::System && message.content.as_text().starts_with(MEMORY_ENVELOPE_HEADER))
660    });
661}
662
663fn extract_compaction_summary(compacted: &[Message], original_history: &[Message]) -> String {
664    if let Some(summary) = compacted.iter().find_map(|message| {
665        if message.role != MessageRole::System {
666            return None;
667        }
668
669        let text = message.content.as_text();
670        let trimmed = text.trim();
671        trimmed
672            .strip_prefix("Previous conversation summary:\n")
673            .map(str::trim)
674            .filter(|value| !value.is_empty())
675            .map(str::to_string)
676    }) {
677        return summary;
678    }
679
680    if let Some(summary) = compacted.iter().find_map(|message| {
681        if message.role != MessageRole::Assistant {
682            return None;
683        }
684
685        message.reasoning_details.as_ref()?.iter().find_map(|detail| {
686            let value = match detail {
687                Value::String(serialized) => serde_json::from_str::<Value>(serialized).ok()?,
688                value => value.clone(),
689            };
690            let summary = value
691                .get("content")
692                .and_then(Value::as_str)
693                .map(str::trim)
694                .filter(|summary| !summary.is_empty())?;
695            (value.get("type").and_then(Value::as_str) == Some("compaction")).then_some(summary.to_string())
696        })
697    }) {
698        return summary;
699    }
700
701    let mut recent = original_history
702        .iter()
703        .rev()
704        .filter_map(|message| {
705            let text = message.content.as_text();
706            let trimmed = normalize_whitespace(text.as_ref());
707            (!trimmed.is_empty()).then_some(format!(
708                "{}: {}",
709                message.role.as_generic_str(),
710                truncate_for_fact(&trimmed, 160)
711            ))
712        })
713        .take(4)
714        .collect::<Vec<_>>();
715    recent.reverse();
716
717    if recent.is_empty() {
718        "Compacted earlier conversation state and preserved continuity facts.".to_string()
719    } else {
720        format!("Compacted earlier conversation state. Recent preserved context: {}", recent.join(" | "))
721    }
722}
723
724/// Sanitize a session id the same way history envelope filenames do
725/// (32-char ASCII-safe prefix). Callers that match envelope names must use
726/// this, not the raw session id.
727pub fn sanitize_session_id(session_id: &str) -> String {
728    session_id
729        .chars()
730        .map(|c| {
731            if c.is_alphanumeric() || c == '_' || c == '-' {
732                c
733            } else {
734                '_'
735            }
736        })
737        .take(32)
738        .collect()
739}
740
741/// Whether a history envelope filename belongs to `session_id`.
742///
743/// Envelope names use the 32-char sanitized id, with optional `_<n>`
744/// suffixes. Matching must use this exact rule — a loose `starts_with` on
745/// the raw id over-preserves unrelated sessions.
746pub fn memory_envelope_file_matches_session(name: &str, session_id: &str) -> bool {
747    let session_prefix = sanitize_session_id(session_id);
748    name == format!("{session_prefix}{MEMORY_ENVELOPE_SUFFIX}")
749        || (name.starts_with(&format!("{session_prefix}_")) && name.ends_with(MEMORY_ENVELOPE_SUFFIX))
750}
751
752fn parse_task_tracker_snapshot(content: &str) -> TaskTrackerSnapshot {
753    let title = content
754        .lines()
755        .find(|line| line.starts_with("# "))
756        .map(|line| line.trim_start_matches("# ").trim().to_string());
757    let checklist = content
758        .lines()
759        .filter(|line| line.trim_start().starts_with("- ["))
760        .take(5)
761        .map(normalize_whitespace)
762        .collect::<Vec<_>>();
763    let verification_summary = extract_verification_summary(content, &checklist);
764    let verification_todo = content
765        .lines()
766        .filter(|line| line.trim_start().starts_with("- [ ]"))
767        .take(MEMORY_LIST_LIMIT)
768        .map(normalize_whitespace)
769        .collect::<Vec<_>>();
770    let summary = match (title.clone(), checklist.is_empty()) {
771        (Some(title), false) => Some(format!("{title}: {}", checklist.join(" | "))),
772        (Some(title), true) => Some(title),
773        (None, false) => Some(checklist.join(" | ")),
774        (None, true) => None,
775    };
776
777    TaskTrackerSnapshot {
778        summary,
779        objective: title,
780        verification_summary,
781        verification_todo,
782    }
783}
784
785pub fn read_task_tracker_snapshot(workspace_root: &Path) -> TaskTrackerSnapshot {
786    let tracker_path = current_task_path(workspace_root);
787    fs::read_to_string(&tracker_path)
788        .ok()
789        .map(|content| parse_task_tracker_snapshot(&content))
790        .unwrap_or_default()
791}
792
793/// Read the task tracker without blocking the async runtime.
794pub async fn read_task_tracker_snapshot_async(workspace_root: &Path) -> TaskTrackerSnapshot {
795    let tracker_path = current_task_path(workspace_root);
796    async_fs::read_to_string(tracker_path)
797        .await
798        .ok()
799        .map(|content| parse_task_tracker_snapshot(&content))
800        .unwrap_or_default()
801}
802
803fn extract_verification_summary(content: &str, checklist: &[String]) -> Option<String> {
804    let verify_commands = collect_structured_verify_commands(content);
805    if !verify_commands.is_empty() {
806        return Some(render_bullet_list(&verify_commands));
807    }
808
809    let fallback_lines = checklist
810        .iter()
811        .filter(|line| looks_like_verification_line(line))
812        .cloned()
813        .collect::<Vec<_>>();
814    (!fallback_lines.is_empty()).then(|| fallback_lines.join("\n"))
815}
816
817/// Split the tail of a `verify:` line into clean commands.
818///
819/// Plan writers sometimes emit `verify: [a] and verify: [b]` on one line.
820/// Strip at most one matching outer `[`…`]` pair per piece and drop empties so
821/// a spliced marker can never leak into `verification_summary`.
822fn split_verify_command_tail(rest: &str) -> Vec<String> {
823    rest.split(" and verify:")
824        .map(str::trim)
825        .map(strip_one_outer_bracket_pair)
826        .filter(|piece| !piece.is_empty())
827        .map(normalize_whitespace)
828        .filter(|piece| !piece.is_empty())
829        .collect()
830}
831
832fn strip_one_outer_bracket_pair(piece: &str) -> &str {
833    let trimmed = piece.trim();
834    // Plan splices can leave the closing bracket off (`verify: [cmd`).
835    let Some(inner) = trimmed.strip_prefix('[').map(str::trim_start) else {
836        return trimmed;
837    };
838    match inner.strip_suffix(']') {
839        Some(stripped) => stripped.trim_end(),
840        None => inner,
841    }
842}
843
844fn collect_structured_verify_commands(content: &str) -> Vec<String> {
845    let mut commands = Vec::new();
846    let mut in_verify_block = false;
847
848    for line in content.lines() {
849        let trimmed = line.trim_start();
850        if let Some(rest) = trimmed.strip_prefix("verify:") {
851            for command in split_verify_command_tail(rest) {
852                commands.push(command);
853            }
854            in_verify_block = rest.trim().is_empty();
855            continue;
856        }
857
858        if !in_verify_block {
859            continue;
860        }
861
862        if trimmed.is_empty() {
863            continue;
864        }
865
866        if (line.starts_with(' ') || line.starts_with('\t')) && trimmed.starts_with("- ") {
867            commands.push(normalize_whitespace(trimmed.trim_start_matches("- ")));
868            continue;
869        }
870
871        in_verify_block = false;
872    }
873
874    commands
875}
876
877fn render_bullet_list(items: &[String]) -> String {
878    items.iter().map(|item| format!("- {item}")).collect::<Vec<_>>().join("\n")
879}
880
881fn looks_like_verification_line(line: &str) -> bool {
882    let lowered = line.to_ascii_lowercase();
883    [
884        "verify",
885        "verification",
886        "test",
887        "lint",
888        "cargo check",
889        "check-dev.sh",
890        "check.sh",
891    ]
892    .iter()
893    .any(|keyword| lowered.contains(keyword))
894}
895
896fn memory_envelope_path_from_history_path(workspace_root: &Path, history_path: &Path) -> PathBuf {
897    let absolute_history_path = if history_path.is_absolute() {
898        history_path.to_path_buf()
899    } else {
900        workspace_root.join(history_path)
901    };
902
903    let file_name = absolute_history_path
904        .file_name()
905        .and_then(|name| name.to_str())
906        .map(|name| {
907            if let Some(stem) = name.strip_suffix(".jsonl") {
908                format!("{stem}{MEMORY_ENVELOPE_SUFFIX}")
909            } else {
910                format!("{name}{MEMORY_ENVELOPE_SUFFIX}")
911            }
912        })
913        .unwrap_or_else(|| format!("session_memory{MEMORY_ENVELOPE_SUFFIX}"));
914
915    let parent = absolute_history_path
916        .parent()
917        .map(Path::to_path_buf)
918        .unwrap_or_else(|| workspace_root.join(".vtcode").join("history"));
919    parent.join(file_name)
920}
921
922pub fn default_memory_envelope_path_for_session(workspace_root: &Path, session_id: &str) -> PathBuf {
923    workspace_root
924        .join(".vtcode")
925        .join("history")
926        .join(format!("{}{MEMORY_ENVELOPE_SUFFIX}", sanitize_session_id(session_id)))
927}
928
929fn memory_envelope_paths_for_session(workspace_root: &Path, session_id: &str) -> Vec<PathBuf> {
930    let history_dir = workspace_root.join(".vtcode").join("history");
931    let mut candidates = fs::read_dir(history_dir)
932        .ok()
933        .into_iter()
934        .flat_map(|entries| entries.flatten())
935        .map(|entry| entry.path())
936        .filter(|path| {
937            path.file_name()
938                .and_then(|name| name.to_str())
939                .is_some_and(|name| memory_envelope_file_matches_session(name, session_id))
940        })
941        .collect::<Vec<_>>();
942    candidates.sort_by(|left, right| {
943        let left_modified = fs::metadata(left).and_then(|metadata| metadata.modified()).ok();
944        let right_modified = fs::metadata(right).and_then(|metadata| metadata.modified()).ok();
945        right_modified
946            .cmp(&left_modified)
947            .then_with(|| right.file_name().cmp(&left.file_name()))
948    });
949    candidates
950}
951
952pub fn latest_memory_envelope_path_for_session(workspace_root: &Path, session_id: &str) -> Option<PathBuf> {
953    memory_envelope_paths_for_session(workspace_root, session_id)
954        .into_iter()
955        .find(|path| {
956            fs::read_to_string(path)
957                .ok()
958                .and_then(|content| serde_json::from_str::<SessionMemoryEnvelope>(&content).ok())
959                .is_some_and(|envelope| envelope.session_id.is_empty() || envelope.session_id == session_id)
960        })
961}
962
963pub fn load_latest_memory_envelope(workspace_root: &Path, session_id: &str) -> Option<SessionMemoryEnvelope> {
964    let path = latest_memory_envelope_path_for_session(workspace_root, session_id)?;
965    let content = fs::read_to_string(path).ok()?;
966    let envelope: SessionMemoryEnvelope = serde_json::from_str(&content).ok()?;
967    if !envelope.session_id.is_empty() && envelope.session_id != session_id {
968        return None;
969    }
970    Some(envelope)
971}
972
973async fn memory_envelope_paths_for_session_async(workspace_root: &Path, session_id: &str) -> Vec<PathBuf> {
974    let history_dir = workspace_root.join(".vtcode").join("history");
975    let mut candidates = Vec::new();
976    let Ok(mut entries) = async_fs::read_dir(history_dir).await else {
977        return candidates;
978    };
979
980    while let Ok(Some(entry)) = entries.next_entry().await {
981        let path = entry.path();
982        let matches = path
983            .file_name()
984            .and_then(|name| name.to_str())
985            .is_some_and(|name| memory_envelope_file_matches_session(name, session_id));
986        if matches {
987            candidates.push(path);
988        }
989    }
990
991    let mut modified = Vec::with_capacity(candidates.len());
992    for path in candidates {
993        let timestamp = async_fs::metadata(&path)
994            .await
995            .ok()
996            .and_then(|metadata| metadata.modified().ok());
997        modified.push((timestamp, path));
998    }
999    modified.sort_by(|(left_time, left_path), (right_time, right_path)| {
1000        right_time
1001            .cmp(left_time)
1002            .then_with(|| right_path.file_name().cmp(&left_path.file_name()))
1003    });
1004    modified.into_iter().map(|(_, path)| path).collect()
1005}
1006
1007/// Find and deserialize the newest valid envelope without synchronously
1008/// scanning historical candidates on the runtime thread.
1009pub async fn latest_memory_envelope_path_for_session_async(workspace_root: &Path, session_id: &str) -> Option<PathBuf> {
1010    for path in memory_envelope_paths_for_session_async(workspace_root, session_id).await {
1011        let Ok(content) = async_fs::read_to_string(&path).await else {
1012            continue;
1013        };
1014        let Ok(envelope) = serde_json::from_str::<SessionMemoryEnvelope>(&content) else {
1015            continue;
1016        };
1017        if envelope.session_id.is_empty() || envelope.session_id == session_id {
1018            return Some(path);
1019        }
1020    }
1021    None
1022}
1023
1024pub async fn load_latest_memory_envelope_async(
1025    workspace_root: &Path,
1026    session_id: &str,
1027) -> Option<SessionMemoryEnvelope> {
1028    let path = latest_memory_envelope_path_for_session_async(workspace_root, session_id).await?;
1029    let content = async_fs::read_to_string(path).await.ok()?;
1030    let envelope: SessionMemoryEnvelope = serde_json::from_str(&content).ok()?;
1031    if !envelope.session_id.is_empty() && envelope.session_id != session_id {
1032        return None;
1033    }
1034    Some(envelope)
1035}
1036
1037pub fn insert_memory_envelope_message(
1038    history: &mut Vec<Message>,
1039    envelope: &SessionMemoryEnvelope,
1040    placement: MemoryEnvelopePlacement,
1041) {
1042    let message = memory_envelope_message(envelope);
1043    match placement {
1044        MemoryEnvelopePlacement::Start => history.insert(0, message),
1045        MemoryEnvelopePlacement::BeforeLastUserOrSummary => {
1046            let insert_at = history
1047                .iter()
1048                .rposition(|item| item.role == MessageRole::User || is_compaction_summary_message(item))
1049                .unwrap_or(0);
1050            history.insert(insert_at, message);
1051        }
1052    }
1053}
1054
1055fn apply_memory_envelope(
1056    compacted: &mut Vec<Message>,
1057    envelope: &SessionMemoryEnvelope,
1058    placement: MemoryEnvelopePlacement,
1059) {
1060    strip_existing_memory_envelope(compacted);
1061    insert_memory_envelope_message(compacted, envelope, placement);
1062}
1063
1064pub fn inject_latest_memory_envelope(workspace_root: &Path, session_id: &str, history: &mut Vec<Message>) -> bool {
1065    let Some(envelope) = load_latest_memory_envelope(workspace_root, session_id) else {
1066        return false;
1067    };
1068
1069    strip_existing_memory_envelope(history);
1070    insert_memory_envelope_message(history, &envelope, MemoryEnvelopePlacement::Start);
1071    true
1072}
1073
1074pub fn write_memory_envelope_to_path(path: &Path, envelope: &SessionMemoryEnvelope) -> anyhow::Result<()> {
1075    let serialized = serde_json::to_vec_pretty(envelope).context("serialize memory envelope")?;
1076    vtcode_commons::VtCodePaths::write_private_file_atomic(path, &serialized)
1077        .with_context(|| format!("write memory envelope {}", path.display()))
1078}
1079
1080/// Write an envelope through the shared private-file policy on a blocking worker.
1081/// The synced, exclusive temporary file is created beside the destination and
1082/// renamed over it without first removing the last committed envelope.
1083pub async fn write_memory_envelope_to_path_async(path: &Path, envelope: &SessionMemoryEnvelope) -> anyhow::Result<()> {
1084    let serialized = serde_json::to_vec_pretty(envelope).context("serialize memory envelope")?;
1085    vtcode_commons::fs::write_private_file_atomic(path, &serialized)
1086        .await
1087        .with_context(|| format!("write memory envelope {}", path.display()))
1088}
1089
1090pub fn has_latest_memory_envelope(workspace_root: &Path, session_id: &str) -> bool {
1091    latest_memory_envelope_path_for_session(workspace_root, session_id).is_some()
1092}
1093
1094// ---------------------------------------------------------------------------
1095// Local compaction configuration + zero-cost fork history
1096// ---------------------------------------------------------------------------
1097
1098pub fn configured_retained_user_messages(vt_cfg: Option<&VTCodeConfig>) -> usize {
1099    vt_cfg.map(|cfg| cfg.context.dynamic.retained_user_messages).unwrap_or(4)
1100}
1101
1102pub fn local_compaction_config(vt_cfg: Option<&VTCodeConfig>, always_summarize: bool) -> CompactionConfig {
1103    CompactionConfig {
1104        always_summarize,
1105        retained_user_messages: configured_retained_user_messages(vt_cfg),
1106        ..CompactionConfig::default()
1107    }
1108}
1109
1110fn collect_zero_cost_retained_user_messages(
1111    history: &[Message],
1112    token_budget: usize,
1113    max_messages: usize,
1114) -> Vec<Message> {
1115    if token_budget == 0 || max_messages == 0 {
1116        return Vec::new();
1117    }
1118
1119    let mut kept = Vec::new();
1120    let mut remaining = token_budget;
1121
1122    for message in history.iter().rev() {
1123        if kept.len() >= max_messages {
1124            break;
1125        }
1126        if message.role != MessageRole::User || message.content.trim().is_empty() {
1127            continue;
1128        }
1129
1130        let estimated = message.estimate_tokens();
1131        if estimated <= remaining {
1132            kept.push(message.clone());
1133            remaining = remaining.saturating_sub(estimated);
1134            continue;
1135        }
1136
1137        if remaining > 4 {
1138            let truncated = truncate_to_token_limit(message.content.as_text().as_ref(), remaining.saturating_sub(4));
1139            let trimmed = truncated.trim();
1140            if !trimmed.is_empty() {
1141                kept.push(Message::user(trimmed.to_string()));
1142            }
1143        }
1144        break;
1145    }
1146
1147    kept.reverse();
1148    kept
1149}
1150
1151pub fn build_zero_cost_summarized_fork_history(
1152    source_history: &[Message],
1153    source_envelope: Option<&SessionMemoryEnvelope>,
1154    retained_user_messages: usize,
1155) -> Vec<Message> {
1156    let summary = source_envelope
1157        .map(|envelope| normalize_whitespace(&envelope.summary))
1158        .filter(|summary| !summary.is_empty())
1159        .unwrap_or_else(|| derive_continuity_summary(source_history, source_envelope, &TaskTrackerSnapshot::default()));
1160
1161    let retained_users = collect_zero_cost_retained_user_messages(
1162        source_history,
1163        CompactionConfig::default().retained_user_message_tokens,
1164        retained_user_messages,
1165    );
1166
1167    let mut compacted = Vec::with_capacity(retained_users.len().saturating_add(1));
1168    compacted.push(Message::system(format!("Previous conversation summary:\n{}", summary.trim())));
1169    compacted.extend(retained_users);
1170    compacted
1171}
1172
1173// ---------------------------------------------------------------------------
1174// File-read de-duplication for local compaction
1175// ---------------------------------------------------------------------------
1176
1177#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1178struct FileReadDedupKey {
1179    target: String,
1180    start_line: Option<u64>,
1181    end_line: Option<u64>,
1182    spool_path: Option<String>,
1183}
1184
1185#[derive(Debug, Clone, PartialEq, Eq)]
1186struct FileReadDedupCandidate {
1187    key: FileReadDedupKey,
1188    placeholder_content: String,
1189}
1190
1191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1192enum FileReadToolKind {
1193    ReadFile,
1194    UnifiedFileRead,
1195}
1196
1197fn is_read_file_tool_name(tool_name: &str) -> bool {
1198    tool_name == tool_names::READ_FILE || tool_name.ends_with(".read_file")
1199}
1200
1201fn collect_file_read_tool_kinds(history: &[Message]) -> HashMap<String, FileReadToolKind> {
1202    let mut kinds = HashMap::new();
1203    for message in history {
1204        let Some(tool_calls) = message.tool_calls.as_ref() else {
1205            continue;
1206        };
1207        for tc in tool_calls {
1208            let Some(tn) = tc.tool_name() else {
1209                continue;
1210            };
1211            let kind = if is_read_file_tool_name(tn) {
1212                Some(FileReadToolKind::ReadFile)
1213            } else if tn == tool_names::UNIFIED_FILE {
1214                tc.execution_arguments().ok().and_then(|args| {
1215                    args.get("action")
1216                        .and_then(Value::as_str)
1217                        .filter(|a| *a == "read")
1218                        .map(|_| FileReadToolKind::UnifiedFileRead)
1219                })
1220            } else {
1221                None
1222            };
1223            if let Some(k) = kind {
1224                kinds.insert(tc.id.clone(), k);
1225            }
1226        }
1227    }
1228    kinds
1229}
1230
1231fn normalize_file_read_target(value: &str) -> Option<String> {
1232    let trimmed = value.trim();
1233    (!trimmed.is_empty()).then(|| trimmed.replace('\\', "/"))
1234}
1235
1236fn build_file_read_dedup_key(payload: &Value) -> Option<FileReadDedupKey> {
1237    let obj = payload.as_object()?;
1238    if obj.get("items").is_some()
1239        || obj.get("error").is_some()
1240        || obj.get("spool_chunked").and_then(Value::as_bool).unwrap_or(false)
1241        || obj.get("has_more").and_then(Value::as_bool).unwrap_or(false)
1242    {
1243        return None;
1244    }
1245    let target = obj
1246        .get("file_path")
1247        .and_then(Value::as_str)
1248        .or_else(|| obj.get("path").and_then(Value::as_str))
1249        .and_then(normalize_file_read_target)?;
1250    Some(FileReadDedupKey {
1251        target,
1252        start_line: obj.get("start_line").and_then(Value::as_u64),
1253        end_line: obj.get("end_line").and_then(Value::as_u64),
1254        spool_path: obj
1255            .get("spool_path")
1256            .and_then(Value::as_str)
1257            .and_then(normalize_file_read_target),
1258    })
1259}
1260
1261fn build_file_read_placeholder_content(payload: &Value, key: &FileReadDedupKey) -> String {
1262    let mut p = serde_json::Map::new();
1263    p.insert("deduped_read".into(), Value::Bool(true));
1264    p.insert("note".into(), Value::String(DEDUPED_FILE_READ_NOTE.to_string()));
1265
1266    fn maybe_str(p: &mut serde_json::Map<String, Value>, payload: &Value, key: &str) {
1267        if let Some(s) = payload
1268            .get(key)
1269            .and_then(Value::as_str)
1270            .map(str::trim)
1271            .filter(|s| !s.is_empty())
1272        {
1273            p.insert(key.into(), Value::String(s.to_string()));
1274        }
1275    }
1276
1277    maybe_str(&mut p, payload, "file_path");
1278    maybe_str(&mut p, payload, "path");
1279    if let Some(sl) = key.start_line {
1280        p.insert("start_line".into(), json!(sl));
1281    }
1282    if let Some(el) = key.end_line {
1283        p.insert("end_line".into(), json!(el));
1284    }
1285    if let Some(sp) = key.spool_path.as_deref() {
1286        p.insert("spool_path".into(), json!(sp));
1287    }
1288    Value::Object(p).to_string()
1289}
1290
1291fn file_read_dedup_candidate(
1292    message: &Message,
1293    tool_kinds: &HashMap<String, FileReadToolKind>,
1294) -> Option<FileReadDedupCandidate> {
1295    if message.role != MessageRole::Tool {
1296        return None;
1297    }
1298
1299    let kind = message
1300        .tool_call_id
1301        .as_deref()
1302        .and_then(|tool_call_id| tool_kinds.get(tool_call_id).copied())
1303        .or_else(|| {
1304            message
1305                .origin_tool
1306                .as_deref()
1307                .and_then(|tool_name| is_read_file_tool_name(tool_name).then_some(FileReadToolKind::ReadFile))
1308        })?;
1309
1310    if !matches!(kind, FileReadToolKind::ReadFile | FileReadToolKind::UnifiedFileRead) {
1311        return None;
1312    }
1313
1314    let payload: Value = serde_json::from_str(message.content.as_text().as_ref()).ok()?;
1315    let key = build_file_read_dedup_key(&payload)?;
1316
1317    Some(FileReadDedupCandidate {
1318        placeholder_content: build_file_read_placeholder_content(&payload, &key),
1319        key,
1320    })
1321}
1322
1323pub fn dedup_repeated_file_reads_for_local_compaction(history: &[Message]) -> Vec<Message> {
1324    let tool_kinds = collect_file_read_tool_kinds(history);
1325    let mut last_idx = HashMap::new();
1326    let mut candidates = Vec::new();
1327    for (i, msg) in history.iter().enumerate() {
1328        let Some(c) = file_read_dedup_candidate(msg, &tool_kinds) else {
1329            continue;
1330        };
1331        last_idx.insert(c.key.clone(), i);
1332        candidates.push((i, c));
1333    }
1334    let mut deduped = history.to_vec();
1335    let mut changed = false;
1336    for (idx, c) in candidates {
1337        if last_idx.get(&c.key).copied() == Some(idx) {
1338            continue;
1339        }
1340        if let Some(msg) = deduped.get_mut(idx) {
1341            msg.content = c.placeholder_content.into();
1342            changed = true;
1343        }
1344    }
1345    if changed { deduped } else { history.to_vec() }
1346}
1347
1348// ---------------------------------------------------------------------------
1349// Threshold resolution (shared by every compaction trigger)
1350// ---------------------------------------------------------------------------
1351
1352/// Conservative output reservation when the request does not declare a limit.
1353pub const DEFAULT_OUTPUT_RESERVE_TOKENS: usize = 4096;
1354
1355/// Resolve a prompt threshold while preserving room for the next response.
1356pub fn resolve_compaction_threshold(configured_threshold: Option<u64>, context_size: usize) -> Option<u64> {
1357    resolve_compaction_threshold_with_reserve(configured_threshold, context_size, DEFAULT_OUTPUT_RESERVE_TOKENS)
1358}
1359
1360pub fn resolve_compaction_threshold_with_reserve(
1361    configured_threshold: Option<u64>,
1362    context_size: usize,
1363    reserved_output_tokens: usize,
1364) -> Option<u64> {
1365    let configured = configured_threshold.filter(|value| *value > 0);
1366    if context_size == 0 {
1367        return configured;
1368    }
1369    let prompt_budget = context_size.saturating_sub(reserved_output_tokens).max(1) as u64;
1370    // Default trigger is a ratio of the prompt budget so long runs compact
1371    // before the expensive near-full zone (HarnessTax / session-efficiency).
1372    // An explicit `auto_compaction_threshold_tokens` still wins, capped at the
1373    // prompt budget so compaction never exceeds the usable window.
1374    // Integer percent avoids f64→u64 cast lint; `default_compaction_trigger_uses_ratio_of_prompt_budget`
1375    // pins this to `DEFAULT_COMPACTION_TRIGGER_RATIO`.
1376    const TRIGGER_RATIO_PERCENT: u64 = 75;
1377    let default_trigger = prompt_budget.saturating_mul(TRIGGER_RATIO_PERCENT) / 100;
1378    let default_trigger = default_trigger.clamp(1, prompt_budget);
1379    Some(configured.map_or(default_trigger, |value| value.min(prompt_budget)))
1380}
1381
1382/// Explicit trigger overrides can reduce, but never bypass, the session ceiling.
1383pub fn resolve_effective_compaction_threshold(
1384    configured_threshold: Option<u64>,
1385    provider_context_size: usize,
1386    session_context_budget: usize,
1387) -> Option<u64> {
1388    resolve_compaction_threshold(
1389        configured_threshold,
1390        effective_session_context_budget(provider_context_size, session_context_budget),
1391    )
1392}
1393
1394/// Zero means unknown/unconfigured; positive limits are intersected.
1395#[must_use]
1396pub fn effective_session_context_budget(provider_context_size: usize, session_context_budget: usize) -> usize {
1397    match (provider_context_size > 0, session_context_budget > 0) {
1398        (true, true) => provider_context_size.min(session_context_budget),
1399        (true, false) => provider_context_size,
1400        (false, true) => session_context_budget,
1401        (false, false) => 0,
1402    }
1403}
1404
1405/// Resolve catalog/dynamic model capacity and the provider's route-specific ceiling.
1406#[must_use]
1407pub fn effective_context_budget(vt_cfg: Option<&VTCodeConfig>, provider: &dyn LLMProvider, model: &str) -> usize {
1408    use crate::llm::model_resolver::{DynamicModelMeta, ModelResolver};
1409
1410    let provider_capacity = provider.effective_context_size(model);
1411    // Resolve through the shared model capability path so catalog entries and
1412    // discovered model metadata participate in exactly the same calculation as
1413    // request construction. The provider remains a hard route-specific ceiling
1414    // because a catalog can describe a larger platform window than this endpoint
1415    // exposes (or an explicit `ContextWindowProvider` override can narrow it).
1416    let resolved_capacity = ModelResolver::resolve(
1417        Some(provider.name()),
1418        model,
1419        &[],
1420        Some(DynamicModelMeta {
1421            display_name: model.to_owned(),
1422            description: None,
1423            context_window: (provider_capacity > 0).then_some(provider_capacity),
1424        }),
1425    )
1426    .and_then(|resolved| resolved.context_window())
1427    // Custom provider names and dynamic model ids are intentionally not
1428    // required to exist in the built-in catalog. The provider trait has
1429    // already resolved the route-specific capacity, so keep that value when
1430    // catalog resolution cannot identify the route.
1431    .unwrap_or(provider_capacity);
1432    let capacity = effective_session_context_budget(resolved_capacity, provider_capacity);
1433    let session_budget = vt_cfg.map_or_else(default_max_context_tokens, |cfg| cfg.context.max_context_tokens);
1434    effective_session_context_budget(capacity, session_budget)
1435}
1436
1437pub fn effective_compaction_threshold_with_reserve(
1438    vt_cfg: Option<&VTCodeConfig>,
1439    provider: &dyn LLMProvider,
1440    model: &str,
1441    reserved_output_tokens: usize,
1442) -> Option<usize> {
1443    resolve_compaction_threshold_with_reserve(
1444        vt_cfg.and_then(|cfg| cfg.agent.harness.auto_compaction_threshold_tokens),
1445        effective_context_budget(vt_cfg, provider, model),
1446        reserved_output_tokens,
1447    )
1448    .and_then(|value| usize::try_from(value).ok())
1449}
1450
1451pub fn effective_compaction_threshold(
1452    vt_cfg: Option<&VTCodeConfig>,
1453    provider: &dyn LLMProvider,
1454    model: &str,
1455) -> Option<usize> {
1456    let reserve = provider
1457        .sampling_overrides(model)
1458        .max_tokens
1459        .map_or(DEFAULT_OUTPUT_RESERVE_TOKENS, |value| value as usize);
1460    effective_compaction_threshold_with_reserve(vt_cfg, provider, model, reserve)
1461}
1462
1463#[cfg(test)]
1464mod persistence_tests;
1465
1466#[cfg(test)]
1467mod tests {
1468    use super::extract_compaction_summary;
1469    use super::{
1470        SessionMemoryEnvelope, TaskTrackerSnapshot, build_session_memory_envelope, parse_task_tracker_snapshot,
1471        resolve_compaction_threshold_with_reserve,
1472    };
1473    use crate::llm::provider::Message;
1474    use std::path::Path;
1475
1476    #[test]
1477    fn default_compaction_trigger_uses_ratio_of_prompt_budget() {
1478        // 100_000 context, 4_096 reserve → prompt budget 95_904.
1479        // Default trigger is 75% of the prompt budget, not the full budget.
1480        let threshold = resolve_compaction_threshold_with_reserve(None, 100_000, 4_096).expect("threshold");
1481        let prompt_budget = 100_000u64 - 4_096;
1482        let expected = prompt_budget * 75 / 100;
1483        assert_eq!(threshold, expected);
1484        // Keep the integer percent in sync with the shared ratio constant.
1485        assert!((vtcode_config::constants::context::DEFAULT_COMPACTION_TRIGGER_RATIO - 0.75).abs() < f64::EPSILON);
1486        assert!(threshold < prompt_budget, "default trigger must fire before the full prompt budget");
1487        // Explicit config still wins and is capped at the prompt budget.
1488        assert_eq!(resolve_compaction_threshold_with_reserve(Some(10_000), 100_000, 4_096), Some(10_000));
1489        assert_eq!(resolve_compaction_threshold_with_reserve(Some(200_000), 100_000, 4_096), Some(prompt_budget));
1490    }
1491
1492    fn tracker_snapshot(summary: &str, objective: &str, todo: &[&str]) -> TaskTrackerSnapshot {
1493        let markdown = format!("# {objective}\n\n- [ ] {}\n", todo.join("\n- [ ] "));
1494        let mut snap = parse_task_tracker_snapshot(&markdown);
1495        snap.summary = Some(summary.to_string());
1496        snap.objective = Some(objective.to_string());
1497        snap.verification_todo = todo.iter().map(|s| (*s).to_string()).collect();
1498        snap
1499    }
1500
1501    #[test]
1502    fn envelope_prefers_live_objective_over_stale_prior() {
1503        let prior = SessionMemoryEnvelope {
1504            session_id: "sess-a".to_string(),
1505            objective: Some("1789-mighty-harbor".to_string()),
1506            task_summary: Some("mighty-harbor: README checklist".to_string()),
1507            verification_todo: vec!["mighty todo".to_string()],
1508            ..Default::default()
1509        };
1510        let live = tracker_snapshot("bright-squid analyze fix", "1789-bright-squid", &["cargo check analyze"]);
1511
1512        let envelope = build_session_memory_envelope(
1513            "sess-b",
1514            Path::new("."),
1515            &[],
1516            &[],
1517            "Working on bright-squid".to_string(),
1518            None,
1519            Some(&prior),
1520            &live,
1521            None,
1522        );
1523
1524        assert_eq!(envelope.objective.as_deref(), Some("1789-bright-squid"));
1525        assert!(
1526            envelope.task_summary.as_deref().unwrap_or_default().contains("bright-squid"),
1527            "task_summary must not keep prior-task narrative: {:?}",
1528            envelope.task_summary
1529        );
1530        assert_eq!(envelope.verification_todo, vec!["cargo check analyze".to_string()]);
1531    }
1532
1533    #[test]
1534    fn envelope_objective_change_drops_prior_task_summary_when_live_empty() {
1535        let prior = SessionMemoryEnvelope {
1536            session_id: "sess-a".to_string(),
1537            objective: Some("task-a".to_string()),
1538            task_summary: Some("task-a: stale checklist".to_string()),
1539            verification_todo: vec!["stale".to_string()],
1540            ..Default::default()
1541        };
1542        let live = TaskTrackerSnapshot {
1543            objective: Some("task-b".to_string()),
1544            summary: None,
1545            ..Default::default()
1546        };
1547
1548        let envelope = build_session_memory_envelope(
1549            "sess-b",
1550            Path::new("."),
1551            &[],
1552            &[],
1553            "summary".to_string(),
1554            None,
1555            Some(&prior),
1556            &live,
1557            None,
1558        );
1559
1560        assert_eq!(envelope.objective.as_deref(), Some("task-b"));
1561        assert_eq!(envelope.task_summary, None);
1562        assert!(envelope.verification_todo.is_empty());
1563    }
1564
1565    #[test]
1566    fn envelope_same_objective_keeps_todo_merge() {
1567        let prior = SessionMemoryEnvelope {
1568            session_id: "sess-a".to_string(),
1569            objective: Some("task-1".to_string()),
1570            task_summary: Some("task-1: shared".to_string()),
1571            verification_todo: vec!["keep me".to_string()],
1572            ..Default::default()
1573        };
1574        let live = tracker_snapshot("task-1 continued", "task-1", &["new item"]);
1575
1576        let envelope = build_session_memory_envelope(
1577            "sess-a",
1578            Path::new("."),
1579            &[],
1580            &[],
1581            "summary".to_string(),
1582            None,
1583            Some(&prior),
1584            &live,
1585            None,
1586        );
1587
1588        assert_eq!(envelope.objective.as_deref(), Some("task-1"));
1589        assert!(envelope.verification_todo.contains(&"keep me".to_string()));
1590        assert!(envelope.verification_todo.contains(&"new item".to_string()));
1591    }
1592
1593    #[test]
1594    fn envelope_stale_artifact_resets_prior_constraints() {
1595        let workspace = tempfile::tempdir().expect("tempdir");
1596        let tasks_dir = workspace.path().join(".vtcode").join("tasks");
1597        std::fs::create_dir_all(&tasks_dir).expect("tasks dir");
1598        std::fs::create_dir_all(workspace.path().join(".vtcode").join("sessions").join("sess-stale"))
1599            .expect("session dir anchors the artifact cutoff");
1600        let spec_path = tasks_dir.join("current_spec.md");
1601        std::fs::write(&spec_path, "# Spec\n- Do not touch prod config\n").expect("write stale spec");
1602        let stale = std::time::SystemTime::now() - std::time::Duration::from_secs(48 * 60 * 60);
1603        let file = std::fs::File::options().write(true).open(&spec_path).expect("open");
1604        file.set_modified(stale).expect("set mtime");
1605
1606        let prior = SessionMemoryEnvelope {
1607            session_id: "sess-stale".to_string(),
1608            constraints: vec!["Do not touch prod config".to_string(), "Keep user budget".to_string()],
1609            ..Default::default()
1610        };
1611
1612        let envelope = build_session_memory_envelope(
1613            "sess-stale",
1614            workspace.path(),
1615            &[],
1616            &[],
1617            "summary".to_string(),
1618            None,
1619            Some(&prior),
1620            &tracker_snapshot("continuing", "sess-stale", &["cargo check"]),
1621            None,
1622        );
1623
1624        assert!(envelope.spec_summary.is_none(), "stale spec must not describe the session");
1625        assert!(
1626            envelope.constraints.is_empty(),
1627            "a stale artifact resets the constraints channel so its lines cannot re-enter: {:?}",
1628            envelope.constraints
1629        );
1630    }
1631
1632    #[test]
1633    fn envelope_fresh_artifact_merges_prior_constraints() {
1634        let workspace = tempfile::tempdir().expect("tempdir");
1635        let tasks_dir = workspace.path().join(".vtcode").join("tasks");
1636        std::fs::create_dir_all(&tasks_dir).expect("tasks dir");
1637        std::fs::create_dir_all(workspace.path().join(".vtcode").join("sessions").join("sess-fresh"))
1638            .expect("session dir anchors the artifact cutoff");
1639        std::fs::write(tasks_dir.join("current_spec.md"), "# Spec\n- Keep coverage at 70%\n")
1640            .expect("write fresh spec");
1641
1642        let prior = SessionMemoryEnvelope {
1643            session_id: "sess-fresh".to_string(),
1644            constraints: vec!["Do not redesign the harness".to_string()],
1645            ..Default::default()
1646        };
1647
1648        let envelope = build_session_memory_envelope(
1649            "sess-fresh",
1650            workspace.path(),
1651            &[],
1652            &[],
1653            "summary".to_string(),
1654            None,
1655            Some(&prior),
1656            &tracker_snapshot("continuing", "sess-fresh", &["cargo check"]),
1657            None,
1658        );
1659
1660        assert!(
1661            envelope.constraints.contains(&"Do not redesign the harness".to_string()),
1662            "fresh artifacts keep the continuity merge of inherited constraints: {:?}",
1663            envelope.constraints
1664        );
1665        assert!(
1666            envelope.constraints.contains(&"Keep coverage at 70%".to_string()),
1667            "fresh artifact constraints are extracted: {:?}",
1668            envelope.constraints
1669        );
1670    }
1671
1672    #[test]
1673    fn local_summary_takes_precedence_over_retained_provider_detail() {
1674        let compacted = vec![
1675            Message::system("Previous conversation summary:\nnew local summary".to_string()),
1676            Message::user("latest request".to_string()),
1677            Message::assistant(String::new()).with_reasoning_details(Some(vec![serde_json::json!({
1678                "type": "compaction",
1679                "content": "stale provider summary",
1680            })])),
1681        ];
1682
1683        assert_eq!(extract_compaction_summary(&compacted, &[]), "new local summary");
1684    }
1685
1686    #[test]
1687    fn split_verify_command_tail_splits_and_strips_brackets() {
1688        let tail = " [cargo nextest run -E 'test(turn_loop_helpers) or test(tool_outcomes) or test(blocked_handoff)'] and verify: [cargo check --locked";
1689        let commands = super::split_verify_command_tail(tail);
1690        assert_eq!(
1691            commands,
1692            vec![
1693                "cargo nextest run -E 'test(turn_loop_helpers) or test(tool_outcomes) or test(blocked_handoff)'"
1694                    .to_string(),
1695                "cargo check --locked".to_string(),
1696            ]
1697        );
1698    }
1699
1700    #[test]
1701    fn split_verify_command_tail_keeps_legitimate_inner_brackets() {
1702        // Only one outer pair is stripped; array/subscript syntax inside the
1703        // command must survive.
1704        let commands = super::split_verify_command_tail(" cargo test --features 'a[b]' ");
1705        assert_eq!(commands, vec!["cargo test --features 'a[b]'".to_string()]);
1706    }
1707
1708    #[test]
1709    fn structured_verify_commands_do_not_splice_bracketed_pairs() {
1710        let content =
1711            "# Fix\n\n- [x] step\n  files: src/x.rs\n  verify: [cargo check --locked] and verify: [cargo fmt --check\n";
1712        let commands = super::collect_structured_verify_commands(content);
1713        assert_eq!(commands, vec!["cargo check --locked".to_string(), "cargo fmt --check".to_string()]);
1714        let summary = super::extract_verification_summary(content, &[]).expect("summary");
1715        assert!(!summary.contains("] and verify:"), "splice marker must not leak: {summary}");
1716    }
1717}