vtcode_memory/progress/
goal_api.rs1use std::path::PathBuf;
11use std::{fs, io};
12use vtcode_commons::VtCodePaths;
13
14use super::{GoalOrchestration, GoalStatus, GoalTracker};
15use crate::error::SessionStoreError;
16
17const GOAL_SNAPSHOT_FILE: &str = "goal.json";
19
20fn goal_snapshot_path(session_dir: &std::path::Path) -> Result<PathBuf, SessionStoreError> {
21 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 #[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 #[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 #[must_use]
72 pub fn active_activation_id(&self) -> Option<uuid::Uuid> {
73 self.activation_id.filter(|_| self.is_active())
74 }
75
76 pub fn commit(&mut self, staged: Self) -> Result<(), SessionStoreError> {
78 staged.persist()?;
79 *self = staged;
80 Ok(())
81 }
82 #[must_use]
84 pub fn has_goal(&self) -> bool {
85 self.orchestration.is_some()
86 }
87
88 #[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 #[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 #[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 #[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 #[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 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 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 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 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 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 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 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 #[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 #[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 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}