Skip to main content

vtcode_memory/progress/
goal_api.rs

1//! Runtime-facing [`GoalTracker`](super::GoalTracker) API and persistence.
2//!
3//! The state machine itself lives in [`super`]; this module holds the small
4//! public surface the runloop and frontends use (read accessors, token/elapsed
5//! accounting, objective edits) plus `goal.json` save/restore under the
6//! session's `goal/` directory. Restoring demotes any in-flight goal to
7//! paused (see [`GoalTracker::from_snapshot`](super::GoalTracker::from_snapshot)),
8//! so a reloaded goal never resumes driving itself.
9
10use std::path::PathBuf;
11
12use super::{GoalOrchestration, GoalStatus, GoalTracker};
13use crate::error::SessionStoreError;
14
15/// Snapshot filename inside the session's `goal/` directory.
16const GOAL_SNAPSHOT_FILE: &str = "goal.json";
17
18impl GoalStatus {
19    /// Wire value used in persisted snapshots (`"active"`, `"user_paused"`, …).
20    #[must_use]
21    pub const fn as_str(self) -> &'static str {
22        match self {
23            Self::Active => "active",
24            Self::UserPaused => "user_paused",
25            Self::BackOffPaused => "back_off_paused",
26            Self::NoProgressPaused => "no_progress_paused",
27            Self::InfraPaused => "infra_paused",
28            Self::Blocked => "blocked",
29            Self::BudgetLimited => "budget_limited",
30            Self::Complete => "complete",
31        }
32    }
33
34    /// Short human-readable label for status lines.
35    #[must_use]
36    pub const fn display_name(self) -> &'static str {
37        match self {
38            Self::Active => "Active",
39            Self::UserPaused => "Paused",
40            Self::BackOffPaused => "Paused (backing off)",
41            Self::NoProgressPaused => "Paused (no progress)",
42            Self::InfraPaused => "Paused (infra error)",
43            Self::Blocked => "Blocked",
44            Self::BudgetLimited => "Budget limited",
45            Self::Complete => "Complete",
46        }
47    }
48}
49
50impl GoalTracker {
51    /// `true` when a goal snapshot exists, regardless of lifecycle status.
52    #[must_use]
53    pub fn has_goal(&self) -> bool {
54        self.orchestration.is_some()
55    }
56
57    /// Stable goal id, if a goal exists.
58    #[must_use]
59    pub fn goal_id(&self) -> Option<&str> {
60        self.orchestration.as_ref().map(|o| o.goal_id.as_str())
61    }
62
63    /// User-facing pause message, if the goal paused with one.
64    #[must_use]
65    pub fn pause_message(&self) -> Option<&str> {
66        self.orchestration.as_ref().and_then(|o| o.pause_message.as_deref())
67    }
68
69    /// Total elapsed wall-clock time in milliseconds, including the live
70    /// portion when the goal is currently active.
71    #[must_use]
72    pub fn elapsed_ms(&self) -> u64 {
73        let base = self.orchestration.as_ref().map_or(0, |o| o.elapsed_ms);
74        if self.orchestration.is_some()
75            && let Some(since) = self.active_since
76        {
77            return base.saturating_add(since.elapsed().as_millis() as u64);
78        }
79        base
80    }
81
82    /// High-water mark of tokens spent on the goal (session total minus the
83    /// start baseline, floored at zero). Zero when no goal exists.
84    #[must_use]
85    pub fn tokens_used(&self) -> i64 {
86        self.orchestration.as_ref().map_or(0, |o| o.tokens_used_high_water)
87    }
88
89    /// Consumed auto-continue turns this episode. Zero without a goal.
90    #[must_use]
91    pub fn auto_continue_turns(&self) -> u8 {
92        self.orchestration.as_ref().map_or(0, |o| o.auto_continue_turns)
93    }
94
95    /// Atomically reserve one auto-continue turn when budget remains,
96    /// returning the 1-based turn number. `None` leaves state untouched.
97    pub fn claim_auto_continue_turn(&mut self, max_turns: u8) -> Option<u8> {
98        let o = self.orchestration.as_mut()?;
99        if o.auto_continue_turns >= max_turns {
100            return None;
101        }
102        o.auto_continue_turns = o.auto_continue_turns.saturating_add(1);
103        Some(o.auto_continue_turns)
104    }
105
106    /// Fold a session token-total observation into the high-water mark.
107    /// Monotonic, and a no-op without a goal.
108    pub fn record_token_observation(&mut self, session_total: i64) {
109        if let Some(o) = self.orchestration.as_mut() {
110            o.last_session_tokens_seen = Some(session_total);
111            let used = session_total.saturating_sub(o.token_baseline).max(0);
112            o.tokens_used_high_water = o.tokens_used_high_water.max(used);
113        }
114    }
115
116    /// Replace the token budget in place (`None` clears it). Returns `false`
117    /// when no goal exists.
118    pub fn set_token_budget(&mut self, budget: Option<i64>) -> bool {
119        if let Some(o) = self.orchestration.as_mut() {
120            o.token_budget = budget;
121            return true;
122        }
123        false
124    }
125
126    /// Mark an Active goal budget-limited when usage reached its cap.
127    /// Paused goals keep the user's explicit state. Returns `true` if applied.
128    pub fn enforce_budget(&mut self) -> bool {
129        let over = self.orchestration.as_ref().is_some_and(|o| {
130            o.status == GoalStatus::Active && o.token_budget.is_some_and(|b| o.tokens_used_high_water >= b)
131        });
132        if over { self.budget_limit() } else { false }
133    }
134
135    /// Replace the objective in place, preserving elapsed time and history.
136    /// Returns `false` when no goal exists.
137    pub fn set_objective(&mut self, objective: &str) -> bool {
138        if let Some(o) = self.orchestration.as_mut() {
139            o.objective = objective.trim().to_string();
140            return true;
141        }
142        false
143    }
144
145    /// Persist the snapshot to `<session_dir>/goal/goal.json`, creating the
146    /// directory if needed. With no goal, removes a stale snapshot instead so
147    /// a cleared goal never resurrects on restart.
148    pub fn persist(&self) -> Result<(), SessionStoreError> {
149        let dir = self.goal_dir();
150        std::fs::create_dir_all(&dir).map_err(|e| SessionStoreError::CreateDir { path: dir.clone(), source: e })?;
151        let path = dir.join(GOAL_SNAPSHOT_FILE);
152        match &self.orchestration {
153            Some(o) => {
154                let bytes = serde_json::to_vec(o)?;
155                std::fs::write(&path, bytes).map_err(|e| SessionStoreError::io(path, e))?;
156                Ok(())
157            }
158            None => {
159                if path.exists() {
160                    std::fs::remove_file(&path).map_err(|e| SessionStoreError::io(path, e))?;
161                }
162                Ok(())
163            }
164        }
165    }
166
167    /// Restore a tracker from `<session_dir>/goal/goal.json`, or return an
168    /// empty tracker when no snapshot exists. In-flight goals restore paused.
169    pub fn restore(session_dir: PathBuf) -> Result<Self, SessionStoreError> {
170        let path = session_dir.join("goal").join(GOAL_SNAPSHOT_FILE);
171        if !path.exists() {
172            return Ok(Self::new(session_dir));
173        }
174        let bytes = std::fs::read(&path).map_err(|e| SessionStoreError::io(path.clone(), e))?;
175        let snapshot: GoalOrchestration = serde_json::from_slice(&bytes)?;
176        Ok(Self::from_snapshot(session_dir, snapshot))
177    }
178
179    /// Current snapshot for event and RPC payloads; `None` without a goal.
180    #[must_use]
181    pub fn goal_snapshot(&self) -> Option<vtcode_exec_events::goal::GoalSnapshot> {
182        use vtcode_exec_events::goal::GoalSnapshot;
183        self.orchestration.as_ref().map(|o| GoalSnapshot {
184            goal_id: o.goal_id.clone(),
185            state: vtcode_exec_events::goal::GoalState::from(o.status),
186            objective: o.objective.clone(),
187            elapsed_ms: self.elapsed_ms(),
188            tokens_used: o.tokens_used_high_water,
189            token_budget: o.token_budget,
190            pause_message: o.pause_message.clone(),
191        })
192    }
193
194    /// Build the `goal.updated` payload for the current state; `goal: None`
195    /// when no goal exists.
196    #[must_use]
197    pub fn to_goal_updated_event(&self) -> vtcode_exec_events::ThreadEvent {
198        use vtcode_exec_events::goal::GoalUpdatedEvent;
199        let goal = self.goal_snapshot();
200        vtcode_exec_events::ThreadEvent::GoalUpdated(Box::new(GoalUpdatedEvent { goal }))
201    }
202}
203
204impl From<GoalStatus> for vtcode_exec_events::goal::GoalState {
205    /// Collapse the tracker's fine-grained pause reasons into the coarse wire
206    /// state. Every paused variant maps to `Paused`; terminal states map 1:1.
207    fn from(status: GoalStatus) -> Self {
208        use vtcode_exec_events::goal::GoalState;
209        match status {
210            GoalStatus::Active => GoalState::Active,
211            GoalStatus::UserPaused
212            | GoalStatus::BackOffPaused
213            | GoalStatus::NoProgressPaused
214            | GoalStatus::InfraPaused => GoalState::Paused,
215            GoalStatus::Blocked => GoalState::Blocked,
216            GoalStatus::BudgetLimited => GoalState::BudgetLimited,
217            GoalStatus::Complete => GoalState::Complete,
218        }
219    }
220}