1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(rename_all = "snake_case")]
24pub enum MilestoneStatus {
25 Pending,
27 InProgress,
29 Done,
31 Blocked,
33}
34
35impl MilestoneStatus {
36 #[must_use]
38 fn is_terminal(&self) -> bool {
39 matches!(self, MilestoneStatus::Done)
40 }
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45pub struct Milestone {
46 pub id: String,
48 pub description: String,
50 pub status: MilestoneStatus,
52}
53
54#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
61pub struct ProgressLedger {
62 pub session_id: String,
64 pub goal: String,
66 milestones: Vec<Milestone>,
68 pub confidence: f32,
70 stalled_since: Option<String>,
73 updated_at: String,
75 #[serde(default)]
78 previous_session_id: Option<String>,
79 #[serde(default)]
81 handoff_summary: Option<String>,
82 #[serde(default)]
84 known_issues: Vec<String>,
85 #[serde(default)]
87 git_checkpoint: Option<String>,
88}
89
90impl ProgressLedger {
91 #[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 #[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 #[must_use]
122 pub fn is_complete(&self) -> bool {
123 self.completion_ratio() >= 1.0
124 }
125
126 #[must_use]
128 pub fn is_stalled(&self) -> bool {
129 self.stalled_since.is_some()
130 }
131
132 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 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 pub fn set_milestones(&mut self, milestones: Vec<Milestone>) {
152 self.milestones = milestones;
153 self.updated_at = Utc::now().to_rfc3339();
154 }
155
156 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 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 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 #[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
229use std::time::Instant;
234
235#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
237#[serde(rename_all = "snake_case")]
238pub enum GoalPhase {
239 Idle,
241 Planning,
243 Executing,
245}
246
247#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
261#[serde(rename_all = "snake_case")]
262pub enum GoalStatus {
263 #[serde(alias = "Active")]
265 Active,
266 #[serde(alias = "Paused")]
268 UserPaused,
269 BackOffPaused,
271 NoProgressPaused,
273 InfraPaused,
275 Blocked,
277 #[serde(alias = "BudgetLimited")]
279 BudgetLimited,
280 #[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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
326pub enum GoalPauseReason {
327 User,
329 BackOff,
331 NoProgress,
333 Verification,
335 Infra,
337 ModelBlocked,
339 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
371#[serde(rename_all = "snake_case")]
372pub enum GoalClassifierVerdict {
373 Achieved,
375 NotAchieved,
377}
378
379#[derive(Debug, Clone, Serialize, Deserialize)]
381#[serde(rename_all = "snake_case")]
382pub enum GoalEvent {
383 GoalCreated,
385 PlanningStarted,
387 PlanningCompleted,
389 PlanningFailed,
391 WorkerStarted,
393 WorkerCompleted,
395 WorkerFailed,
397 ContextRotated,
399 GoalPaused,
401 GoalResumed,
403 GoalCompleted,
405 GoalCleared,
407 BudgetExceeded,
409 PrematureStopDetected,
411 #[serde(other)]
413 Unknown,
414}
415
416#[derive(Debug, Clone, Serialize, Deserialize)]
418pub struct GoalHistoryEntry {
419 timestamp: String,
421 event: GoalEvent,
423 #[serde(default, skip_serializing_if = "Option::is_none")]
425 detail: Option<String>,
426 #[serde(default, skip_serializing_if = "Option::is_none")]
428 round: Option<u32>,
429 #[serde(default, skip_serializing_if = "Option::is_none")]
431 tokens_used: Option<i64>,
432 #[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#[derive(Debug, Clone, Serialize, Deserialize)]
452pub struct GoalOrchestration {
453 goal_id: String,
455 objective: String,
457 status: GoalStatus,
459 phase: GoalPhase,
461 token_budget: Option<i64>,
463 elapsed_ms: u64,
465 created_at: String,
467 current_subagent_id: Option<String>,
469 current_subagent_role: Option<String>,
471 #[serde(default)]
473 total_worker_rounds: u32,
474 #[serde(default)]
476 total_verify_rounds: u32,
477 #[serde(skip)]
479 budget_limit_reported: bool,
480 #[serde(default)]
482 token_baseline: i64,
483 #[serde(default)]
485 tokens_used_high_water: i64,
486 #[serde(default)]
488 parent_tokens_spent: i64,
489 #[serde(default)]
491 last_session_tokens_seen: Option<i64>,
492 history: Vec<GoalHistoryEntry>,
494 #[serde(default, skip_serializing_if = "Option::is_none")]
496 pause_message: Option<String>,
497 #[serde(default)]
499 classifier_stall_count: u32,
500 #[serde(default)]
502 classifier_runs_attempted: u32,
503 #[serde(default)]
505 rounds_since_verify: u32,
506 #[serde(default)]
508 consecutive_not_achieved: u32,
509 #[serde(default)]
514 auto_continue_turns: u8,
515 #[serde(default)]
517 last_strategist_fired_at: u32,
518 #[serde(default)]
520 strategist_cap_bonus: u32,
521 #[serde(default, skip_serializing_if = "Option::is_none")]
523 last_strategy_path: Option<String>,
524 #[serde(default, skip_serializing_if = "Option::is_none")]
526 last_strategy_recommendation: Option<String>,
527 #[serde(default, skip_serializing_if = "Option::is_none")]
529 changes_baseline_commit: Option<String>,
530 #[serde(default, skip_serializing_if = "Option::is_none")]
532 last_gap_fingerprint: Option<String>,
533 #[serde(skip)]
535 live_subagent_tokens: u64,
536 #[serde(skip)]
538 live_tokens_by_model: Vec<(String, u64)>,
539 #[serde(skip)]
541 live_context_window: u64,
542 #[serde(skip)]
544 live_context_pct: u8,
545 #[serde(skip)]
547 live_turn_count: u32,
548 #[serde(skip)]
550 live_tool_call_count: u32,
551 #[serde(skip)]
553 planning_in_flight: bool,
554 #[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#[derive(Debug)]
576pub struct GoalTracker {
577 orchestration: Option<GoalOrchestration>,
579 session_dir: PathBuf,
581 active_since: Option<Instant>,
583}
584
585impl GoalTracker {
586 pub fn new(session_dir: PathBuf) -> Self {
588 Self {
589 orchestration: None,
590 session_dir,
591 active_since: None,
592 }
593 }
594
595 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 fn snapshot(&self) -> Option<&GoalOrchestration> {
624 self.orchestration.as_ref()
625 }
626
627 pub fn snapshot_mut(&mut self) -> Option<&mut GoalOrchestration> {
629 self.orchestration.as_mut()
630 }
631
632 pub fn is_active(&self) -> bool {
634 self.orchestration.as_ref().is_some_and(|o| o.status == GoalStatus::Active)
635 }
636
637 pub fn phase(&self) -> Option<GoalPhase> {
639 self.orchestration.as_ref().map(|o| o.phase)
640 }
641
642 pub fn status(&self) -> Option<GoalStatus> {
644 self.orchestration.as_ref().map(|o| o.status)
645 }
646
647 fn current_subagent_id(&self) -> Option<&str> {
649 self.orchestration.as_ref().and_then(|o| o.current_subagent_id.as_deref())
650 }
651
652 pub fn objective(&self) -> Option<&str> {
654 self.orchestration.as_ref().map(|o| o.objective.as_str())
655 }
656
657 pub fn token_budget(&self) -> Option<i64> {
659 self.orchestration.as_ref().and_then(|o| o.token_budget)
660 }
661
662 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 fn set_phase(&mut self, phase: GoalPhase) {
721 if let Some(o) = &mut self.orchestration {
722 o.phase = phase;
723 }
724 }
725
726 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 pub fn pause(&mut self, reason: GoalPauseReason) -> bool {
736 self.pause_inner(reason, None)
737 }
738
739 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 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 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 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 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 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 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 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 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 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 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 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 fn reset_strategist_state(&mut self) {
910 if let Some(o) = self.orchestration.as_mut() {
911 o.reset_strategist_fields();
912 }
913 }
914
915 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 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;