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
226mod persistence;
227pub use persistence::{load_progress, progress_path, save_progress};
228
229// ============================================================================
230// Goal tracker state machine
231// ============================================================================
232
233use std::time::Instant;
234
235/// Phase of goal execution.
236#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
237#[serde(rename_all = "snake_case")]
238pub enum GoalPhase {
239    /// Goal is idle; no active planning or execution.
240    Idle,
241    /// Planning phase is in progress.
242    Planning,
243    /// Execution phase is in progress.
244    Executing,
245}
246
247/// Lifecycle status of a goal.
248///
249/// The paused variants encode the reason the goal was paused:
250/// - `UserPaused` for explicit pause requests
251/// - `BackOffPaused` when the classifier run cap is hit
252/// - `NoProgressPaused` when the verifier flags the same gaps with no progress
253/// - `InfraPaused` when a turn finishes with an infrastructure error
254/// - `Blocked` when the model determined the goal is not achievable
255///
256/// **Backwards-compat serde aliases:** older shells serialized this
257/// enum with the default PascalCase form (`"Active"`, `"Paused"`,
258/// `"BudgetLimited"`, `"Complete"`). The `#[serde(alias = ...)]`
259/// attributes preserve in-flight goal snapshots written by older shells.
260#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
261#[serde(rename_all = "snake_case")]
262pub enum GoalStatus {
263    /// Goal is actively running.
264    #[serde(alias = "Active")]
265    Active,
266    /// Explicitly paused by the user.
267    #[serde(alias = "Paused")]
268    UserPaused,
269    /// Paused due to repeated classifier failures (back-off cap hit).
270    BackOffPaused,
271    /// Paused because the verifier reported the same gaps with no progress.
272    NoProgressPaused,
273    /// Paused due to an infrastructure error in a turn.
274    InfraPaused,
275    /// Blocked; the model determined the goal is not achievable.
276    Blocked,
277    /// Hit the token budget limit.
278    #[serde(alias = "BudgetLimited")]
279    BudgetLimited,
280    /// Goal completed successfully.
281    #[serde(alias = "Complete")]
282    Complete,
283}
284
285impl<'de> Deserialize<'de> for GoalStatus {
286    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
287    where
288        D: serde::Deserializer<'de>,
289    {
290        let s = String::deserialize(deserializer)?;
291        Ok(Self::from_wire_str(&s))
292    }
293}
294
295impl GoalStatus {
296    /// Parse a persisted/wire status string. Unknown values map to
297    /// `UserPaused`: a status this shell cannot interpret must restore as
298    /// a resumable paused goal, never an Active self-driving one.
299    fn from_wire_str(s: &str) -> Self {
300        match s {
301            "active" | "Active" => Self::Active,
302            "user_paused" | "paused" | "Paused" => Self::UserPaused,
303            "doom_loop_paused" => Self::UserPaused,
304            "back_off_paused" => Self::BackOffPaused,
305            "no_progress_paused" => Self::NoProgressPaused,
306            "infra_paused" => Self::InfraPaused,
307            "blocked" => Self::Blocked,
308            "budget_limited" | "BudgetLimited" => Self::BudgetLimited,
309            "complete" | "Complete" => Self::Complete,
310            _ => Self::UserPaused,
311        }
312    }
313
314    /// `true` for any paused variant.
315    pub fn is_paused(&self) -> bool {
316        matches!(
317            self,
318            Self::UserPaused | Self::BackOffPaused | Self::NoProgressPaused | Self::InfraPaused | Self::Blocked
319        )
320    }
321}
322
323/// Reason for pausing a goal. Maps 1:1 to one of the paused variants on
324/// [`GoalStatus`].
325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
326pub enum GoalPauseReason {
327    /// Paused by explicit user request.
328    User,
329    /// Paused after repeated classifier failures hit the back-off cap.
330    BackOff,
331    /// Paused because the verifier reported no progress on known gaps.
332    NoProgress,
333    /// Paused because the verifier determined the goal is not achievable.
334    Verification,
335    /// Paused due to an infrastructure error.
336    Infra,
337    /// Paused because the model reported an external blocker it cannot resolve.
338    ModelBlocked,
339    /// Paused because the driving session ended. Resume clears it.
340    SessionEnd,
341}
342
343impl GoalPauseReason {
344    fn to_status(self) -> GoalStatus {
345        match self {
346            Self::User => GoalStatus::UserPaused,
347            Self::BackOff => GoalStatus::BackOffPaused,
348            Self::NoProgress => GoalStatus::NoProgressPaused,
349            Self::Verification => GoalStatus::Blocked,
350            Self::Infra => GoalStatus::InfraPaused,
351            Self::ModelBlocked => GoalStatus::Blocked,
352            Self::SessionEnd => GoalStatus::UserPaused,
353        }
354    }
355
356    fn history_detail(self) -> &'static str {
357        match self {
358            Self::User => "user",
359            Self::BackOff => "back_off",
360            Self::NoProgress => "no_progress",
361            Self::Verification => "blocked",
362            Self::Infra => "infra",
363            Self::ModelBlocked => "model_blocked",
364            Self::SessionEnd => "session_end",
365        }
366    }
367}
368
369/// Aggregate verdict produced by the goal-verification stage.
370#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
371#[serde(rename_all = "snake_case")]
372pub enum GoalClassifierVerdict {
373    /// Goal was achieved.
374    Achieved,
375    /// Goal was not achieved.
376    NotAchieved,
377}
378
379/// Lifecycle event recorded in the goal history.
380#[derive(Debug, Clone, Serialize, Deserialize)]
381#[serde(rename_all = "snake_case")]
382pub enum GoalEvent {
383    /// Goal was created.
384    GoalCreated,
385    /// Planning phase started.
386    PlanningStarted,
387    /// Planning phase completed.
388    PlanningCompleted,
389    /// Planning phase failed.
390    PlanningFailed,
391    /// Worker started processing.
392    WorkerStarted,
393    /// Worker completed successfully.
394    WorkerCompleted,
395    /// Worker failed.
396    WorkerFailed,
397    /// Context was rotated.
398    ContextRotated,
399    /// Goal was paused.
400    GoalPaused,
401    /// Goal was resumed.
402    GoalResumed,
403    /// Goal completed successfully.
404    GoalCompleted,
405    /// Goal was cleared.
406    GoalCleared,
407    /// Budget was exceeded.
408    BudgetExceeded,
409    /// Premature stop was detected.
410    PrematureStopDetected,
411    /// Unknown or unrecognized event.
412    #[serde(other)]
413    Unknown,
414}
415
416/// A single history entry for a goal lifecycle event.
417#[derive(Debug, Clone, Serialize, Deserialize)]
418pub struct GoalHistoryEntry {
419    /// ISO-8601 timestamp of the event.
420    timestamp: String,
421    /// Lifecycle event type.
422    event: GoalEvent,
423    /// Optional human-readable detail string.
424    #[serde(default, skip_serializing_if = "Option::is_none")]
425    detail: Option<String>,
426    /// Optional round number associated with the event.
427    #[serde(default, skip_serializing_if = "Option::is_none")]
428    round: Option<u32>,
429    /// Optional token count at the time of the event.
430    #[serde(default, skip_serializing_if = "Option::is_none")]
431    tokens_used: Option<i64>,
432    /// Unmet requirements or blockers recorded at this event.
433    #[serde(default, skip_serializing_if = "Vec::is_empty")]
434    unmet: Vec<String>,
435}
436
437impl GoalHistoryEntry {
438    fn now(event: GoalEvent, detail: Option<String>) -> Self {
439        Self {
440            timestamp: Utc::now().to_rfc3339(),
441            event,
442            detail,
443            round: None,
444            tokens_used: None,
445            unmet: Vec::new(),
446        }
447    }
448}
449
450/// Full persisted state for a goal orchestration.
451#[derive(Debug, Clone, Serialize, Deserialize)]
452pub struct GoalOrchestration {
453    /// Unique identifier for the goal.
454    goal_id: String,
455    /// Human-readable objective description.
456    objective: String,
457    /// Current lifecycle status.
458    status: GoalStatus,
459    /// Current execution phase.
460    phase: GoalPhase,
461    /// Optional token budget cap.
462    token_budget: Option<i64>,
463    /// Elapsed wall-clock time in milliseconds.
464    elapsed_ms: u64,
465    /// ISO-8601 creation timestamp.
466    created_at: String,
467    /// Currently executing subagent ID, if any.
468    current_subagent_id: Option<String>,
469    /// Role of the current subagent.
470    current_subagent_role: Option<String>,
471    /// Total worker rounds executed.
472    #[serde(default)]
473    total_worker_rounds: u32,
474    /// Total verification rounds executed.
475    #[serde(default)]
476    total_verify_rounds: u32,
477    /// Whether the budget limit notification has already been emitted.
478    #[serde(skip)]
479    budget_limit_reported: bool,
480    /// Baseline token count when the goal started.
481    #[serde(default)]
482    token_baseline: i64,
483    /// High-water mark for tokens used.
484    #[serde(default)]
485    tokens_used_high_water: i64,
486    /// Tokens spent by the parent session before this goal started.
487    #[serde(default)]
488    parent_tokens_spent: i64,
489    /// Last observed session token count.
490    #[serde(default)]
491    last_session_tokens_seen: Option<i64>,
492    /// Ordered history of lifecycle events.
493    history: Vec<GoalHistoryEntry>,
494    /// User-facing pause message, if any.
495    #[serde(default, skip_serializing_if = "Option::is_none")]
496    pause_message: Option<String>,
497    /// Number of consecutive classifier stall detections.
498    #[serde(default)]
499    classifier_stall_count: u32,
500    /// Total classifier run attempts.
501    #[serde(default)]
502    classifier_runs_attempted: u32,
503    /// Rounds since the last verification pass.
504    #[serde(default)]
505    rounds_since_verify: u32,
506    /// Consecutive not-achieved verdicts.
507    #[serde(default)]
508    consecutive_not_achieved: u32,
509    /// Consumed goal-loop auto-continue turns this episode. Reset by
510    /// [`GoalTracker::create_goal`](GoalTracker::create_goal) and
511    /// [`GoalTracker::resume`](GoalTracker::resume) so every fresh or resumed
512    /// goal gets a full budget on every frontend.
513    #[serde(default)]
514    auto_continue_turns: u8,
515    /// Turn at which the strategist last fired.
516    #[serde(default)]
517    last_strategist_fired_at: u32,
518    /// Bonus tokens granted by the strategist.
519    #[serde(default)]
520    strategist_cap_bonus: u32,
521    /// Path of the last strategy recommendation, if any.
522    #[serde(default, skip_serializing_if = "Option::is_none")]
523    last_strategy_path: Option<String>,
524    /// Last strategy recommendation text, if any.
525    #[serde(default, skip_serializing_if = "Option::is_none")]
526    last_strategy_recommendation: Option<String>,
527    /// Commit hash at the last strategy change baseline, if any.
528    #[serde(default, skip_serializing_if = "Option::is_none")]
529    changes_baseline_commit: Option<String>,
530    /// Fingerprint of the last gap signature, if any.
531    #[serde(default, skip_serializing_if = "Option::is_none")]
532    last_gap_fingerprint: Option<String>,
533    /// Live token count for active subagents.
534    #[serde(skip)]
535    live_subagent_tokens: u64,
536    /// Live token usage broken down by model.
537    #[serde(skip)]
538    live_tokens_by_model: Vec<(String, u64)>,
539    /// Live context window size in tokens.
540    #[serde(skip)]
541    live_context_window: u64,
542    /// Live context window utilization percentage (0-100).
543    #[serde(skip)]
544    live_context_pct: u8,
545    /// Live turn count for the current goal.
546    #[serde(skip)]
547    live_turn_count: u32,
548    /// Live tool call count for the current goal.
549    #[serde(skip)]
550    live_tool_call_count: u32,
551    /// Whether a planning pass is currently in flight.
552    #[serde(skip)]
553    planning_in_flight: bool,
554    /// Whether a verification pass is currently in flight.
555    #[serde(skip)]
556    verifying_in_flight: bool,
557}
558
559impl GoalOrchestration {
560    fn reset_strategist_fields(&mut self) {
561        self.consecutive_not_achieved = 0;
562        self.last_strategist_fired_at = 0;
563        self.strategist_cap_bonus = 0;
564        self.last_strategy_path = None;
565        self.last_strategy_recommendation = None;
566    }
567
568    fn reset_classifier_stall_fields(&mut self) {
569        self.classifier_stall_count = 0;
570        self.last_gap_fingerprint = None;
571    }
572}
573
574/// Pure state machine for goal tracking.
575#[derive(Debug)]
576pub struct GoalTracker {
577    /// Current goal orchestration state, if a goal is active.
578    orchestration: Option<GoalOrchestration>,
579    /// Directory where progress snapshots are persisted.
580    session_dir: PathBuf,
581    /// Instant when the goal became active.
582    active_since: Option<Instant>,
583}
584
585impl GoalTracker {
586    /// Create a new tracker with no active goal.
587    pub fn new(session_dir: PathBuf) -> Self {
588        Self {
589            orchestration: None,
590            session_dir,
591            active_since: None,
592        }
593    }
594
595    /// Restore tracker state from a persisted snapshot.
596    pub fn from_snapshot(session_dir: PathBuf, mut snapshot: GoalOrchestration) -> Self {
597        match snapshot.phase {
598            GoalPhase::Planning | GoalPhase::Executing => {
599                snapshot.phase = GoalPhase::Idle;
600                if snapshot.status == GoalStatus::Active {
601                    snapshot.status = GoalStatus::UserPaused;
602                }
603                snapshot.current_subagent_id = None;
604                snapshot.current_subagent_role = None;
605            }
606            GoalPhase::Idle => {}
607        }
608        snapshot.planning_in_flight = false;
609        snapshot.verifying_in_flight = false;
610        let active_since = if snapshot.status == GoalStatus::Active {
611            Some(Instant::now())
612        } else {
613            None
614        };
615        Self {
616            orchestration: Some(snapshot),
617            session_dir,
618            active_since,
619        }
620    }
621
622    /// Return an immutable reference to the current orchestration snapshot.
623    fn snapshot(&self) -> Option<&GoalOrchestration> {
624        self.orchestration.as_ref()
625    }
626
627    /// Return a mutable reference to the current orchestration snapshot.
628    pub fn snapshot_mut(&mut self) -> Option<&mut GoalOrchestration> {
629        self.orchestration.as_mut()
630    }
631
632    /// `true` if a goal is currently active.
633    pub fn is_active(&self) -> bool {
634        self.orchestration.as_ref().is_some_and(|o| o.status == GoalStatus::Active)
635    }
636
637    /// Current execution phase, if a goal is active.
638    pub fn phase(&self) -> Option<GoalPhase> {
639        self.orchestration.as_ref().map(|o| o.phase)
640    }
641
642    /// Current lifecycle status, if a goal is active.
643    pub fn status(&self) -> Option<GoalStatus> {
644        self.orchestration.as_ref().map(|o| o.status)
645    }
646
647    /// ID of the currently executing subagent, if any.
648    fn current_subagent_id(&self) -> Option<&str> {
649        self.orchestration.as_ref().and_then(|o| o.current_subagent_id.as_deref())
650    }
651
652    /// Human-readable objective, if a goal is active.
653    pub fn objective(&self) -> Option<&str> {
654        self.orchestration.as_ref().map(|o| o.objective.as_str())
655    }
656
657    /// Token budget cap, if set.
658    pub fn token_budget(&self) -> Option<i64> {
659        self.orchestration.as_ref().and_then(|o| o.token_budget)
660    }
661
662    /// Create a new goal. Replaces any existing orchestration.
663    pub fn create_goal(
664        &mut self,
665        goal_id: String,
666        objective: String,
667        token_budget: Option<i64>,
668        token_baseline: i64,
669        created_at: String,
670        baseline_commit: Option<String>,
671    ) {
672        let _ = std::fs::create_dir_all(self.goal_dir());
673        if self.orchestration.is_some() {
674            self.remove_scratch_root();
675        }
676        self.orchestration = Some(GoalOrchestration {
677            goal_id,
678            objective,
679            status: GoalStatus::Active,
680            phase: GoalPhase::Executing,
681            token_budget,
682            elapsed_ms: 0,
683            created_at,
684            current_subagent_id: None,
685            current_subagent_role: None,
686            total_worker_rounds: 0,
687            total_verify_rounds: 0,
688            budget_limit_reported: false,
689            token_baseline,
690            tokens_used_high_water: 0,
691            parent_tokens_spent: 0,
692            last_session_tokens_seen: Some(token_baseline),
693            history: Vec::new(),
694            pause_message: None,
695            classifier_stall_count: 0,
696            classifier_runs_attempted: 0,
697            rounds_since_verify: 0,
698            consecutive_not_achieved: 0,
699            auto_continue_turns: 0,
700            last_strategist_fired_at: 0,
701            strategist_cap_bonus: 0,
702            last_strategy_path: None,
703            last_strategy_recommendation: None,
704            changes_baseline_commit: baseline_commit,
705            last_gap_fingerprint: None,
706            live_subagent_tokens: 0,
707            live_tokens_by_model: Vec::new(),
708            live_context_window: 0,
709            live_context_pct: 0,
710            live_turn_count: 0,
711            live_tool_call_count: 0,
712            planning_in_flight: false,
713            verifying_in_flight: false,
714        });
715        self.active_since = Some(Instant::now());
716        self.record_event(GoalEvent::GoalCreated, None);
717    }
718
719    /// Update the execution phase of the active goal.
720    fn set_phase(&mut self, phase: GoalPhase) {
721        if let Some(o) = &mut self.orchestration {
722            o.phase = phase;
723        }
724    }
725
726    /// Update the current subagent ID and role.
727    fn set_current_subagent(&mut self, id: Option<String>, role: Option<String>) {
728        if let Some(o) = &mut self.orchestration {
729            o.current_subagent_id = id;
730            o.current_subagent_role = role;
731        }
732    }
733
734    /// Pause the goal with a specific reason. Only transitions from `Active`.
735    pub fn pause(&mut self, reason: GoalPauseReason) -> bool {
736        self.pause_inner(reason, None)
737    }
738
739    /// Like [`Self::pause`] but also stores a human-readable `message`.
740    pub fn pause_with_message(&mut self, reason: GoalPauseReason, message: String) -> bool {
741        self.pause_inner(reason, Some(message))
742    }
743
744    fn pause_inner(&mut self, reason: GoalPauseReason, message: Option<String>) -> bool {
745        let applied = if let Some(o) = &mut self.orchestration
746            && o.status == GoalStatus::Active
747        {
748            if let Some(since) = self.active_since.take() {
749                o.elapsed_ms = o.elapsed_ms.saturating_add(since.elapsed().as_millis() as u64);
750            }
751            o.status = reason.to_status();
752            if message.is_some() {
753                o.pause_message = message;
754            }
755            true
756        } else {
757            false
758        };
759        if applied {
760            self.record_event(GoalEvent::GoalPaused, Some(reason.history_detail().to_owned()));
761        }
762        applied
763    }
764
765    /// Resume a paused goal (any paused variant). Returns `true` if applied.
766    pub fn resume(&mut self) -> bool {
767        if let Some(o) = &mut self.orchestration
768            && o.status.is_paused()
769        {
770            o.status = GoalStatus::Active;
771            o.pause_message = None;
772            o.classifier_runs_attempted = 0;
773            o.rounds_since_verify = 0;
774            o.auto_continue_turns = 0;
775            o.reset_strategist_fields();
776            o.reset_classifier_stall_fields();
777            self.active_since = Some(Instant::now());
778            self.record_event(GoalEvent::GoalResumed, None);
779            return true;
780        }
781        false
782    }
783
784    /// Mark the goal as complete. Accepts `Active` or any paused variant.
785    pub fn complete(&mut self) -> bool {
786        if let Some(o) = &mut self.orchestration
787            && (o.status == GoalStatus::Active || o.status.is_paused())
788        {
789            if let Some(since) = self.active_since.take() {
790                o.elapsed_ms = o.elapsed_ms.saturating_add(since.elapsed().as_millis() as u64);
791            }
792            o.status = GoalStatus::Complete;
793            o.phase = GoalPhase::Idle;
794            o.current_subagent_id = None;
795            o.current_subagent_role = None;
796            o.pause_message = None;
797            o.reset_strategist_fields();
798            self.record_event(GoalEvent::GoalCompleted, None);
799            return true;
800        }
801        false
802    }
803
804    /// Mark the goal as budget-limited. Accepts `Active` or any paused variant.
805    pub fn budget_limit(&mut self) -> bool {
806        if let Some(o) = &mut self.orchestration
807            && (o.status == GoalStatus::Active || o.status.is_paused())
808        {
809            if let Some(since) = self.active_since.take() {
810                o.elapsed_ms = o.elapsed_ms.saturating_add(since.elapsed().as_millis() as u64);
811            }
812            o.status = GoalStatus::BudgetLimited;
813            o.phase = GoalPhase::Idle;
814            o.current_subagent_id = None;
815            o.current_subagent_role = None;
816            o.pause_message = None;
817            o.reset_strategist_fields();
818            self.record_event(GoalEvent::BudgetExceeded, None);
819            return true;
820        }
821        false
822    }
823
824    /// Clear the goal entirely.
825    pub fn clear(&mut self) {
826        self.orchestration = None;
827        self.active_since = None;
828    }
829
830    fn goal_dir(&self) -> PathBuf {
831        self.session_dir.join("goal")
832    }
833
834    fn remove_scratch_root(&self) {
835        let _ = std::fs::remove_dir_all(self.session_dir.join("goal"));
836    }
837
838    /// Flush elapsed wall-clock time into `elapsed_ms`.
839    pub fn account_elapsed(&mut self) {
840        if let Some(o) = &mut self.orchestration
841            && let Some(since) = self.active_since
842        {
843            o.elapsed_ms = o.elapsed_ms.saturating_add(since.elapsed().as_millis() as u64);
844            self.active_since = Some(Instant::now());
845        }
846    }
847
848    /// Record a `NotAchieved` rejection's gap `fingerprint` and report
849    /// whether the goal has stalled.
850    fn record_classifier_stall(&mut self, fingerprint: &str) -> bool {
851        let Some(o) = self.orchestration.as_mut() else {
852            return false;
853        };
854        if o.last_gap_fingerprint.as_deref() == Some(fingerprint) {
855            o.classifier_stall_count = o.classifier_stall_count.saturating_add(1);
856        } else {
857            o.last_gap_fingerprint = Some(fingerprint.to_string());
858            o.classifier_stall_count = 1;
859        }
860        o.classifier_stall_count >= 2
861    }
862
863    /// Undo the most recent attempt-slot reservation.
864    pub fn rollback_classifier_attempt(&mut self) {
865        if let Some(o) = self.orchestration.as_mut() {
866            o.classifier_runs_attempted = o.classifier_runs_attempted.saturating_sub(1);
867        }
868    }
869
870    /// Clear the stall streak.
871    fn reset_classifier_stall(&mut self) {
872        if let Some(o) = self.orchestration.as_mut() {
873            o.reset_classifier_stall_fields();
874        }
875    }
876
877    /// Increment the consecutive-`NotAchieved` streak and return the new value.
878    fn record_not_achieved_streak(&mut self) -> u32 {
879        match self.orchestration.as_mut() {
880            Some(o) => {
881                o.consecutive_not_achieved = o.consecutive_not_achieved.saturating_add(1);
882                o.consecutive_not_achieved
883            }
884            None => 0,
885        }
886    }
887
888    /// Atomically evaluate the strategist trigger and claim a fire.
889    pub fn claim_strategist_fire(&mut self, should_fire: impl Fn(u32, u32) -> bool) -> Option<u32> {
890        let o = self.orchestration.as_mut()?;
891        if should_fire(o.consecutive_not_achieved, o.last_strategist_fired_at) {
892            o.last_strategist_fired_at = o.consecutive_not_achieved;
893            o.strategist_cap_bonus = 3;
894            o.reset_classifier_stall_fields();
895            Some(o.consecutive_not_achieved)
896        } else {
897            None
898        }
899    }
900
901    /// Revoke the cap bonus granted by [`Self::claim_strategist_fire`].
902    pub fn revoke_strategist_cap_bonus(&mut self) {
903        if let Some(o) = self.orchestration.as_mut() {
904            o.strategist_cap_bonus = 0;
905        }
906    }
907
908    /// Reset ALL strategist state.
909    fn reset_strategist_state(&mut self) {
910        if let Some(o) = self.orchestration.as_mut() {
911            o.reset_strategist_fields();
912        }
913    }
914
915    /// Persist the strategist's latest output path + short recommendation.
916    fn record_strategy_recommendation(&mut self, path: String, recommendation: String) {
917        if let Some(o) = self.orchestration.as_mut() {
918            o.last_strategy_path = Some(path);
919            o.last_strategy_recommendation = Some(recommendation);
920        }
921    }
922
923    /// Append a history entry to the active goal, if any.
924    fn append_history(&mut self, entry: GoalHistoryEntry) {
925        if let Some(o) = &mut self.orchestration {
926            o.history.push(entry);
927        }
928    }
929
930    fn record_event(&mut self, event: GoalEvent, detail: Option<String>) {
931        self.append_history(GoalHistoryEntry::now(event, detail));
932    }
933}
934
935mod goal_api;
936#[cfg(test)]
937mod goal_tracker_tests;
938#[cfg(test)]
939mod progress_tests;