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    /// Tokens charged across active intervals, including across process restarts.
481    #[serde(default)]
482    tokens_used_high_water: i64,
483    /// Tokens spent by the parent session before this goal started.
484    #[serde(default)]
485    parent_tokens_spent: i64,
486    /// Ordered history of lifecycle events.
487    history: Vec<GoalHistoryEntry>,
488    /// User-facing pause message, if any.
489    #[serde(default, skip_serializing_if = "Option::is_none")]
490    pause_message: Option<String>,
491    /// Number of consecutive classifier stall detections.
492    #[serde(default)]
493    classifier_stall_count: u32,
494    /// Total classifier run attempts.
495    #[serde(default)]
496    classifier_runs_attempted: u32,
497    /// Rounds since the last verification pass.
498    #[serde(default)]
499    rounds_since_verify: u32,
500    /// Consecutive not-achieved verdicts.
501    #[serde(default)]
502    consecutive_not_achieved: u32,
503    /// Consumed goal-loop auto-continue turns this episode. Reset by
504    /// [`GoalTracker::create_goal`](GoalTracker::create_goal) and
505    /// [`GoalTracker::resume`](GoalTracker::resume) so every fresh or resumed
506    /// goal gets a full budget on every frontend.
507    #[serde(default)]
508    auto_continue_turns: u8,
509    /// Turn at which the strategist last fired.
510    #[serde(default)]
511    last_strategist_fired_at: u32,
512    /// Bonus tokens granted by the strategist.
513    #[serde(default)]
514    strategist_cap_bonus: u32,
515    /// Path of the last strategy recommendation, if any.
516    #[serde(default, skip_serializing_if = "Option::is_none")]
517    last_strategy_path: Option<String>,
518    /// Last strategy recommendation text, if any.
519    #[serde(default, skip_serializing_if = "Option::is_none")]
520    last_strategy_recommendation: Option<String>,
521    /// Commit hash at the last strategy change baseline, if any.
522    #[serde(default, skip_serializing_if = "Option::is_none")]
523    changes_baseline_commit: Option<String>,
524    /// Fingerprint of the last gap signature, if any.
525    #[serde(default, skip_serializing_if = "Option::is_none")]
526    last_gap_fingerprint: Option<String>,
527    /// Live token count for active subagents.
528    #[serde(skip)]
529    live_subagent_tokens: u64,
530    /// Live token usage broken down by model.
531    #[serde(skip)]
532    live_tokens_by_model: Vec<(String, u64)>,
533    /// Live context window size in tokens.
534    #[serde(skip)]
535    live_context_window: u64,
536    /// Live context window utilization percentage (0-100).
537    #[serde(skip)]
538    live_context_pct: u8,
539    /// Live turn count for the current goal.
540    #[serde(skip)]
541    live_turn_count: u32,
542    /// Live tool call count for the current goal.
543    #[serde(skip)]
544    live_tool_call_count: u32,
545    /// Whether a planning pass is currently in flight.
546    #[serde(skip)]
547    planning_in_flight: bool,
548    /// Whether a verification pass is currently in flight.
549    #[serde(skip)]
550    verifying_in_flight: bool,
551}
552
553impl GoalOrchestration {
554    fn reset_strategist_fields(&mut self) {
555        self.consecutive_not_achieved = 0;
556        self.last_strategist_fired_at = 0;
557        self.strategist_cap_bonus = 0;
558        self.last_strategy_path = None;
559        self.last_strategy_recommendation = None;
560    }
561
562    fn reset_classifier_stall_fields(&mut self) {
563        self.classifier_stall_count = 0;
564        self.last_gap_fingerprint = None;
565    }
566}
567
568/// Pure state machine for goal tracking.
569#[derive(Debug, Clone)]
570pub struct GoalTracker {
571    /// Current goal orchestration state, if a goal is active.
572    orchestration: Option<GoalOrchestration>,
573    /// Directory where progress snapshots are persisted.
574    session_dir: PathBuf,
575    /// Instant when the goal became active.
576    active_since: Option<Instant>,
577    /// Observation cursor for this runloop only. Its token total resets on reopen.
578    last_session_tokens_seen: Option<i64>,
579    /// Changes whenever work is explicitly started or resumed.
580    activation_id: Option<uuid::Uuid>,
581}
582
583impl GoalTracker {
584    /// Create a new tracker with no active goal.
585    pub fn new(session_dir: PathBuf) -> Self {
586        Self {
587            orchestration: None,
588            session_dir,
589            active_since: None,
590            last_session_tokens_seen: None,
591            activation_id: 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        if snapshot.status == GoalStatus::Active {
598            snapshot.status = GoalStatus::UserPaused;
599        }
600        match snapshot.phase {
601            GoalPhase::Planning | GoalPhase::Executing => {
602                snapshot.phase = GoalPhase::Idle;
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        Self {
611            orchestration: Some(snapshot),
612            session_dir,
613            active_since: None,
614            last_session_tokens_seen: None,
615            activation_id: None,
616        }
617    }
618
619    /// Return an immutable reference to the current orchestration snapshot.
620    fn snapshot(&self) -> Option<&GoalOrchestration> {
621        self.orchestration.as_ref()
622    }
623
624    /// Return a mutable reference to the current orchestration snapshot.
625    pub fn snapshot_mut(&mut self) -> Option<&mut GoalOrchestration> {
626        self.orchestration.as_mut()
627    }
628
629    /// `true` if a goal is currently active.
630    pub fn is_active(&self) -> bool {
631        self.orchestration.as_ref().is_some_and(|o| o.status == GoalStatus::Active)
632    }
633
634    /// Current execution phase, if a goal is active.
635    pub fn phase(&self) -> Option<GoalPhase> {
636        self.orchestration.as_ref().map(|o| o.phase)
637    }
638
639    /// Current lifecycle status, if a goal is active.
640    pub fn status(&self) -> Option<GoalStatus> {
641        self.orchestration.as_ref().map(|o| o.status)
642    }
643
644    /// ID of the currently executing subagent, if any.
645    fn current_subagent_id(&self) -> Option<&str> {
646        self.orchestration.as_ref().and_then(|o| o.current_subagent_id.as_deref())
647    }
648
649    /// Human-readable objective, if a goal is active.
650    pub fn objective(&self) -> Option<&str> {
651        self.orchestration.as_ref().map(|o| o.objective.as_str())
652    }
653
654    /// Token budget cap, if set.
655    pub fn token_budget(&self) -> Option<i64> {
656        self.orchestration.as_ref().and_then(|o| o.token_budget)
657    }
658
659    /// Create a new goal. Replaces any existing orchestration.
660    pub fn create_goal(
661        &mut self,
662        goal_id: String,
663        objective: String,
664        token_budget: Option<i64>,
665        token_baseline: i64,
666        created_at: String,
667        baseline_commit: Option<String>,
668    ) {
669        self.orchestration = Some(GoalOrchestration {
670            goal_id,
671            objective,
672            status: GoalStatus::Active,
673            phase: GoalPhase::Executing,
674            token_budget,
675            elapsed_ms: 0,
676            created_at,
677            current_subagent_id: None,
678            current_subagent_role: None,
679            total_worker_rounds: 0,
680            total_verify_rounds: 0,
681            budget_limit_reported: false,
682            tokens_used_high_water: 0,
683            parent_tokens_spent: 0,
684            history: Vec::new(),
685            pause_message: None,
686            classifier_stall_count: 0,
687            classifier_runs_attempted: 0,
688            rounds_since_verify: 0,
689            consecutive_not_achieved: 0,
690            auto_continue_turns: 0,
691            last_strategist_fired_at: 0,
692            strategist_cap_bonus: 0,
693            last_strategy_path: None,
694            last_strategy_recommendation: None,
695            changes_baseline_commit: baseline_commit,
696            last_gap_fingerprint: None,
697            live_subagent_tokens: 0,
698            live_tokens_by_model: Vec::new(),
699            live_context_window: 0,
700            live_context_pct: 0,
701            live_turn_count: 0,
702            live_tool_call_count: 0,
703            planning_in_flight: false,
704            verifying_in_flight: false,
705        });
706        self.active_since = Some(Instant::now());
707        self.activation_id = Some(uuid::Uuid::new_v4());
708        self.last_session_tokens_seen = Some(token_baseline.max(0));
709        self.record_event(GoalEvent::GoalCreated, None);
710    }
711
712    /// Update the execution phase of the active goal.
713    fn set_phase(&mut self, phase: GoalPhase) {
714        if let Some(o) = &mut self.orchestration {
715            o.phase = phase;
716        }
717    }
718
719    /// Update the current subagent ID and role.
720    fn set_current_subagent(&mut self, id: Option<String>, role: Option<String>) {
721        if let Some(o) = &mut self.orchestration {
722            o.current_subagent_id = id;
723            o.current_subagent_role = role;
724        }
725    }
726
727    /// Pause the goal with a specific reason. Only transitions from `Active`.
728    pub fn pause(&mut self, reason: GoalPauseReason) -> bool {
729        self.pause_inner(reason, None)
730    }
731
732    /// Like [`Self::pause`] but also stores a human-readable `message`.
733    pub fn pause_with_message(&mut self, reason: GoalPauseReason, message: String) -> bool {
734        self.pause_inner(reason, Some(message))
735    }
736
737    fn pause_inner(&mut self, reason: GoalPauseReason, message: Option<String>) -> bool {
738        let applied = if let Some(o) = &mut self.orchestration
739            && o.status == GoalStatus::Active
740        {
741            if let Some(since) = self.active_since.take() {
742                o.elapsed_ms = o.elapsed_ms.saturating_add(since.elapsed().as_millis() as u64);
743            }
744            o.status = reason.to_status();
745            if message.is_some() {
746                o.pause_message = message;
747            }
748            true
749        } else {
750            false
751        };
752        if applied {
753            self.record_event(GoalEvent::GoalPaused, Some(reason.history_detail().to_owned()));
754        }
755        applied
756    }
757
758    /// Resume a paused goal (any paused variant). Returns `true` if applied.
759    pub fn resume(&mut self) -> bool {
760        if let Some(o) = &mut self.orchestration
761            && o.status.is_paused()
762        {
763            o.status = GoalStatus::Active;
764            o.pause_message = None;
765            o.classifier_runs_attempted = 0;
766            o.rounds_since_verify = 0;
767            o.auto_continue_turns = 0;
768            o.reset_strategist_fields();
769            o.reset_classifier_stall_fields();
770            self.active_since = Some(Instant::now());
771            self.activation_id = Some(uuid::Uuid::new_v4());
772            self.record_event(GoalEvent::GoalResumed, None);
773            return true;
774        }
775        false
776    }
777
778    /// Mark the goal as complete. Accepts `Active` or any paused variant.
779    pub fn complete(&mut self) -> bool {
780        if let Some(o) = &mut self.orchestration
781            && (o.status == GoalStatus::Active || o.status.is_paused())
782        {
783            if let Some(since) = self.active_since.take() {
784                o.elapsed_ms = o.elapsed_ms.saturating_add(since.elapsed().as_millis() as u64);
785            }
786            o.status = GoalStatus::Complete;
787            o.phase = GoalPhase::Idle;
788            o.current_subagent_id = None;
789            o.current_subagent_role = None;
790            o.pause_message = None;
791            o.reset_strategist_fields();
792            self.record_event(GoalEvent::GoalCompleted, None);
793            return true;
794        }
795        false
796    }
797
798    /// Mark the goal as budget-limited. Accepts `Active` or any paused variant.
799    pub fn budget_limit(&mut self) -> bool {
800        if let Some(o) = &mut self.orchestration
801            && (o.status == GoalStatus::Active || o.status.is_paused())
802        {
803            if let Some(since) = self.active_since.take() {
804                o.elapsed_ms = o.elapsed_ms.saturating_add(since.elapsed().as_millis() as u64);
805            }
806            o.status = GoalStatus::BudgetLimited;
807            o.phase = GoalPhase::Idle;
808            o.current_subagent_id = None;
809            o.current_subagent_role = None;
810            o.pause_message = None;
811            o.reset_strategist_fields();
812            self.record_event(GoalEvent::BudgetExceeded, None);
813            return true;
814        }
815        false
816    }
817
818    /// Clear the goal entirely.
819    pub fn clear(&mut self) {
820        self.orchestration = None;
821        self.active_since = None;
822    }
823
824    /// Flush elapsed wall-clock time into `elapsed_ms`.
825    pub fn account_elapsed(&mut self) {
826        if let Some(o) = &mut self.orchestration
827            && let Some(since) = self.active_since
828        {
829            o.elapsed_ms = o.elapsed_ms.saturating_add(since.elapsed().as_millis() as u64);
830            self.active_since = Some(Instant::now());
831        }
832    }
833
834    /// Record a `NotAchieved` rejection's gap `fingerprint` and report
835    /// whether the goal has stalled.
836    fn record_classifier_stall(&mut self, fingerprint: &str) -> bool {
837        let Some(o) = self.orchestration.as_mut() else {
838            return false;
839        };
840        if o.last_gap_fingerprint.as_deref() == Some(fingerprint) {
841            o.classifier_stall_count = o.classifier_stall_count.saturating_add(1);
842        } else {
843            o.last_gap_fingerprint = Some(fingerprint.to_string());
844            o.classifier_stall_count = 1;
845        }
846        o.classifier_stall_count >= 2
847    }
848
849    /// Undo the most recent attempt-slot reservation.
850    pub fn rollback_classifier_attempt(&mut self) {
851        if let Some(o) = self.orchestration.as_mut() {
852            o.classifier_runs_attempted = o.classifier_runs_attempted.saturating_sub(1);
853        }
854    }
855
856    /// Clear the stall streak.
857    fn reset_classifier_stall(&mut self) {
858        if let Some(o) = self.orchestration.as_mut() {
859            o.reset_classifier_stall_fields();
860        }
861    }
862
863    /// Increment the consecutive-`NotAchieved` streak and return the new value.
864    fn record_not_achieved_streak(&mut self) -> u32 {
865        match self.orchestration.as_mut() {
866            Some(o) => {
867                o.consecutive_not_achieved = o.consecutive_not_achieved.saturating_add(1);
868                o.consecutive_not_achieved
869            }
870            None => 0,
871        }
872    }
873
874    /// Atomically evaluate the strategist trigger and claim a fire.
875    pub fn claim_strategist_fire(&mut self, should_fire: impl Fn(u32, u32) -> bool) -> Option<u32> {
876        let o = self.orchestration.as_mut()?;
877        if should_fire(o.consecutive_not_achieved, o.last_strategist_fired_at) {
878            o.last_strategist_fired_at = o.consecutive_not_achieved;
879            o.strategist_cap_bonus = 3;
880            o.reset_classifier_stall_fields();
881            Some(o.consecutive_not_achieved)
882        } else {
883            None
884        }
885    }
886
887    /// Revoke the cap bonus granted by [`Self::claim_strategist_fire`].
888    pub fn revoke_strategist_cap_bonus(&mut self) {
889        if let Some(o) = self.orchestration.as_mut() {
890            o.strategist_cap_bonus = 0;
891        }
892    }
893
894    /// Reset ALL strategist state.
895    fn reset_strategist_state(&mut self) {
896        if let Some(o) = self.orchestration.as_mut() {
897            o.reset_strategist_fields();
898        }
899    }
900
901    /// Persist the strategist's latest output path + short recommendation.
902    fn record_strategy_recommendation(&mut self, path: String, recommendation: String) {
903        if let Some(o) = self.orchestration.as_mut() {
904            o.last_strategy_path = Some(path);
905            o.last_strategy_recommendation = Some(recommendation);
906        }
907    }
908
909    /// Append a history entry to the active goal, if any.
910    fn append_history(&mut self, entry: GoalHistoryEntry) {
911        if let Some(o) = &mut self.orchestration {
912            o.history.push(entry);
913        }
914    }
915
916    fn record_event(&mut self, event: GoalEvent, detail: Option<String>) {
917        self.append_history(GoalHistoryEntry::now(event, detail));
918    }
919}
920
921mod goal_api;
922#[cfg(test)]
923mod goal_tracker_tests;
924#[cfg(test)]
925mod progress_tests;