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;
11use std::{fs, io};
12use vtcode_commons::VtCodePaths;
13
14use super::{GoalOrchestration, GoalStatus, GoalTracker};
15use crate::error::SessionStoreError;
16
17/// Snapshot filename inside the session's `goal/` directory.
18const GOAL_SNAPSHOT_FILE: &str = "goal.json";
19
20fn goal_snapshot_path(session_dir: &std::path::Path) -> Result<PathBuf, SessionStoreError> {
21    // Session IDs and the goal subdirectory are owned paths, even when a
22    // workspace ancestor is a permitted platform alias.
23    for dir in [session_dir.to_path_buf(), session_dir.join("goal")] {
24        match fs::symlink_metadata(&dir) {
25            Ok(metadata) if !metadata.is_dir() => {
26                return Err(SessionStoreError::io(dir, io::Error::other("goal storage requires a real directory")));
27            }
28            Ok(_) => (),
29            Err(err) if err.kind() == io::ErrorKind::NotFound => (),
30            Err(err) => return Err(SessionStoreError::io(dir, err)),
31        }
32    }
33    Ok(session_dir.join("goal").join(GOAL_SNAPSHOT_FILE))
34}
35
36impl GoalStatus {
37    /// Wire value used in persisted snapshots (`"active"`, `"user_paused"`, …).
38    #[must_use]
39    pub const fn as_str(self) -> &'static str {
40        match self {
41            Self::Active => "active",
42            Self::UserPaused => "user_paused",
43            Self::BackOffPaused => "back_off_paused",
44            Self::NoProgressPaused => "no_progress_paused",
45            Self::InfraPaused => "infra_paused",
46            Self::Blocked => "blocked",
47            Self::BudgetLimited => "budget_limited",
48            Self::Complete => "complete",
49        }
50    }
51
52    /// Short human-readable label for status lines.
53    #[must_use]
54    pub const fn display_name(self) -> &'static str {
55        match self {
56            Self::Active => "Active",
57            Self::UserPaused => "Paused",
58            Self::BackOffPaused => "Paused (backing off)",
59            Self::NoProgressPaused => "Paused (no progress)",
60            Self::InfraPaused => "Paused (infra error)",
61            Self::Blocked => "Blocked",
62            Self::BudgetLimited => "Budget limited",
63            Self::Complete => "Complete",
64        }
65    }
66}
67
68impl GoalTracker {
69    /// Runtime identity of the current active interval. Paused and restored goals
70    /// cannot authorize work until the user resumes them.
71    #[must_use]
72    pub fn active_activation_id(&self) -> Option<uuid::Uuid> {
73        self.activation_id.filter(|_| self.is_active())
74    }
75
76    /// Replace the live tracker only after the proposed snapshot is persisted.
77    pub fn commit(&mut self, staged: Self) -> Result<(), SessionStoreError> {
78        staged.persist()?;
79        *self = staged;
80        Ok(())
81    }
82    /// `true` when a goal snapshot exists, regardless of lifecycle status.
83    #[must_use]
84    pub fn has_goal(&self) -> bool {
85        self.orchestration.is_some()
86    }
87
88    /// Stable goal id, if a goal exists.
89    #[must_use]
90    pub fn goal_id(&self) -> Option<&str> {
91        self.orchestration.as_ref().map(|o| o.goal_id.as_str())
92    }
93
94    /// User-facing pause message, if the goal paused with one.
95    #[must_use]
96    pub fn pause_message(&self) -> Option<&str> {
97        self.orchestration.as_ref().and_then(|o| o.pause_message.as_deref())
98    }
99
100    /// Total elapsed wall-clock time in milliseconds, including the live
101    /// portion when the goal is currently active.
102    #[must_use]
103    pub fn elapsed_ms(&self) -> u64 {
104        let base = self.orchestration.as_ref().map_or(0, |o| o.elapsed_ms);
105        if self.orchestration.is_some()
106            && let Some(since) = self.active_since
107        {
108            return base.saturating_add(since.elapsed().as_millis() as u64);
109        }
110        base
111    }
112
113    /// Tokens charged while the goal was active. Zero when no goal exists.
114    #[must_use]
115    pub fn tokens_used(&self) -> i64 {
116        self.orchestration.as_ref().map_or(0, |o| o.tokens_used_high_water)
117    }
118
119    /// Consumed auto-continue turns this episode. Zero without a goal.
120    #[must_use]
121    pub fn auto_continue_turns(&self) -> u8 {
122        self.orchestration.as_ref().map_or(0, |o| o.auto_continue_turns)
123    }
124
125    /// Atomically reserve one auto-continue turn when budget remains,
126    /// returning the 1-based turn number. `None` leaves state untouched.
127    pub fn claim_auto_continue_turn(&mut self, max_turns: u8) -> Option<u8> {
128        let o = self.orchestration.as_mut()?;
129        if o.auto_continue_turns >= max_turns {
130            return None;
131        }
132        o.auto_continue_turns = o.auto_continue_turns.saturating_add(1);
133        Some(o.auto_continue_turns)
134    }
135
136    /// Charge the increase in this runloop's cumulative token total to an active
137    /// goal. Observations while paused only advance the cursor. Observe before
138    /// changing status so usage is attributed to the interval that just ended.
139    pub fn record_token_observation(&mut self, session_total: i64) {
140        if let Some(o) = self.orchestration.as_mut() {
141            let previous = self.last_session_tokens_seen.unwrap_or(session_total.max(0));
142            let current = session_total.max(previous);
143            self.last_session_tokens_seen = Some(current);
144            if o.status == GoalStatus::Active {
145                o.tokens_used_high_water = o.tokens_used_high_water.saturating_add(current - previous);
146            }
147        }
148    }
149
150    /// Replace the token budget in place (`None` clears it). Returns `false`
151    /// when no goal exists.
152    pub fn set_token_budget(&mut self, budget: Option<i64>) -> bool {
153        if let Some(o) = self.orchestration.as_mut() {
154            o.token_budget = budget;
155            return true;
156        }
157        false
158    }
159
160    /// Mark an Active goal budget-limited when usage reached its cap.
161    /// Paused goals keep the user's explicit state. Returns `true` if applied.
162    pub fn enforce_budget(&mut self) -> bool {
163        let over = self.orchestration.as_ref().is_some_and(|o| {
164            o.status == GoalStatus::Active && o.token_budget.is_some_and(|b| o.tokens_used_high_water >= b)
165        });
166        if over { self.budget_limit() } else { false }
167    }
168
169    /// Replace the objective in place, preserving elapsed time and history.
170    /// Returns `false` when no goal exists.
171    pub fn set_objective(&mut self, objective: &str) -> bool {
172        if let Some(o) = self.orchestration.as_mut() {
173            o.objective = objective.trim().to_string();
174            return true;
175        }
176        false
177    }
178
179    /// Persist the snapshot to `<session_dir>/goal/goal.json`, creating the
180    /// directory if needed. With no goal, removes a stale snapshot instead so
181    /// a cleared goal never resurrects on restart.
182    pub fn persist(&self) -> Result<(), SessionStoreError> {
183        let path = goal_snapshot_path(&self.session_dir)?;
184        match &self.orchestration {
185            Some(o) => {
186                let bytes = serde_json::to_vec(o)?;
187                VtCodePaths::write_private_file_atomic(&path, &bytes)
188                    .map_err(|err| SessionStoreError::io(path, io::Error::other(err)))
189            }
190            None => {
191                vtcode_commons::paths::validate_no_escaping_symlink_ancestors(&path, true)
192                    .map_err(|err| SessionStoreError::io(&path, err))?;
193                match fs::remove_file(&path) {
194                    Ok(()) => Ok(()),
195                    Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
196                    Err(err) => Err(SessionStoreError::io(path, err)),
197                }
198            }
199        }
200    }
201
202    /// Restore a tracker from `<session_dir>/goal/goal.json`, or return an
203    /// empty tracker when no snapshot exists. In-flight goals restore paused.
204    pub fn restore(session_dir: PathBuf) -> Result<Self, SessionStoreError> {
205        let path = goal_snapshot_path(&session_dir)?;
206        match fs::symlink_metadata(&path) {
207            Ok(_) => (),
208            Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Self::new(session_dir)),
209            Err(err) => return Err(SessionStoreError::io(path, err)),
210        }
211        let bytes = VtCodePaths::read_file_no_follow(&path)
212            .map_err(|err| SessionStoreError::io(path, io::Error::other(err)))?;
213        let snapshot: GoalOrchestration = serde_json::from_slice(&bytes)?;
214        Ok(Self::from_snapshot(session_dir, snapshot))
215    }
216
217    /// Current snapshot for event and RPC payloads; `None` without a goal.
218    #[must_use]
219    pub fn goal_snapshot(&self) -> Option<vtcode_exec_events::goal::GoalSnapshot> {
220        use vtcode_exec_events::goal::GoalSnapshot;
221        self.orchestration.as_ref().map(|o| GoalSnapshot {
222            goal_id: o.goal_id.clone(),
223            state: vtcode_exec_events::goal::GoalState::from(o.status),
224            objective: o.objective.clone(),
225            elapsed_ms: self.elapsed_ms(),
226            tokens_used: o.tokens_used_high_water,
227            token_budget: o.token_budget,
228            pause_message: o.pause_message.clone(),
229        })
230    }
231
232    /// Build the `goal.updated` payload for the current state; `goal: None`
233    /// when no goal exists.
234    #[must_use]
235    pub fn to_goal_updated_event(&self) -> vtcode_exec_events::ThreadEvent {
236        use vtcode_exec_events::goal::GoalUpdatedEvent;
237        let goal = self.goal_snapshot();
238        vtcode_exec_events::ThreadEvent::GoalUpdated(Box::new(GoalUpdatedEvent { goal }))
239    }
240}
241
242impl From<GoalStatus> for vtcode_exec_events::goal::GoalState {
243    /// Collapse the tracker's fine-grained pause reasons into the coarse wire
244    /// state. Every paused variant maps to `Paused`; terminal states map 1:1.
245    fn from(status: GoalStatus) -> Self {
246        use vtcode_exec_events::goal::GoalState;
247        match status {
248            GoalStatus::Active => GoalState::Active,
249            GoalStatus::UserPaused
250            | GoalStatus::BackOffPaused
251            | GoalStatus::NoProgressPaused
252            | GoalStatus::InfraPaused => GoalState::Paused,
253            GoalStatus::Blocked => GoalState::Blocked,
254            GoalStatus::BudgetLimited => GoalState::BudgetLimited,
255            GoalStatus::Complete => GoalState::Complete,
256        }
257    }
258}