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 tokens_used_high_water: i64,
483 #[serde(default)]
485 parent_tokens_spent: i64,
486 history: Vec<GoalHistoryEntry>,
488 #[serde(default, skip_serializing_if = "Option::is_none")]
490 pause_message: Option<String>,
491 #[serde(default)]
493 classifier_stall_count: u32,
494 #[serde(default)]
496 classifier_runs_attempted: u32,
497 #[serde(default)]
499 rounds_since_verify: u32,
500 #[serde(default)]
502 consecutive_not_achieved: u32,
503 #[serde(default)]
508 auto_continue_turns: u8,
509 #[serde(default)]
511 last_strategist_fired_at: u32,
512 #[serde(default)]
514 strategist_cap_bonus: u32,
515 #[serde(default, skip_serializing_if = "Option::is_none")]
517 last_strategy_path: Option<String>,
518 #[serde(default, skip_serializing_if = "Option::is_none")]
520 last_strategy_recommendation: Option<String>,
521 #[serde(default, skip_serializing_if = "Option::is_none")]
523 changes_baseline_commit: Option<String>,
524 #[serde(default, skip_serializing_if = "Option::is_none")]
526 last_gap_fingerprint: Option<String>,
527 #[serde(skip)]
529 live_subagent_tokens: u64,
530 #[serde(skip)]
532 live_tokens_by_model: Vec<(String, u64)>,
533 #[serde(skip)]
535 live_context_window: u64,
536 #[serde(skip)]
538 live_context_pct: u8,
539 #[serde(skip)]
541 live_turn_count: u32,
542 #[serde(skip)]
544 live_tool_call_count: u32,
545 #[serde(skip)]
547 planning_in_flight: bool,
548 #[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#[derive(Debug, Clone)]
570pub struct GoalTracker {
571 orchestration: Option<GoalOrchestration>,
573 session_dir: PathBuf,
575 active_since: Option<Instant>,
577 last_session_tokens_seen: Option<i64>,
579 activation_id: Option<uuid::Uuid>,
581}
582
583impl GoalTracker {
584 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 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 fn snapshot(&self) -> Option<&GoalOrchestration> {
621 self.orchestration.as_ref()
622 }
623
624 pub fn snapshot_mut(&mut self) -> Option<&mut GoalOrchestration> {
626 self.orchestration.as_mut()
627 }
628
629 pub fn is_active(&self) -> bool {
631 self.orchestration.as_ref().is_some_and(|o| o.status == GoalStatus::Active)
632 }
633
634 pub fn phase(&self) -> Option<GoalPhase> {
636 self.orchestration.as_ref().map(|o| o.phase)
637 }
638
639 pub fn status(&self) -> Option<GoalStatus> {
641 self.orchestration.as_ref().map(|o| o.status)
642 }
643
644 fn current_subagent_id(&self) -> Option<&str> {
646 self.orchestration.as_ref().and_then(|o| o.current_subagent_id.as_deref())
647 }
648
649 pub fn objective(&self) -> Option<&str> {
651 self.orchestration.as_ref().map(|o| o.objective.as_str())
652 }
653
654 pub fn token_budget(&self) -> Option<i64> {
656 self.orchestration.as_ref().and_then(|o| o.token_budget)
657 }
658
659 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 fn set_phase(&mut self, phase: GoalPhase) {
714 if let Some(o) = &mut self.orchestration {
715 o.phase = phase;
716 }
717 }
718
719 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 pub fn pause(&mut self, reason: GoalPauseReason) -> bool {
729 self.pause_inner(reason, None)
730 }
731
732 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 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 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 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 pub fn clear(&mut self) {
820 self.orchestration = None;
821 self.active_since = None;
822 }
823
824 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 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 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 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 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 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 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 fn reset_strategist_state(&mut self) {
896 if let Some(o) = self.orchestration.as_mut() {
897 o.reset_strategist_fields();
898 }
899 }
900
901 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 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;