Skip to main content

vtcode_memory/progress/
mod.rs

1//! Durable, compaction-safe progress ledger.
2//!
3//! Long-horizon agent capability requires a persistent signal of *goal
4//! progress* that survives compaction, fork, and resume. The live conversation
5//! is never reloaded into context from disk, but the progress ledger is a tiny
6//! derived artifact (like `manifest.json`) that the harness can read on each
7//! turn to decide whether work is actually advancing toward completion.
8//!
9//! The ledger is stored under `<session_dir>/derived/progress.json` and
10//! overwritten on each update — it is a single mutable summary, not an
11//! append-only log, which keeps reads O(1) and cheap.
12
13use chrono::Utc;
14use serde::{Deserialize, Serialize};
15use std::fmt::Write as _;
16use std::path::{Path, PathBuf};
17
18use crate::error::SessionStoreError;
19use crate::session_dir;
20
21/// Lifecycle status of a single milestone toward the session goal.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(rename_all = "snake_case")]
24pub enum MilestoneStatus {
25    /// Not yet started.
26    Pending,
27    /// Actively being worked on this/last turn.
28    InProgress,
29    /// Completed and verified.
30    Done,
31    /// Blocked — cannot proceed without external input or a replan.
32    Blocked,
33}
34
35impl MilestoneStatus {
36    /// Whether this status counts as forward progress toward completion.
37    #[must_use]
38    fn is_terminal(&self) -> bool {
39        matches!(self, MilestoneStatus::Done)
40    }
41}
42
43/// A single tracked milestone derived from the task tracker / plan.
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45pub struct Milestone {
46    /// Stable identifier (e.g. tracker item index or plan item id).
47    pub id: String,
48    /// Human-readable description.
49    pub description: String,
50    /// Current status.
51    pub status: MilestoneStatus,
52}
53
54/// Compact, durable progress signal for one session.
55///
56/// This is the harness's externalized memory of "are we getting closer to
57/// done?" It is intentionally small so it can be loaded every turn without
58/// touching the event log. Includes handoff metadata so cross-session
59/// continuity is explicit in the ledger itself.
60#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
61pub struct ProgressLedger {
62    /// Owning session id.
63    pub session_id: String,
64    /// The objective the agent is pursuing.
65    pub goal: String,
66    /// Tracked milestones; empty when the agent has no explicit tracker.
67    milestones: Vec<Milestone>,
68    /// Agent's confidence in eventual completion, `0.0..=1.0`.
69    pub confidence: f32,
70    /// RFC3339 timestamp of the first turn where no forward progress was
71    /// detected, or `None` if progress is currently being made.
72    stalled_since: Option<String>,
73    /// RFC3339 timestamp of the last ledger update.
74    updated_at: String,
75    /// The session id of the predecessor session that handed off to this one.
76    /// `None` for the first session in a chain.
77    #[serde(default)]
78    previous_session_id: Option<String>,
79    /// Summary communicated by the previous session at handoff time.
80    #[serde(default)]
81    handoff_summary: Option<String>,
82    /// Issues carried forward from the previous session.
83    #[serde(default)]
84    known_issues: Vec<String>,
85    /// Git commit hash at the time of handoff (the "checkpoint").
86    #[serde(default)]
87    git_checkpoint: Option<String>,
88}
89
90impl ProgressLedger {
91    /// Create a fresh ledger for a session with an initial goal.
92    #[must_use]
93    pub fn new(session_id: &str, goal: &str) -> Self {
94        let ts = Utc::now().to_rfc3339();
95        Self {
96            session_id: session_id.to_string(),
97            goal: goal.to_string(),
98            milestones: Vec::new(),
99            confidence: 1.0,
100            stalled_since: None,
101            updated_at: ts,
102            previous_session_id: None,
103            handoff_summary: None,
104            known_issues: Vec::new(),
105            git_checkpoint: None,
106        }
107    }
108
109    /// Fraction of milestones in a terminal (`Done`) state, `0.0..=1.0`.
110    /// Returns `1.0` when there are no milestones (nothing tracked yet).
111    #[must_use]
112    pub fn completion_ratio(&self) -> f32 {
113        if self.milestones.is_empty() {
114            return 1.0;
115        }
116        let done = self.milestones.iter().filter(|m| m.status.is_terminal()).count() as f32;
117        done / self.milestones.len() as f32
118    }
119
120    /// Whether every tracked milestone is complete (or none are tracked).
121    #[must_use]
122    pub fn is_complete(&self) -> bool {
123        self.completion_ratio() >= 1.0
124    }
125
126    /// Whether the ledger currently reports a stall.
127    #[must_use]
128    pub fn is_stalled(&self) -> bool {
129        self.stalled_since.is_some()
130    }
131
132    /// Record forward progress: clears any stall marker and refreshes the
133    /// timestamp. Confidence is nudged upward (bounded at 1.0).
134    pub fn note_advance(&mut self) {
135        self.stalled_since = None;
136        self.confidence = (self.confidence + 0.05).min(1.0);
137        self.updated_at = Utc::now().to_rfc3339();
138    }
139
140    /// Record a stall: sets `stalled_since` on first occurrence and refreshes
141    /// the timestamp. Confidence is nudged downward (bounded at `0.0`).
142    pub fn note_stall(&mut self) {
143        if self.stalled_since.is_none() {
144            self.stalled_since = Some(Utc::now().to_rfc3339());
145        }
146        self.confidence = (self.confidence - 0.1).max(0.0);
147        self.updated_at = Utc::now().to_rfc3339();
148    }
149
150    /// Replace the milestone set and refresh the timestamp.
151    pub fn set_milestones(&mut self, milestones: Vec<Milestone>) {
152        self.milestones = milestones;
153        self.updated_at = Utc::now().to_rfc3339();
154    }
155
156    /// Set the session goal and refresh the timestamp.
157    pub fn set_goal(&mut self, goal: &str) {
158        self.goal = goal.to_string();
159        self.updated_at = Utc::now().to_rfc3339();
160    }
161
162    /// Record handoff metadata from a previous session.
163    fn set_handoff(&mut self, previous_session_id: &str, summary: &str, git_checkpoint: Option<String>) {
164        self.previous_session_id = Some(previous_session_id.to_string());
165        self.handoff_summary = Some(summary.to_string());
166        self.git_checkpoint = git_checkpoint;
167        self.updated_at = Utc::now().to_rfc3339();
168    }
169
170    /// Add a known issue carried forward from a previous session.
171    fn add_known_issue(&mut self, issue: &str) {
172        self.known_issues.push(issue.to_string());
173        self.updated_at = Utc::now().to_rfc3339();
174    }
175
176    /// Render a compact, human-readable progress summary for durable memory
177    /// (e.g. `<workspace>/memories/progress.md`). Survives compaction and gives
178    /// a resumed session an accurate picture of what is done. Includes handoff
179    /// metadata when present so the next session can orient from this alone.
180    #[must_use]
181    pub fn to_markdown(&self) -> String {
182        let mut out = String::new();
183        out.push_str("# Session Progress\n\n");
184        let _ = writeln!(out, "**Goal:** {}", self.goal);
185        let _ = writeln!(out, "**Completion:** {:.0}%", (self.completion_ratio() * 100.0).round());
186        let _ = writeln!(out, "**Confidence:** {:.2}", self.confidence);
187        if let Some(since) = &self.stalled_since {
188            let _ = writeln!(out, "**Stalled since:** {since}");
189        }
190        let _ = writeln!(out, "**Updated:** {}\n", self.updated_at);
191
192        if let Some(prev) = &self.previous_session_id {
193            let _ = writeln!(out, "**Handed off from:** {prev}");
194        }
195        if let Some(summary) = &self.handoff_summary {
196            let _ = writeln!(out, "**Handoff summary:** {summary}");
197        }
198        if let Some(checkpoint) = &self.git_checkpoint {
199            let _ = writeln!(out, "**Git checkpoint:** `{checkpoint}`");
200        }
201        if !self.known_issues.is_empty() {
202            out.push_str("\n## Known Issues\n\n");
203            for issue in &self.known_issues {
204                let _ = writeln!(out, "- {issue}");
205            }
206        }
207
208        if self.milestones.is_empty() {
209            out.push_str("\n_No tracked milestones yet._\n");
210        } else {
211            out.push_str("\n## Milestones\n\n");
212            for m in &self.milestones {
213                let mark = match m.status {
214                    MilestoneStatus::Done => "[x]",
215                    MilestoneStatus::InProgress => "[~]",
216                    MilestoneStatus::Blocked => "[!]",
217                    MilestoneStatus::Pending => "[ ]",
218                };
219                let _ = writeln!(out, "{} {} — {}", mark, m.id, m.description);
220            }
221        }
222        out
223    }
224}
225
226/// Resolve the on-disk path of the progress ledger for a session.
227#[must_use]
228pub fn progress_path(workspace: &Path, session_id: &str) -> PathBuf {
229    session_dir(workspace, session_id)
230        .join(crate::DERIVED_DIR)
231        .join("progress.json")
232}
233
234/// Load the progress ledger for a session, if one has been persisted.
235///
236/// Returns `Ok(None)` when no ledger file exists yet (a fresh or pre-ledger
237/// session) rather than an error, so callers can treat absence as "no signal".
238pub fn load_progress(workspace: &Path, session_id: &str) -> Result<Option<ProgressLedger>, SessionStoreError> {
239    let path = progress_path(workspace, session_id);
240    if !path.exists() {
241        return Ok(None);
242    }
243    let bytes = std::fs::read(&path).map_err(|e| SessionStoreError::io(path.clone(), e))?;
244    let ledger: ProgressLedger = serde_json::from_slice(&bytes)?;
245    Ok(Some(ledger))
246}
247
248/// Persist the progress ledger for a session, creating `derived/` if needed.
249pub fn save_progress(workspace: &Path, session_id: &str, ledger: &ProgressLedger) -> Result<(), SessionStoreError> {
250    let path = progress_path(workspace, session_id);
251    if let Some(parent) = path.parent() {
252        std::fs::create_dir_all(parent)
253            .map_err(|e| SessionStoreError::CreateDir { path: parent.to_path_buf(), source: e })?;
254    }
255    let bytes = serde_json::to_vec(ledger)?;
256    std::fs::write(&path, bytes).map_err(|e| SessionStoreError::io(path, e))?;
257    Ok(())
258}
259
260// ============================================================================
261// Goal tracker state machine
262// ============================================================================
263
264use std::time::Instant;
265
266/// Phase of goal execution.
267#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
268#[serde(rename_all = "snake_case")]
269pub enum GoalPhase {
270    /// Goal is idle; no active planning or execution.
271    Idle,
272    /// Planning phase is in progress.
273    Planning,
274    /// Execution phase is in progress.
275    Executing,
276}
277
278/// Lifecycle status of a goal.
279///
280/// The paused variants encode the reason the goal was paused:
281/// - `UserPaused` for explicit pause requests
282/// - `BackOffPaused` when the classifier run cap is hit
283/// - `NoProgressPaused` when the verifier flags the same gaps with no progress
284/// - `InfraPaused` when a turn finishes with an infrastructure error
285/// - `Blocked` when the model determined the goal is not achievable
286///
287/// **Backwards-compat serde aliases:** older shells serialized this
288/// enum with the default PascalCase form (`"Active"`, `"Paused"`,
289/// `"BudgetLimited"`, `"Complete"`). The `#[serde(alias = ...)]`
290/// attributes preserve in-flight goal snapshots written by older shells.
291#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
292#[serde(rename_all = "snake_case")]
293pub enum GoalStatus {
294    /// Goal is actively running.
295    #[serde(alias = "Active")]
296    Active,
297    /// Explicitly paused by the user.
298    #[serde(alias = "Paused")]
299    UserPaused,
300    /// Paused due to repeated classifier failures (back-off cap hit).
301    BackOffPaused,
302    /// Paused because the verifier reported the same gaps with no progress.
303    NoProgressPaused,
304    /// Paused due to an infrastructure error in a turn.
305    InfraPaused,
306    /// Blocked; the model determined the goal is not achievable.
307    Blocked,
308    /// Hit the token budget limit.
309    #[serde(alias = "BudgetLimited")]
310    BudgetLimited,
311    /// Goal completed successfully.
312    #[serde(alias = "Complete")]
313    Complete,
314}
315
316impl<'de> Deserialize<'de> for GoalStatus {
317    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
318    where
319        D: serde::Deserializer<'de>,
320    {
321        let s = String::deserialize(deserializer)?;
322        Ok(Self::from_wire_str(&s))
323    }
324}
325
326impl GoalStatus {
327    /// Parse a persisted/wire status string. Unknown values map to
328    /// `UserPaused`: a status this shell cannot interpret must restore as
329    /// a resumable paused goal, never an Active self-driving one.
330    fn from_wire_str(s: &str) -> Self {
331        match s {
332            "active" | "Active" => Self::Active,
333            "user_paused" | "paused" | "Paused" => Self::UserPaused,
334            "doom_loop_paused" => Self::UserPaused,
335            "back_off_paused" => Self::BackOffPaused,
336            "no_progress_paused" => Self::NoProgressPaused,
337            "infra_paused" => Self::InfraPaused,
338            "blocked" => Self::Blocked,
339            "budget_limited" | "BudgetLimited" => Self::BudgetLimited,
340            "complete" | "Complete" => Self::Complete,
341            _ => Self::UserPaused,
342        }
343    }
344
345    /// `true` for any paused variant.
346    pub fn is_paused(&self) -> bool {
347        matches!(
348            self,
349            Self::UserPaused | Self::BackOffPaused | Self::NoProgressPaused | Self::InfraPaused | Self::Blocked
350        )
351    }
352}
353
354/// Reason for pausing a goal. Maps 1:1 to one of the paused variants on
355/// [`GoalStatus`].
356#[derive(Debug, Clone, Copy, PartialEq, Eq)]
357pub enum GoalPauseReason {
358    /// Paused by explicit user request.
359    User,
360    /// Paused after repeated classifier failures hit the back-off cap.
361    BackOff,
362    /// Paused because the verifier reported no progress on known gaps.
363    NoProgress,
364    /// Paused because the verifier determined the goal is not achievable.
365    Verification,
366    /// Paused due to an infrastructure error.
367    Infra,
368    /// Paused because the model reported an external blocker it cannot resolve.
369    ModelBlocked,
370    /// Paused because the driving session ended. Resume clears it.
371    SessionEnd,
372}
373
374impl GoalPauseReason {
375    fn to_status(self) -> GoalStatus {
376        match self {
377            Self::User => GoalStatus::UserPaused,
378            Self::BackOff => GoalStatus::BackOffPaused,
379            Self::NoProgress => GoalStatus::NoProgressPaused,
380            Self::Verification => GoalStatus::Blocked,
381            Self::Infra => GoalStatus::InfraPaused,
382            Self::ModelBlocked => GoalStatus::Blocked,
383            Self::SessionEnd => GoalStatus::UserPaused,
384        }
385    }
386
387    fn history_detail(self) -> &'static str {
388        match self {
389            Self::User => "user",
390            Self::BackOff => "back_off",
391            Self::NoProgress => "no_progress",
392            Self::Verification => "blocked",
393            Self::Infra => "infra",
394            Self::ModelBlocked => "model_blocked",
395            Self::SessionEnd => "session_end",
396        }
397    }
398}
399
400/// Aggregate verdict produced by the goal-verification stage.
401#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
402#[serde(rename_all = "snake_case")]
403pub enum GoalClassifierVerdict {
404    /// Goal was achieved.
405    Achieved,
406    /// Goal was not achieved.
407    NotAchieved,
408}
409
410/// Lifecycle event recorded in the goal history.
411#[derive(Debug, Clone, Serialize, Deserialize)]
412#[serde(rename_all = "snake_case")]
413pub enum GoalEvent {
414    /// Goal was created.
415    GoalCreated,
416    /// Planning phase started.
417    PlanningStarted,
418    /// Planning phase completed.
419    PlanningCompleted,
420    /// Planning phase failed.
421    PlanningFailed,
422    /// Worker started processing.
423    WorkerStarted,
424    /// Worker completed successfully.
425    WorkerCompleted,
426    /// Worker failed.
427    WorkerFailed,
428    /// Context was rotated.
429    ContextRotated,
430    /// Goal was paused.
431    GoalPaused,
432    /// Goal was resumed.
433    GoalResumed,
434    /// Goal completed successfully.
435    GoalCompleted,
436    /// Goal was cleared.
437    GoalCleared,
438    /// Budget was exceeded.
439    BudgetExceeded,
440    /// Premature stop was detected.
441    PrematureStopDetected,
442    /// Unknown or unrecognized event.
443    #[serde(other)]
444    Unknown,
445}
446
447/// A single history entry for a goal lifecycle event.
448#[derive(Debug, Clone, Serialize, Deserialize)]
449pub struct GoalHistoryEntry {
450    /// ISO-8601 timestamp of the event.
451    timestamp: String,
452    /// Lifecycle event type.
453    event: GoalEvent,
454    /// Optional human-readable detail string.
455    #[serde(default, skip_serializing_if = "Option::is_none")]
456    detail: Option<String>,
457    /// Optional round number associated with the event.
458    #[serde(default, skip_serializing_if = "Option::is_none")]
459    round: Option<u32>,
460    /// Optional token count at the time of the event.
461    #[serde(default, skip_serializing_if = "Option::is_none")]
462    tokens_used: Option<i64>,
463    /// Unmet requirements or blockers recorded at this event.
464    #[serde(default, skip_serializing_if = "Vec::is_empty")]
465    unmet: Vec<String>,
466}
467
468impl GoalHistoryEntry {
469    fn now(event: GoalEvent, detail: Option<String>) -> Self {
470        Self {
471            timestamp: Utc::now().to_rfc3339(),
472            event,
473            detail,
474            round: None,
475            tokens_used: None,
476            unmet: Vec::new(),
477        }
478    }
479}
480
481/// Full persisted state for a goal orchestration.
482#[derive(Debug, Clone, Serialize, Deserialize)]
483pub struct GoalOrchestration {
484    /// Unique identifier for the goal.
485    goal_id: String,
486    /// Human-readable objective description.
487    objective: String,
488    /// Current lifecycle status.
489    status: GoalStatus,
490    /// Current execution phase.
491    phase: GoalPhase,
492    /// Optional token budget cap.
493    token_budget: Option<i64>,
494    /// Elapsed wall-clock time in milliseconds.
495    elapsed_ms: u64,
496    /// ISO-8601 creation timestamp.
497    created_at: String,
498    /// Currently executing subagent ID, if any.
499    current_subagent_id: Option<String>,
500    /// Role of the current subagent.
501    current_subagent_role: Option<String>,
502    /// Total worker rounds executed.
503    #[serde(default)]
504    total_worker_rounds: u32,
505    /// Total verification rounds executed.
506    #[serde(default)]
507    total_verify_rounds: u32,
508    /// Whether the budget limit notification has already been emitted.
509    #[serde(skip)]
510    budget_limit_reported: bool,
511    /// Baseline token count when the goal started.
512    #[serde(default)]
513    token_baseline: i64,
514    /// High-water mark for tokens used.
515    #[serde(default)]
516    tokens_used_high_water: i64,
517    /// Tokens spent by the parent session before this goal started.
518    #[serde(default)]
519    parent_tokens_spent: i64,
520    /// Last observed session token count.
521    #[serde(default)]
522    last_session_tokens_seen: Option<i64>,
523    /// Ordered history of lifecycle events.
524    history: Vec<GoalHistoryEntry>,
525    /// User-facing pause message, if any.
526    #[serde(default, skip_serializing_if = "Option::is_none")]
527    pause_message: Option<String>,
528    /// Number of consecutive classifier stall detections.
529    #[serde(default)]
530    classifier_stall_count: u32,
531    /// Total classifier run attempts.
532    #[serde(default)]
533    classifier_runs_attempted: u32,
534    /// Rounds since the last verification pass.
535    #[serde(default)]
536    rounds_since_verify: u32,
537    /// Consecutive not-achieved verdicts.
538    #[serde(default)]
539    consecutive_not_achieved: u32,
540    /// Consumed goal-loop auto-continue turns this episode. Reset by
541    /// [`GoalTracker::create_goal`](GoalTracker::create_goal) and
542    /// [`GoalTracker::resume`](GoalTracker::resume) so every fresh or resumed
543    /// goal gets a full budget on every frontend.
544    #[serde(default)]
545    auto_continue_turns: u8,
546    /// Turn at which the strategist last fired.
547    #[serde(default)]
548    last_strategist_fired_at: u32,
549    /// Bonus tokens granted by the strategist.
550    #[serde(default)]
551    strategist_cap_bonus: u32,
552    /// Path of the last strategy recommendation, if any.
553    #[serde(default, skip_serializing_if = "Option::is_none")]
554    last_strategy_path: Option<String>,
555    /// Last strategy recommendation text, if any.
556    #[serde(default, skip_serializing_if = "Option::is_none")]
557    last_strategy_recommendation: Option<String>,
558    /// Commit hash at the last strategy change baseline, if any.
559    #[serde(default, skip_serializing_if = "Option::is_none")]
560    changes_baseline_commit: Option<String>,
561    /// Fingerprint of the last gap signature, if any.
562    #[serde(default, skip_serializing_if = "Option::is_none")]
563    last_gap_fingerprint: Option<String>,
564    /// Live token count for active subagents.
565    #[serde(skip)]
566    live_subagent_tokens: u64,
567    /// Live token usage broken down by model.
568    #[serde(skip)]
569    live_tokens_by_model: Vec<(String, u64)>,
570    /// Live context window size in tokens.
571    #[serde(skip)]
572    live_context_window: u64,
573    /// Live context window utilization percentage (0-100).
574    #[serde(skip)]
575    live_context_pct: u8,
576    /// Live turn count for the current goal.
577    #[serde(skip)]
578    live_turn_count: u32,
579    /// Live tool call count for the current goal.
580    #[serde(skip)]
581    live_tool_call_count: u32,
582    /// Whether a planning pass is currently in flight.
583    #[serde(skip)]
584    planning_in_flight: bool,
585    /// Whether a verification pass is currently in flight.
586    #[serde(skip)]
587    verifying_in_flight: bool,
588}
589
590impl GoalOrchestration {
591    fn reset_strategist_fields(&mut self) {
592        self.consecutive_not_achieved = 0;
593        self.last_strategist_fired_at = 0;
594        self.strategist_cap_bonus = 0;
595        self.last_strategy_path = None;
596        self.last_strategy_recommendation = None;
597    }
598
599    fn reset_classifier_stall_fields(&mut self) {
600        self.classifier_stall_count = 0;
601        self.last_gap_fingerprint = None;
602    }
603}
604
605/// Pure state machine for goal tracking.
606#[derive(Debug)]
607pub struct GoalTracker {
608    /// Current goal orchestration state, if a goal is active.
609    orchestration: Option<GoalOrchestration>,
610    /// Directory where progress snapshots are persisted.
611    session_dir: PathBuf,
612    /// Instant when the goal became active.
613    active_since: Option<Instant>,
614}
615
616impl GoalTracker {
617    /// Create a new tracker with no active goal.
618    pub fn new(session_dir: PathBuf) -> Self {
619        Self {
620            orchestration: None,
621            session_dir,
622            active_since: None,
623        }
624    }
625
626    /// Restore tracker state from a persisted snapshot.
627    pub fn from_snapshot(session_dir: PathBuf, mut snapshot: GoalOrchestration) -> Self {
628        match snapshot.phase {
629            GoalPhase::Planning | GoalPhase::Executing => {
630                snapshot.phase = GoalPhase::Idle;
631                if snapshot.status == GoalStatus::Active {
632                    snapshot.status = GoalStatus::UserPaused;
633                }
634                snapshot.current_subagent_id = None;
635                snapshot.current_subagent_role = None;
636            }
637            GoalPhase::Idle => {}
638        }
639        snapshot.planning_in_flight = false;
640        snapshot.verifying_in_flight = false;
641        let active_since = if snapshot.status == GoalStatus::Active {
642            Some(Instant::now())
643        } else {
644            None
645        };
646        Self {
647            orchestration: Some(snapshot),
648            session_dir,
649            active_since,
650        }
651    }
652
653    /// Return an immutable reference to the current orchestration snapshot.
654    fn snapshot(&self) -> Option<&GoalOrchestration> {
655        self.orchestration.as_ref()
656    }
657
658    /// Return a mutable reference to the current orchestration snapshot.
659    pub fn snapshot_mut(&mut self) -> Option<&mut GoalOrchestration> {
660        self.orchestration.as_mut()
661    }
662
663    /// `true` if a goal is currently active.
664    pub fn is_active(&self) -> bool {
665        self.orchestration.as_ref().is_some_and(|o| o.status == GoalStatus::Active)
666    }
667
668    /// Current execution phase, if a goal is active.
669    pub fn phase(&self) -> Option<GoalPhase> {
670        self.orchestration.as_ref().map(|o| o.phase)
671    }
672
673    /// Current lifecycle status, if a goal is active.
674    pub fn status(&self) -> Option<GoalStatus> {
675        self.orchestration.as_ref().map(|o| o.status)
676    }
677
678    /// ID of the currently executing subagent, if any.
679    fn current_subagent_id(&self) -> Option<&str> {
680        self.orchestration.as_ref().and_then(|o| o.current_subagent_id.as_deref())
681    }
682
683    /// Human-readable objective, if a goal is active.
684    pub fn objective(&self) -> Option<&str> {
685        self.orchestration.as_ref().map(|o| o.objective.as_str())
686    }
687
688    /// Token budget cap, if set.
689    pub fn token_budget(&self) -> Option<i64> {
690        self.orchestration.as_ref().and_then(|o| o.token_budget)
691    }
692
693    /// Create a new goal. Replaces any existing orchestration.
694    pub fn create_goal(
695        &mut self,
696        goal_id: String,
697        objective: String,
698        token_budget: Option<i64>,
699        token_baseline: i64,
700        created_at: String,
701        baseline_commit: Option<String>,
702    ) {
703        let _ = std::fs::create_dir_all(self.goal_dir());
704        if self.orchestration.is_some() {
705            self.remove_scratch_root();
706        }
707        self.orchestration = Some(GoalOrchestration {
708            goal_id,
709            objective,
710            status: GoalStatus::Active,
711            phase: GoalPhase::Executing,
712            token_budget,
713            elapsed_ms: 0,
714            created_at,
715            current_subagent_id: None,
716            current_subagent_role: None,
717            total_worker_rounds: 0,
718            total_verify_rounds: 0,
719            budget_limit_reported: false,
720            token_baseline,
721            tokens_used_high_water: 0,
722            parent_tokens_spent: 0,
723            last_session_tokens_seen: Some(token_baseline),
724            history: Vec::new(),
725            pause_message: None,
726            classifier_stall_count: 0,
727            classifier_runs_attempted: 0,
728            rounds_since_verify: 0,
729            consecutive_not_achieved: 0,
730            auto_continue_turns: 0,
731            last_strategist_fired_at: 0,
732            strategist_cap_bonus: 0,
733            last_strategy_path: None,
734            last_strategy_recommendation: None,
735            changes_baseline_commit: baseline_commit,
736            last_gap_fingerprint: None,
737            live_subagent_tokens: 0,
738            live_tokens_by_model: Vec::new(),
739            live_context_window: 0,
740            live_context_pct: 0,
741            live_turn_count: 0,
742            live_tool_call_count: 0,
743            planning_in_flight: false,
744            verifying_in_flight: false,
745        });
746        self.active_since = Some(Instant::now());
747        self.record_event(GoalEvent::GoalCreated, None);
748    }
749
750    /// Update the execution phase of the active goal.
751    fn set_phase(&mut self, phase: GoalPhase) {
752        if let Some(o) = &mut self.orchestration {
753            o.phase = phase;
754        }
755    }
756
757    /// Update the current subagent ID and role.
758    fn set_current_subagent(&mut self, id: Option<String>, role: Option<String>) {
759        if let Some(o) = &mut self.orchestration {
760            o.current_subagent_id = id;
761            o.current_subagent_role = role;
762        }
763    }
764
765    /// Pause the goal with a specific reason. Only transitions from `Active`.
766    pub fn pause(&mut self, reason: GoalPauseReason) -> bool {
767        self.pause_inner(reason, None)
768    }
769
770    /// Like [`Self::pause`] but also stores a human-readable `message`.
771    pub fn pause_with_message(&mut self, reason: GoalPauseReason, message: String) -> bool {
772        self.pause_inner(reason, Some(message))
773    }
774
775    fn pause_inner(&mut self, reason: GoalPauseReason, message: Option<String>) -> bool {
776        let applied = if let Some(o) = &mut self.orchestration
777            && o.status == GoalStatus::Active
778        {
779            if let Some(since) = self.active_since.take() {
780                o.elapsed_ms = o.elapsed_ms.saturating_add(since.elapsed().as_millis() as u64);
781            }
782            o.status = reason.to_status();
783            if message.is_some() {
784                o.pause_message = message;
785            }
786            true
787        } else {
788            false
789        };
790        if applied {
791            self.record_event(GoalEvent::GoalPaused, Some(reason.history_detail().to_owned()));
792        }
793        applied
794    }
795
796    /// Resume a paused goal (any paused variant). Returns `true` if applied.
797    pub fn resume(&mut self) -> bool {
798        if let Some(o) = &mut self.orchestration
799            && o.status.is_paused()
800        {
801            o.status = GoalStatus::Active;
802            o.pause_message = None;
803            o.classifier_runs_attempted = 0;
804            o.rounds_since_verify = 0;
805            o.auto_continue_turns = 0;
806            o.reset_strategist_fields();
807            o.reset_classifier_stall_fields();
808            self.active_since = Some(Instant::now());
809            self.record_event(GoalEvent::GoalResumed, None);
810            return true;
811        }
812        false
813    }
814
815    /// Mark the goal as complete. Accepts `Active` or any paused variant.
816    pub fn complete(&mut self) -> bool {
817        if let Some(o) = &mut self.orchestration
818            && (o.status == GoalStatus::Active || o.status.is_paused())
819        {
820            if let Some(since) = self.active_since.take() {
821                o.elapsed_ms = o.elapsed_ms.saturating_add(since.elapsed().as_millis() as u64);
822            }
823            o.status = GoalStatus::Complete;
824            o.phase = GoalPhase::Idle;
825            o.current_subagent_id = None;
826            o.current_subagent_role = None;
827            o.pause_message = None;
828            o.reset_strategist_fields();
829            self.record_event(GoalEvent::GoalCompleted, None);
830            return true;
831        }
832        false
833    }
834
835    /// Mark the goal as budget-limited. Accepts `Active` or any paused variant.
836    pub fn budget_limit(&mut self) -> bool {
837        if let Some(o) = &mut self.orchestration
838            && (o.status == GoalStatus::Active || o.status.is_paused())
839        {
840            if let Some(since) = self.active_since.take() {
841                o.elapsed_ms = o.elapsed_ms.saturating_add(since.elapsed().as_millis() as u64);
842            }
843            o.status = GoalStatus::BudgetLimited;
844            o.phase = GoalPhase::Idle;
845            o.current_subagent_id = None;
846            o.current_subagent_role = None;
847            o.pause_message = None;
848            o.reset_strategist_fields();
849            self.record_event(GoalEvent::BudgetExceeded, None);
850            return true;
851        }
852        false
853    }
854
855    /// Clear the goal entirely.
856    pub fn clear(&mut self) {
857        self.orchestration = None;
858        self.active_since = None;
859    }
860
861    fn goal_dir(&self) -> PathBuf {
862        self.session_dir.join("goal")
863    }
864
865    fn remove_scratch_root(&self) {
866        let _ = std::fs::remove_dir_all(self.session_dir.join("goal"));
867    }
868
869    /// Flush elapsed wall-clock time into `elapsed_ms`.
870    pub fn account_elapsed(&mut self) {
871        if let Some(o) = &mut self.orchestration
872            && let Some(since) = self.active_since
873        {
874            o.elapsed_ms = o.elapsed_ms.saturating_add(since.elapsed().as_millis() as u64);
875            self.active_since = Some(Instant::now());
876        }
877    }
878
879    /// Record a `NotAchieved` rejection's gap `fingerprint` and report
880    /// whether the goal has stalled.
881    fn record_classifier_stall(&mut self, fingerprint: &str) -> bool {
882        let Some(o) = self.orchestration.as_mut() else {
883            return false;
884        };
885        if o.last_gap_fingerprint.as_deref() == Some(fingerprint) {
886            o.classifier_stall_count = o.classifier_stall_count.saturating_add(1);
887        } else {
888            o.last_gap_fingerprint = Some(fingerprint.to_string());
889            o.classifier_stall_count = 1;
890        }
891        o.classifier_stall_count >= 2
892    }
893
894    /// Undo the most recent attempt-slot reservation.
895    pub fn rollback_classifier_attempt(&mut self) {
896        if let Some(o) = self.orchestration.as_mut() {
897            o.classifier_runs_attempted = o.classifier_runs_attempted.saturating_sub(1);
898        }
899    }
900
901    /// Clear the stall streak.
902    fn reset_classifier_stall(&mut self) {
903        if let Some(o) = self.orchestration.as_mut() {
904            o.reset_classifier_stall_fields();
905        }
906    }
907
908    /// Increment the consecutive-`NotAchieved` streak and return the new value.
909    fn record_not_achieved_streak(&mut self) -> u32 {
910        match self.orchestration.as_mut() {
911            Some(o) => {
912                o.consecutive_not_achieved = o.consecutive_not_achieved.saturating_add(1);
913                o.consecutive_not_achieved
914            }
915            None => 0,
916        }
917    }
918
919    /// Atomically evaluate the strategist trigger and claim a fire.
920    pub fn claim_strategist_fire(&mut self, should_fire: impl Fn(u32, u32) -> bool) -> Option<u32> {
921        let o = self.orchestration.as_mut()?;
922        if should_fire(o.consecutive_not_achieved, o.last_strategist_fired_at) {
923            o.last_strategist_fired_at = o.consecutive_not_achieved;
924            o.strategist_cap_bonus = 3;
925            o.reset_classifier_stall_fields();
926            Some(o.consecutive_not_achieved)
927        } else {
928            None
929        }
930    }
931
932    /// Revoke the cap bonus granted by [`Self::claim_strategist_fire`].
933    pub fn revoke_strategist_cap_bonus(&mut self) {
934        if let Some(o) = self.orchestration.as_mut() {
935            o.strategist_cap_bonus = 0;
936        }
937    }
938
939    /// Reset ALL strategist state.
940    fn reset_strategist_state(&mut self) {
941        if let Some(o) = self.orchestration.as_mut() {
942            o.reset_strategist_fields();
943        }
944    }
945
946    /// Persist the strategist's latest output path + short recommendation.
947    fn record_strategy_recommendation(&mut self, path: String, recommendation: String) {
948        if let Some(o) = self.orchestration.as_mut() {
949            o.last_strategy_path = Some(path);
950            o.last_strategy_recommendation = Some(recommendation);
951        }
952    }
953
954    /// Append a history entry to the active goal, if any.
955    fn append_history(&mut self, entry: GoalHistoryEntry) {
956        if let Some(o) = &mut self.orchestration {
957            o.history.push(entry);
958        }
959    }
960
961    fn record_event(&mut self, event: GoalEvent, detail: Option<String>) {
962        self.append_history(GoalHistoryEntry::now(event, detail));
963    }
964}
965
966mod goal_api;
967#[cfg(test)]
968mod goal_tracker_tests;
969#[cfg(test)]
970mod progress_tests;