1pub mod checklist_args;
11mod store;
12
13pub use store::{PlanStore, migrate_task_plans};
14
15pub const CHECKLIST_HEADER: &str = "Checklist updated";
19
20use chrono::{DateTime, Utc};
21use serde::{Deserialize, Serialize};
22use serde_json::Value as JsonValue;
23
24use crate::traits::ToolMutationEffects;
25pub use aidaemon_core::card::StepEvidence;
26use aidaemon_events::text::truncate_str;
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct TaskPlan {
31 pub id: String,
33
34 pub session_id: String,
36
37 pub description: String,
39
40 pub trigger_message: String,
42
43 pub steps: Vec<PlanStep>,
45
46 pub current_step: usize,
48
49 pub status: PlanStatus,
51
52 pub checkpoint: JsonValue,
54
55 pub creation_reason: String,
57
58 pub task_id: Option<String>,
60
61 pub created_at: DateTime<Utc>,
62 pub updated_at: DateTime<Utc>,
63}
64
65impl TaskPlan {
66 pub fn new(
68 session_id: impl Into<String>,
69 trigger_message: impl Into<String>,
70 description: impl Into<String>,
71 steps: Vec<String>,
72 creation_reason: impl Into<String>,
73 ) -> Self {
74 let now = Utc::now();
75 let plan_steps: Vec<PlanStep> = steps
76 .into_iter()
77 .enumerate()
78 .map(|(index, description)| PlanStep {
79 index,
80 description,
81 depends_on: index.checked_sub(1).into_iter().collect(),
82 required_mutation_effects: ToolMutationEffects::NONE,
83 requires_observation: false,
84 expected_targets: Vec::new(),
85 owner_units: Vec::new(),
86 evidence_receipt_ids: Vec::new(),
87 background_jobs: Vec::new(),
88 waited_jobs: Vec::new(),
89 made_folders: Vec::new(),
90 not_done: None,
91 evidence: StepEvidence::Settled,
92 status: if index == 0 {
93 StepStatus::InProgress
94 } else {
95 StepStatus::Pending
96 },
97 tool_call_ids: Vec::new(),
98 result_summary: None,
99 error: None,
100 retry_count: 0,
101 started_at: if index == 0 { Some(now) } else { None },
102 completed_at: None,
103 })
104 .collect();
105
106 Self {
107 id: uuid::Uuid::new_v4().to_string(),
108 session_id: session_id.into(),
109 description: description.into(),
110 trigger_message: trigger_message.into(),
111 steps: plan_steps,
112 current_step: 0,
113 status: PlanStatus::InProgress,
114 checkpoint: JsonValue::Object(serde_json::Map::new()),
115 creation_reason: creation_reason.into(),
116 task_id: None,
117 created_at: now,
118 updated_at: now,
119 }
120 }
121
122 pub fn current_step_ref(&self) -> Option<&PlanStep> {
124 self.steps.get(self.current_step)
125 }
126
127 pub fn current_step_mut(&mut self) -> Option<&mut PlanStep> {
129 self.steps.get_mut(self.current_step)
130 }
131
132 pub fn sync_active_step(&mut self) {
135 if let Some(index) = self
136 .steps
137 .iter()
138 .position(|step| step.status == StepStatus::InProgress)
139 {
140 self.current_step = index;
141 return;
142 }
143
144 if let Some(index) = self
145 .ready_step_indices()
146 .ok()
147 .and_then(|indices| indices.into_iter().next())
148 {
149 self.current_step = index;
150 if self.status == PlanStatus::InProgress {
151 let step = &mut self.steps[index];
152 step.status = StepStatus::InProgress;
153 step.started_at.get_or_insert_with(Utc::now);
154 }
155 } else if self.is_finished() {
156 self.status = self.resolved_status();
157 }
158 self.updated_at = Utc::now();
159 }
160
161 pub fn duration_secs(&self) -> u64 {
163 (self.updated_at - self.created_at).num_seconds().max(0) as u64
164 }
165
166 pub fn completed_steps(&self) -> usize {
168 self.steps
169 .iter()
170 .filter(|s| s.status == StepStatus::Completed)
171 .count()
172 }
173
174 pub fn unverified_steps(&self) -> usize {
177 self.steps.iter().filter(|s| s.unverified()).count()
178 }
179
180 pub fn confirm_steps(&mut self, indices: &std::collections::BTreeSet<usize>) -> bool {
184 let mut changed = false;
185 for step in &mut self.steps {
186 if step.evidence == StepEvidence::ModelSaid && indices.contains(&step.index) {
187 step.evidence = StepEvidence::Settled;
188 changed = true;
189 }
190 }
191 if changed {
192 self.updated_at = Utc::now();
193 }
194 changed
195 }
196
197 pub fn helper_did_not_start(&mut self, indices: &[usize], reason: &str) -> bool {
202 let now = Utc::now();
203 let mut changed = false;
204 for &index in indices {
205 let Some(step) = self.steps.get_mut(index) else {
206 continue;
207 };
208 if matches!(
209 step.status,
210 StepStatus::Completed | StepStatus::Skipped | StepStatus::Deferred
211 ) || (step.status == StepStatus::Background && !step.background_jobs.is_empty())
212 {
213 continue;
214 }
215 step.status = StepStatus::Failed;
216 step.evidence = StepEvidence::HelperNotStarted;
217 step.waited_jobs.clear();
218 step.error = Some(reason.to_string());
219 step.completed_at = Some(now);
220 changed = true;
221 }
222 if changed {
223 if self.is_finished() {
224 self.status = self.resolved_status();
225 } else {
226 self.sync_active_step();
227 }
228 self.updated_at = now;
229 }
230 changed
231 }
232
233 pub fn is_finished(&self) -> bool {
235 self.steps.iter().all(|s| {
236 matches!(
237 s.status,
238 StepStatus::Completed
239 | StepStatus::Failed
240 | StepStatus::Skipped
241 | StepStatus::Deferred
242 )
243 })
244 }
245
246 pub fn resolved_status(&self) -> PlanStatus {
249 if self
250 .steps
251 .iter()
252 .any(|step| step.status == StepStatus::Failed)
253 {
254 PlanStatus::Failed
255 } else if self
256 .steps
257 .iter()
258 .any(|step| step.status == StepStatus::Deferred)
259 {
260 PlanStatus::PartiallyCompleted
261 } else {
262 PlanStatus::Completed
263 }
264 }
265
266 pub fn validate_graph(&self) -> Result<(), String> {
268 self.step_graph().map(|_| ())
269 }
270
271 pub fn ready_step_indices(&self) -> Result<Vec<usize>, String> {
275 let graph = self.step_graph()?;
276 Ok(self
277 .steps
278 .iter()
279 .filter(|step| {
280 step.status == StepStatus::Pending
281 && graph.dependencies_satisfied(&plan_step_node_id(step.index))
282 })
283 .map(|step| step.index)
284 .collect())
285 }
286
287 fn step_graph(&self) -> Result<aidaemon_events::execution_graph::ExecutionGraph, String> {
288 use aidaemon_events::execution_graph::{
289 ExecutionEdgeKind, ExecutionGraph, ExecutionNodeKind, ExecutionNodeState,
290 };
291
292 let mut graph = ExecutionGraph::default();
293 for (position, step) in self.steps.iter().enumerate() {
294 if step.index != position {
295 return Err(format!(
296 "plan step index {} does not match position {}",
297 step.index, position
298 ));
299 }
300 let state = match step.status {
301 StepStatus::Pending => ExecutionNodeState::Pending,
302 StepStatus::InProgress | StepStatus::Background => ExecutionNodeState::Running,
303 StepStatus::Completed | StepStatus::Skipped | StepStatus::Deferred => {
304 ExecutionNodeState::Satisfied
305 }
306 StepStatus::Failed => ExecutionNodeState::Failed,
307 };
308 graph.add_node(
309 plan_step_node_id(step.index),
310 ExecutionNodeKind::PlanStep,
311 state,
312 )?;
313 }
314 for step in &self.steps {
315 let mut unique_dependencies = std::collections::BTreeSet::new();
316 for dependency in &step.depends_on {
317 if !unique_dependencies.insert(*dependency) {
318 return Err(format!(
319 "plan step {} lists dependency {} more than once",
320 step.index, dependency
321 ));
322 }
323 if *dependency >= self.steps.len() {
324 return Err(format!(
325 "plan step {} depends on missing step {}",
326 step.index, dependency
327 ));
328 }
329 graph.add_edge(
330 &plan_step_node_id(step.index),
331 &plan_step_node_id(*dependency),
332 ExecutionEdgeKind::DependsOn,
333 None,
334 )?;
335 }
336 }
337 Ok(graph)
338 }
339
340 pub fn advance_to_next_step(&mut self) -> bool {
342 if let Some(next_index) = self
343 .ready_step_indices()
344 .ok()
345 .and_then(|indices| indices.into_iter().next())
346 {
347 self.current_step = next_index;
348 if let Some(step) = self.steps.get_mut(self.current_step) {
349 step.status = StepStatus::InProgress;
350 step.started_at = Some(Utc::now());
351 }
352 self.updated_at = Utc::now();
353 true
354 } else if self.is_finished() {
355 self.status = self.resolved_status();
356 self.updated_at = Utc::now();
357 false
358 } else {
359 self.updated_at = Utc::now();
360 false
361 }
362 }
363
364 pub fn complete_current_step(&mut self, summary: Option<String>) {
366 if let Some(step) = self.current_step_mut() {
367 step.status = StepStatus::Completed;
368 step.completed_at = Some(Utc::now());
369 step.result_summary = summary;
370 }
371 self.updated_at = Utc::now();
372 }
373
374 pub fn fail_current_step(&mut self, error: String) {
376 if let Some(step) = self.current_step_mut() {
377 step.status = StepStatus::Failed;
378 step.completed_at = Some(Utc::now());
379 step.error = Some(error);
380 }
381 self.updated_at = Utc::now();
382 }
383
384 pub fn retry_current_step(&mut self) {
386 if let Some(step) = self.current_step_mut() {
387 step.retry_count += 1;
388 step.status = StepStatus::InProgress;
389 step.error = None;
390 step.started_at = Some(Utc::now());
391 step.completed_at = None;
392 }
393 self.updated_at = Utc::now();
394 }
395
396 pub fn unchecked_steps(&self) -> Vec<&PlanStep> {
398 self.steps
399 .iter()
400 .filter(|s| matches!(s.status, StepStatus::Pending | StepStatus::InProgress))
401 .collect()
402 }
403
404 pub fn has_background_steps(&self) -> bool {
406 self.steps
407 .iter()
408 .any(|step| step.status == StepStatus::Background)
409 }
410
411 pub fn link_background_job(&mut self, indices: &[usize], job_id: &str) -> bool {
417 let mut changed = false;
418 for &index in indices {
419 let Some(step) = self.steps.get_mut(index) else {
420 continue;
421 };
422 if matches!(step.status, StepStatus::Completed | StepStatus::Skipped) {
423 continue;
424 }
425 step.evidence = StepEvidence::Settled;
426 step.error = None;
427 step.not_done = None;
428 step.waited_jobs.clear();
430 step.status = StepStatus::Background;
431 step.started_at.get_or_insert_with(Utc::now);
432 step.completed_at = None;
433 if !step.background_jobs.iter().any(|job| job == job_id) {
434 step.background_jobs.push(job_id.to_string());
435 }
436 changed = true;
437 }
438 changed |= self.wait_on_runs_of_taken_units();
439 if changed {
440 if !self.status.is_incomplete() {
443 self.status = PlanStatus::InProgress;
444 }
445 self.updated_at = Utc::now();
446 }
447 changed
448 }
449
450 pub fn launch_steps(&self, named: &[usize], owner_units: &[usize]) -> Vec<usize> {
465 let mut steps: Vec<usize> = named
466 .iter()
467 .copied()
468 .filter(|index| *index < self.steps.len())
469 .collect();
470 let through_named: Vec<usize> = steps
471 .iter()
472 .flat_map(|index| self.steps[*index].owner_units.iter().copied())
473 .collect();
474 if !owner_units.is_empty() {
475 for step in &self.steps {
476 if !step.owner_units.is_empty()
477 && step
478 .owner_units
479 .iter()
480 .all(|unit| owner_units.contains(unit))
481 && !step
482 .owner_units
483 .iter()
484 .any(|unit| through_named.contains(unit))
485 && !steps.contains(&step.index)
486 {
487 steps.push(step.index);
488 }
489 }
490 }
491 steps.sort_unstable();
492 steps
493 }
494
495 fn wait_on_runs_of_taken_units(&mut self) -> bool {
502 let taken: Vec<(Vec<usize>, Vec<String>)> = self
503 .steps
504 .iter()
505 .filter(|step| {
506 step.status == StepStatus::Background && !step.background_jobs.is_empty()
507 })
508 .map(|step| (step.owner_units.clone(), step.background_jobs.clone()))
509 .collect();
510 let mut changed = false;
511 for step in &mut self.steps {
512 let open = matches!(step.status, StepStatus::Pending | StepStatus::InProgress)
513 || (step.status == StepStatus::Background && step.background_jobs.is_empty());
514 if !open || step.owner_units.is_empty() {
515 continue;
516 }
517 let covered = step
518 .owner_units
519 .iter()
520 .all(|unit| taken.iter().any(|(units, _)| units.contains(unit)));
521 if !covered {
522 continue;
523 }
524 for (units, jobs) in &taken {
525 if !units.iter().any(|unit| step.owner_units.contains(unit)) {
526 continue;
527 }
528 for job in jobs {
529 if !step.waited_jobs.contains(job) {
530 step.waited_jobs.push(job.clone());
531 changed = true;
532 }
533 }
534 }
535 if step.status != StepStatus::Background {
536 step.status = StepStatus::Background;
537 step.completed_at = None;
538 changed = true;
539 }
540 }
541 changed
542 }
543
544 pub fn steps_covered_by_running_jobs(
555 &self,
556 indices: &[usize],
557 running: impl Fn(&str) -> bool,
558 ) -> Vec<CoveredStep> {
559 let covered = |step: &PlanStep| -> Option<CoveredStep> {
560 if step.status != StepStatus::Background {
561 return None;
562 }
563 let jobs: Vec<String> = step
564 .background_jobs
565 .iter()
566 .filter(|job| running(job))
567 .cloned()
568 .collect();
569 (!jobs.is_empty()).then(|| CoveredStep {
570 index: step.index,
571 description: step.description.clone(),
572 jobs,
573 })
574 };
575 if !indices.is_empty() {
576 return indices
577 .iter()
578 .filter_map(|index| self.steps.get(*index))
579 .filter_map(covered)
580 .collect();
581 }
582 let open: Vec<&PlanStep> = self
583 .steps
584 .iter()
585 .filter(|step| {
586 !matches!(
587 step.status,
588 StepStatus::Completed
589 | StepStatus::Skipped
590 | StepStatus::Failed
591 | StepStatus::Deferred
592 )
593 })
594 .collect();
595 let all: Vec<CoveredStep> = open.iter().filter_map(|step| covered(step)).collect();
596 if open.is_empty() || all.len() < open.len() {
597 return Vec::new();
598 }
599 all
600 }
601
602 pub fn wait_on_background_jobs(&mut self, job_ids: &[String]) -> bool {
609 if job_ids.is_empty() {
610 return false;
611 }
612 let mut changed = false;
613 for step in &mut self.steps {
614 let open = matches!(step.status, StepStatus::Pending | StepStatus::InProgress)
625 || (step.status == StepStatus::Deferred && step.not_done.is_none())
626 || (step.status == StepStatus::Background && step.background_jobs.is_empty());
627 if !open {
628 continue;
629 }
630 step.status = StepStatus::Background;
631 step.completed_at = None;
632 for job in job_ids {
633 if !step.waited_jobs.contains(job) {
634 step.waited_jobs.push(job.clone());
635 }
636 }
637 changed = true;
638 }
639 if changed {
640 if self.is_finished() {
641 self.status = self.resolved_status();
642 }
643 self.updated_at = Utc::now();
644 }
645 changed
646 }
647
648 pub fn unmark_runless_background_steps(&mut self) -> bool {
654 let mut changed = false;
655 for step in &mut self.steps {
656 if step.status == StepStatus::Background && !step.has_background_jobs() {
657 step.status = StepStatus::Pending;
658 changed = true;
659 }
660 }
661 if changed {
662 self.sync_active_step();
663 self.updated_at = Utc::now();
664 }
665 changed
666 }
667
668 pub fn note_job_folders(&mut self, job_id: &str, folders: &[String]) -> bool {
672 let mut changed = false;
673 for step in &mut self.steps {
674 if !step.background_jobs.iter().any(|job| job == job_id) {
675 continue;
676 }
677 for folder in folders {
678 if !step.made_folders.contains(folder) {
679 step.made_folders.push(folder.clone());
680 changed = true;
681 }
682 }
683 }
684 if changed {
685 self.updated_at = Utc::now();
686 }
687 changed
688 }
689
690 pub fn settle_background_job(&mut self, job_id: &str, end: JobEnd) -> bool {
703 let now = Utc::now();
704 let mut changed = false;
705 let short = match end {
706 JobEnd::Succeeded => None,
707 JobEnd::Declined => Some(NotDoneReason::OwnerDeclined),
708 JobEnd::StoppedByOwner => Some(NotDoneReason::OwnerStopped),
709 JobEnd::Stopped => Some(NotDoneReason::HelperStopped),
710 JobEnd::Failed => Some(NotDoneReason::WaitedOnFailed),
711 };
712 let rank = |reason: NotDoneReason| match reason {
714 NotDoneReason::WaitedOnFailed => 3,
715 NotDoneReason::HelperStopped => 2,
716 _ => 1,
717 };
718 for step in &mut self.steps {
719 let took_on = step.background_jobs.iter().any(|job| job == job_id);
720 let waited = step.waited_jobs.iter().any(|job| job == job_id);
721 if step.status != StepStatus::Background || !(took_on || waited) {
722 continue;
723 }
724 changed = true;
725 step.background_jobs.retain(|job| job != job_id);
726 step.waited_jobs.retain(|job| job != job_id);
727 if !took_on && !step.background_jobs.is_empty() {
731 continue;
732 }
733 if let Some(short) = short {
734 step.not_done = Some(match step.not_done {
735 Some(earlier) if rank(earlier) >= rank(short) => earlier,
736 _ => short,
737 });
738 }
739 if !step.background_jobs.is_empty() || (!took_on && !step.waited_jobs.is_empty()) {
740 continue;
741 }
742 step.waited_jobs.clear();
746 step.completed_at = Some(now);
747 match step.not_done {
748 None => {
749 step.status = StepStatus::Completed;
750 step.evidence = StepEvidence::Settled;
751 }
752 Some(NotDoneReason::WaitedOnFailed) if took_on => {
753 step.status = StepStatus::Failed;
754 step.not_done = None;
755 }
756 Some(_) => step.status = StepStatus::Deferred,
757 }
758 }
759 if changed {
760 if self.is_finished() {
761 self.status = self.resolved_status();
762 } else {
763 self.sync_active_step();
764 }
765 self.updated_at = now;
766 }
767 changed
768 }
769
770 pub fn settle_open_steps(&mut self) -> bool {
789 if self
790 .steps
791 .iter()
792 .any(|step| step.status == StepStatus::Background && step.has_background_jobs())
793 {
794 return false;
795 }
796 let now = Utc::now();
797 let mut changed = false;
798 for step in &mut self.steps {
799 if matches!(
800 step.status,
801 StepStatus::Pending | StepStatus::InProgress | StepStatus::Background
802 ) {
803 step.status = StepStatus::Deferred;
804 step.waited_jobs.clear();
805 step.background_jobs.clear();
806 step.not_done = Some(NotDoneReason::LeftOpen);
807 step.completed_at = Some(now);
808 changed = true;
809 }
810 }
811 let resolved = self.resolved_status();
815 if changed || self.status != resolved {
816 self.status = resolved;
817 self.updated_at = now;
818 changed = true;
819 }
820 changed
821 }
822
823 pub fn mark_not_attempted(&mut self, indices: &std::collections::BTreeSet<usize>) -> bool {
829 let now = Utc::now();
830 let mut changed = false;
831 for &index in indices {
832 let Some(step) = self.steps.get_mut(index) else {
833 continue;
834 };
835 if matches!(step.status, StepStatus::Completed | StepStatus::Skipped)
836 || (step.status == StepStatus::Background && !step.background_jobs.is_empty())
837 {
838 continue;
839 }
840 step.status = StepStatus::Deferred;
841 step.waited_jobs.clear();
842 step.background_jobs.clear();
843 step.not_done = Some(NotDoneReason::NotAttempted);
844 step.completed_at = Some(now);
845 changed = true;
846 }
847 if changed {
848 if self.is_finished() {
849 self.status = self.resolved_status();
850 } else {
851 self.sync_active_step();
852 }
853 self.updated_at = now;
854 }
855 changed
856 }
857
858 pub fn hold_back_unfinished_steps(&mut self, reason: NotDoneReason) -> bool {
863 let mut changed = false;
864 for step in &mut self.steps {
865 if matches!(step.status, StepStatus::Failed | StepStatus::Deferred)
866 && step.not_done.is_none()
867 {
868 step.status = StepStatus::Deferred;
869 step.not_done = Some(reason);
870 step.completed_at.get_or_insert_with(Utc::now);
871 changed = true;
872 }
873 }
874 if changed {
875 if self.is_finished() {
876 self.status = self.resolved_status();
877 }
878 self.updated_at = Utc::now();
879 }
880 changed
881 }
882
883 fn shared_hold_reason(&self) -> Option<NotDoneReason> {
886 let mut reason = None;
887 for step in &self.steps {
888 match (step.status, step.not_done) {
889 (StepStatus::Completed | StepStatus::Skipped, _) => {}
890 (StepStatus::Deferred, Some(found)) if reason.is_none_or(|r| r == found) => {
891 reason = Some(found);
892 }
893 _ => return None,
894 }
895 }
896 reason
897 }
898
899 pub fn card(&self) -> aidaemon_core::card::PlanCard {
902 aidaemon_core::card::PlanCard {
903 text: self.render_compact_checklist(),
904 steps: self.steps.len(),
905 done: self.completed_steps(),
906 finished_steps: self
907 .steps
908 .iter()
909 .filter(|step| matches!(step.status, StepStatus::Completed | StepStatus::Skipped))
910 .map(|step| step.index)
911 .collect(),
912 settled: !self
913 .steps
914 .iter()
915 .any(|step| matches!(step.status, StepStatus::Pending | StepStatus::InProgress)),
916 }
917 }
918
919 pub fn render_compact_checklist(&self) -> String {
930 let total = self.steps.len();
931 let unverified = self.unverified_steps();
932 let in_background = self.has_background_steps();
933 let finished = !matches!(
934 self.status,
935 PlanStatus::Planning | PlanStatus::InProgress | PlanStatus::Paused
936 );
937 let done = self.completed_steps();
940 let said_note = if unverified > 0 && finished && !in_background {
941 format!("; I couldn't verify {unverified}")
942 } else {
943 String::new()
944 };
945 let not_needed = self
946 .steps
947 .iter()
948 .filter(|step| step.status == StepStatus::Skipped)
949 .count();
950 let held = self.shared_hold_reason();
951 if total == 1 && (self.status != PlanStatus::PartiallyCompleted || held.is_some()) {
952 let step = &self.steps[0];
953 let mark = match (self.status, step.status) {
954 (_, StepStatus::Completed) if step.unverified() => "☑️",
955 (_, StepStatus::Completed) => "✅",
956 (_, StepStatus::Skipped) => "✅",
957 _ if held.is_some() => "⏭️",
958 (PlanStatus::Failed, _) | (_, StepStatus::Failed) => "❌",
959 (PlanStatus::Abandoned, _) => "⏹️",
960 (PlanStatus::Paused, _) => "⏸️",
961 _ => "⏳",
962 };
963 let described = step.described();
964 return match (step.status, held) {
965 (StepStatus::Completed, _) if step.unverified() => {
966 format!("{mark} {described} ({UNVERIFIED})")
967 }
968 (StepStatus::Failed, _) if step.helper_not_started() => {
969 format!("{mark} {described} ({HELPER_NOT_STARTED})")
970 }
971 (StepStatus::Background, _) => {
972 format!("{mark} {described} (running in the background)")
973 }
974 (StepStatus::Skipped, _) => format!("{mark} {described} (not needed)"),
975 (_, Some(reason)) => {
976 format!("{mark} {described} (not done: {})", reason.plain())
977 }
978 _ => format!("{mark} {described}"),
979 };
980 }
981 let header = match self.status {
982 _ if in_background => {
985 format!("⏳ Continuing in the background · {done} of {total} done{said_note}")
986 }
987 _ if finished && held.is_some() => {
990 let reason = held.map(NotDoneReason::plain).unwrap_or_default();
991 format!("⏭️ Not done: {reason} · {done} of {total} done{said_note}")
992 }
993 PlanStatus::Planning => "🧭 Planning…".to_string(),
994 PlanStatus::InProgress => {
995 let position = self.current_step.saturating_add(1).min(total);
996 format!("⚙️ Working · step {position} of {total}")
997 }
998 PlanStatus::Paused => format!("⏸️ Paused · {done} of {total} done{said_note}"),
999 PlanStatus::Completed if unverified > 0 => {
1002 let needed_note = if not_needed > 0 {
1003 format!(", {not_needed} not needed")
1004 } else {
1005 String::new()
1006 };
1007 format!("☑️ Finished · {done} of {total} done{said_note}{needed_note}")
1008 }
1009 PlanStatus::Completed if not_needed > 0 => {
1012 format!("✅ Done · {done} done, {not_needed} not needed")
1013 }
1014 PlanStatus::Completed => format!("✅ Done · {done} of {total} steps"),
1015 PlanStatus::PartiallyCompleted => {
1016 format!("⚠️ Stopped short · {done} of {total} done{said_note}")
1017 }
1018 PlanStatus::Failed => format!("❌ Stopped · {done} of {total} done{said_note}"),
1019 PlanStatus::Abandoned => {
1020 format!("⏹️ Cancelled · {done} of {total} done{said_note}")
1021 }
1022 };
1023 let mut out = header;
1024 for step in &self.steps {
1025 let line = match (step.status, step.not_done) {
1026 (StepStatus::Completed, _) if step.unverified() => {
1027 format!("☑️ {} ({UNVERIFIED})", step.described())
1028 }
1029 (StepStatus::Completed, _) => format!("✅ {}", step.described()),
1030 (StepStatus::Failed, _) if step.helper_not_started() => {
1033 format!("⚠️ {} (didn't run)", step.described())
1034 }
1035 (StepStatus::InProgress, _) => format!("▶️ {}", step.described()),
1036 (StepStatus::Background, _) => {
1037 format!("⏳ {} (running in the background)", step.described())
1038 }
1039 (StepStatus::Deferred, Some(reason)) => {
1040 format!("⏭️ {} (not done: {})", step.described(), reason.plain())
1041 }
1042 (StepStatus::Deferred, None) => format!("⏭️ {} (not done)", step.described()),
1045 (StepStatus::Failed, _) => format!("⚠️ {} (couldn't be done)", step.described()),
1046 (StepStatus::Skipped, _) => format!("➖ {} (not needed)", step.described()),
1047 (StepStatus::Pending, _) => format!("○ {}", step.described()),
1048 };
1049 out.push_str("\n\n");
1052 out.push_str(&line);
1053 }
1054 if self.status == PlanStatus::PartiallyCompleted && !in_background && held.is_none() {
1055 out.push_str("\n\nThe reply below says what was left undone and why.");
1056 }
1057 if self
1061 .steps
1062 .iter()
1063 .any(|step| step.status == StepStatus::Failed && step.helper_not_started())
1064 {
1065 out.push_str("\n\nDidn't run: its helper didn't start.");
1066 }
1067 out
1068 }
1069
1070 pub fn render_recap(&self) -> String {
1072 let mut out = String::new();
1073 for step in &self.steps {
1074 let mark = match step.status {
1075 StepStatus::Completed => "✅",
1076 StepStatus::Deferred => "⏭️ (not done)",
1077 StepStatus::Failed => "⚠️ (failed)",
1078 StepStatus::Background => "⏳ (running in the background)",
1079 _ => "☐ (not done)",
1080 };
1081 out.push_str(&format!("{} {}\n", mark, step.description));
1082 }
1083 out.trim_end().to_string()
1084 }
1085
1086 pub fn format_for_prompt(&self) -> String {
1088 let mut lines = vec![
1089 "## Incomplete Task Plan".to_string(),
1090 format!("**Task:** {}", self.description),
1091 format!(
1092 "**Status:** {} ({}/{} steps complete)",
1093 self.status.as_str(),
1094 self.completed_steps(),
1095 self.steps.len()
1096 ),
1097 "**Steps:**".to_string(),
1098 ];
1099
1100 for step in &self.steps {
1101 let marker = match step.status {
1102 StepStatus::Completed => "[x]",
1103 StepStatus::InProgress => "[>]",
1104 StepStatus::Failed => "[!]",
1105 StepStatus::Skipped => "[-]",
1106 StepStatus::Deferred => "[~]",
1107 StepStatus::Background => "[bg]",
1108 StepStatus::Pending => "[ ]",
1109 };
1110 let mut line = format!(" {} {}. {}", marker, step.index + 1, step.description);
1111 if let Some(ref error) = step.error {
1112 line.push_str(&format!(" (Error: {})", truncate_str(error, 50)));
1113 }
1114 lines.push(line);
1115 }
1116
1117 lines.push(String::new());
1118 lines.push(
1119 "If the user wants to continue this task, resume from the current step.".to_string(),
1120 );
1121 lines.push(
1122 "If the user provides NEW REQUIREMENTS or CHANGES (e.g., 'use X instead', 'also add Y'), \
1123 use plan_manager with action='revise' to update the remaining steps accordingly."
1124 .to_string(),
1125 );
1126 lines.push(
1127 "If they want to start over or do something else, use plan_manager to abandon it first."
1128 .to_string(),
1129 );
1130
1131 lines.join("\n")
1132 }
1133}
1134
1135#[derive(Debug, Clone, PartialEq, Eq)]
1138pub struct CoveredStep {
1139 pub index: usize,
1140 pub description: String,
1141 pub jobs: Vec<String>,
1143}
1144
1145#[derive(Debug, Clone, Serialize, Deserialize)]
1147pub struct PlanStep {
1148 pub index: usize,
1150
1151 pub description: String,
1153
1154 #[serde(default)]
1157 pub depends_on: Vec<usize>,
1158
1159 #[serde(default)]
1162 pub required_mutation_effects: ToolMutationEffects,
1163 #[serde(default)]
1164 pub requires_observation: bool,
1165 #[serde(default)]
1167 pub expected_targets: Vec<String>,
1168 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1172 pub owner_units: Vec<usize>,
1173 #[serde(default)]
1175 pub evidence_receipt_ids: Vec<String>,
1176
1177 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1182 pub background_jobs: Vec<String>,
1183
1184 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1191 pub waited_jobs: Vec<String>,
1192
1193 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1200 pub made_folders: Vec<String>,
1201
1202 #[serde(default, skip_serializing_if = "Option::is_none")]
1206 pub not_done: Option<NotDoneReason>,
1207
1208 #[serde(default, skip_serializing_if = "StepEvidence::is_settled")]
1213 pub evidence: StepEvidence,
1214
1215 pub status: StepStatus,
1217
1218 pub tool_call_ids: Vec<String>,
1220
1221 pub result_summary: Option<String>,
1223
1224 pub error: Option<String>,
1226
1227 pub retry_count: u32,
1229
1230 pub started_at: Option<DateTime<Utc>>,
1231 pub completed_at: Option<DateTime<Utc>>,
1232}
1233
1234#[derive(Debug, Clone)]
1235pub struct ChecklistItem {
1236 pub description: String,
1237 pub status: StepStatus,
1238 pub depends_on: Vec<usize>,
1239 pub required_mutation_effects: ToolMutationEffects,
1240 pub requires_observation: bool,
1241 pub expected_targets: Vec<String>,
1242 pub owner_units: Vec<usize>,
1244}
1245
1246fn plan_step_node_id(index: usize) -> String {
1247 format!("plan-step:{index}")
1248}
1249
1250impl PlanStep {
1251 pub fn described(&self) -> String {
1254 let unnamed: Vec<&str> = self
1255 .made_folders
1256 .iter()
1257 .map(|folder| {
1258 std::path::Path::new(folder)
1259 .file_name()
1260 .and_then(|name| name.to_str())
1261 .unwrap_or(folder)
1262 })
1263 .filter(|name| !self.description.contains(name))
1264 .collect();
1265 match unnamed.as_slice() {
1266 [] => self.description.clone(),
1267 [one] => format!("{} (made {one})", self.description),
1268 many => format!("{} (made {})", self.description, many.join(", ")),
1269 }
1270 }
1271
1272 pub fn unverified(&self) -> bool {
1277 self.status == StepStatus::Completed
1278 && self.evidence == StepEvidence::ModelSaid
1279 && !self.required_mutation_effects.is_empty()
1280 }
1281
1282 pub fn has_background_jobs(&self) -> bool {
1285 !self.background_jobs.is_empty() || !self.waited_jobs.is_empty()
1286 }
1287
1288 pub fn helper_not_started(&self) -> bool {
1290 self.evidence == StepEvidence::HelperNotStarted
1291 }
1292
1293 pub fn duration_secs(&self) -> Option<u64> {
1295 match (self.started_at, self.completed_at) {
1296 (Some(start), Some(end)) => Some((end - start).num_seconds().max(0) as u64),
1297 _ => None,
1298 }
1299 }
1300}
1301
1302#[derive(
1304 Debug,
1305 Clone,
1306 Copy,
1307 PartialEq,
1308 Eq,
1309 Serialize,
1310 Deserialize,
1311 strum::IntoStaticStr,
1312 strum::EnumString,
1313)]
1314#[serde(rename_all = "snake_case")]
1315#[strum(serialize_all = "snake_case")]
1316pub enum PlanStatus {
1317 Planning,
1319 InProgress,
1321 Paused,
1323 Completed,
1325 PartiallyCompleted,
1327 Failed,
1329 Abandoned,
1331}
1332
1333impl PlanStatus {
1334 pub fn as_str(&self) -> &'static str {
1335 (*self).into()
1336 }
1337
1338 #[allow(clippy::should_implement_trait)]
1339 pub fn from_str(s: &str) -> Option<Self> {
1340 s.parse().ok()
1341 }
1342
1343 pub fn is_incomplete(&self) -> bool {
1345 matches!(
1346 self,
1347 PlanStatus::Planning | PlanStatus::InProgress | PlanStatus::Paused
1348 )
1349 }
1350}
1351
1352#[derive(
1354 Debug,
1355 Clone,
1356 Copy,
1357 PartialEq,
1358 Eq,
1359 Serialize,
1360 Deserialize,
1361 strum::IntoStaticStr,
1362 strum::EnumString,
1363)]
1364#[serde(rename_all = "snake_case")]
1365#[strum(serialize_all = "snake_case")]
1366pub enum StepStatus {
1367 Pending,
1369 InProgress,
1371 Completed,
1373 Failed,
1375 Skipped,
1377 Deferred,
1379 Background,
1382}
1383
1384impl StepStatus {
1385 pub fn as_str(&self) -> &'static str {
1386 (*self).into()
1387 }
1388
1389 #[allow(clippy::should_implement_trait)]
1390 pub fn from_str(s: &str) -> Option<Self> {
1391 s.parse().ok()
1392 }
1393}
1394
1395const UNVERIFIED: &str = "I couldn't verify this one";
1397const HELPER_NOT_STARTED: &str = "didn't run: its helper didn't start";
1399
1400#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1402#[serde(rename_all = "snake_case")]
1403pub enum NotDoneReason {
1404 ChangesOff,
1407 HelperStopped,
1410 LeftOpen,
1412 WaitedOnFailed,
1414 OwnerDeclined,
1418 OwnerStopped,
1421 NotAttempted,
1424}
1425
1426impl NotDoneReason {
1427 fn plain(self) -> &'static str {
1428 match self {
1429 Self::ChangesOff => "read-only is on",
1430 Self::HelperStopped => "its helper stopped before it finished",
1431 Self::LeftOpen => "nothing was left working on it",
1432 Self::WaitedOnFailed => "the work it waited on failed",
1433 Self::OwnerDeclined => "you declined a step its helper asked to take",
1434 Self::OwnerStopped => "you stopped its helper",
1435 Self::NotAttempted => "not attempted",
1436 }
1437 }
1438}
1439
1440#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1443pub enum JobEnd {
1444 Succeeded,
1445 Stopped,
1446 Declined,
1448 StoppedByOwner,
1450 Failed,
1451}
1452
1453pub use aidaemon_channels::live_status::is_completed_checklist;
1456
1457#[cfg(test)]
1458mod tests {
1459 use super::*;
1460
1461 fn two_sites() -> TaskPlan {
1462 TaskPlan::new(
1463 "session_123",
1464 "Install two sites",
1465 "Two sites",
1466 vec![
1467 "Install WordPress".to_string(),
1468 "Install Drupal".to_string(),
1469 ],
1470 "low",
1471 )
1472 }
1473
1474 #[test]
1478 fn a_step_a_running_helper_does_is_covered_until_it_ends() {
1479 let mut plan = two_sites();
1480 plan.link_background_job(&[0], "job-wp");
1481 plan.link_background_job(&[1], "job-drupal");
1482 let running = |job: &str| job == "job-wp" || job == "job-drupal";
1483
1484 let covered = plan.steps_covered_by_running_jobs(&[0], running);
1485 assert_eq!(
1486 covered,
1487 vec![CoveredStep {
1488 index: 0,
1489 description: "Install WordPress".to_string(),
1490 jobs: vec!["job-wp".to_string()],
1491 }]
1492 );
1493 assert_eq!(plan.steps_covered_by_running_jobs(&[], running).len(), 2);
1495
1496 plan.settle_background_job("job-wp", JobEnd::Stopped);
1498 let only_drupal = |job: &str| job == "job-drupal";
1499 assert!(
1500 plan.steps_covered_by_running_jobs(&[0], only_drupal)
1501 .is_empty()
1502 );
1503 let unnamed = plan.steps_covered_by_running_jobs(&[], only_drupal);
1505 assert_eq!(
1506 unnamed.iter().map(|step| step.index).collect::<Vec<_>>(),
1507 [1]
1508 );
1509 }
1510
1511 #[test]
1514 fn a_step_whose_helper_is_gone_is_not_covered() {
1515 let mut plan = two_sites();
1516 plan.link_background_job(&[0, 1], "job-lost");
1517 assert!(
1518 plan.steps_covered_by_running_jobs(&[0], |_| false)
1519 .is_empty()
1520 );
1521 assert!(
1522 plan.steps_covered_by_running_jobs(&[], |_| false)
1523 .is_empty()
1524 );
1525 }
1526
1527 #[test]
1530 fn an_unnamed_launch_with_a_free_step_is_not_covered() {
1531 let mut plan = two_sites();
1532 plan.link_background_job(&[0], "job-wp");
1533 assert!(
1534 plan.steps_covered_by_running_jobs(&[], |job| job == "job-wp")
1535 .is_empty()
1536 );
1537 assert_eq!(
1539 plan.steps_covered_by_running_jobs(&[0, 1], |job| job == "job-wp")
1540 .len(),
1541 1
1542 );
1543 }
1544
1545 #[test]
1550 fn steps_waiting_on_unnamed_launches_are_not_covered() {
1551 let mut plan = two_sites();
1552 plan.wait_on_background_jobs(&["job-a".to_string(), "job-b".to_string()]);
1553 assert!(plan.steps_covered_by_running_jobs(&[], |_| true).is_empty());
1554 assert!(
1555 plan.steps_covered_by_running_jobs(&[0], |_| true)
1556 .is_empty()
1557 );
1558 }
1559
1560 #[test]
1564 fn a_retried_step_settles_from_its_latest_run() {
1565 for first_end in [JobEnd::Stopped, JobEnd::Failed] {
1566 let mut plan = TaskPlan::new(
1567 "session_123",
1568 "Install two sites",
1569 "Two sites",
1570 vec![
1571 "Install WordPress".to_string(),
1572 "Install Drupal".to_string(),
1573 ],
1574 "low",
1575 );
1576 assert!(plan.link_background_job(&[1], "job-1"));
1577 assert!(plan.settle_background_job("job-1", first_end));
1578 assert_ne!(plan.steps[1].status, StepStatus::Completed);
1579 assert!(plan.link_background_job(&[1], "job-2"), "{first_end:?}");
1580 assert_eq!(plan.steps[1].status, StepStatus::Background);
1581 assert_eq!(plan.steps[1].not_done, None);
1582 assert!(plan.settle_background_job("job-2", JobEnd::Succeeded));
1583 assert_eq!(plan.steps[1].status, StepStatus::Completed);
1584 }
1585 }
1586
1587 #[test]
1588 fn test_create_plan() {
1589 let plan = TaskPlan::new(
1590 "session_123",
1591 "Deploy the app to production",
1592 "Production deployment",
1593 vec![
1594 "Run tests".to_string(),
1595 "Build container".to_string(),
1596 "Deploy".to_string(),
1597 ],
1598 "high_stakes",
1599 );
1600
1601 assert_eq!(plan.steps.len(), 3);
1602 assert_eq!(plan.current_step, 0);
1603 assert_eq!(plan.status, PlanStatus::InProgress);
1604 assert_eq!(plan.steps[0].status, StepStatus::InProgress);
1605 assert_eq!(plan.steps[1].status, StepStatus::Pending);
1606 assert_eq!(plan.steps[2].status, StepStatus::Pending);
1607 }
1608
1609 #[test]
1610 fn test_advance_steps() {
1611 let mut plan = TaskPlan::new(
1612 "session_123",
1613 "test",
1614 "Test task",
1615 vec!["Step 1".to_string(), "Step 2".to_string()],
1616 "test",
1617 );
1618
1619 plan.complete_current_step(Some("Done".to_string()));
1620 assert_eq!(plan.steps[0].status, StepStatus::Completed);
1621
1622 assert!(plan.advance_to_next_step());
1623 assert_eq!(plan.current_step, 1);
1624 assert_eq!(plan.steps[1].status, StepStatus::InProgress);
1625
1626 plan.complete_current_step(None);
1627 assert!(!plan.advance_to_next_step());
1628 assert_eq!(plan.status, PlanStatus::Completed);
1629 }
1630
1631 #[test]
1632 fn sync_active_step_promotes_the_next_pending_item() {
1633 let mut plan = TaskPlan::new(
1634 "session_123",
1635 "test",
1636 "Test task",
1637 vec!["First".to_string(), "Second".to_string()],
1638 "test",
1639 );
1640 plan.steps[0].status = StepStatus::Completed;
1641 plan.steps[1].status = StepStatus::Pending;
1642 plan.current_step = 0;
1643
1644 plan.sync_active_step();
1645
1646 assert_eq!(plan.current_step, 1);
1647 assert_eq!(plan.steps[1].status, StepStatus::InProgress);
1648 }
1649
1650 #[test]
1651 fn dependency_graph_supports_parallel_branches_and_a_join() {
1652 let mut plan = TaskPlan::new(
1653 "session_123",
1654 "test",
1655 "Graph task",
1656 vec!["Left".into(), "Right".into(), "Join".into()],
1657 "test",
1658 );
1659 for step in &mut plan.steps {
1660 step.status = StepStatus::Pending;
1661 }
1662 plan.steps[0].depends_on.clear();
1663 plan.steps[1].depends_on.clear();
1664 plan.steps[2].depends_on = vec![0, 1];
1665
1666 assert_eq!(plan.ready_step_indices().unwrap(), vec![0, 1]);
1667 plan.steps[0].status = StepStatus::Completed;
1668 assert_eq!(plan.ready_step_indices().unwrap(), vec![1]);
1669 plan.steps[1].status = StepStatus::Completed;
1670 assert_eq!(plan.ready_step_indices().unwrap(), vec![2]);
1671 }
1672
1673 #[test]
1677 fn open_steps_settle_once_nothing_runs() {
1678 let mut plan = TaskPlan::new(
1679 "session_123",
1680 "test",
1681 "Two installs",
1682 vec!["Install one".into(), "Install two".into()],
1683 "test",
1684 );
1685 for step in &mut plan.steps {
1686 step.status = StepStatus::Pending;
1687 }
1688 assert!(plan.wait_on_background_jobs(&["job-1".to_string()]));
1689 assert!(plan.wait_on_background_jobs(&["job-2".to_string()]));
1690 assert_eq!(plan.steps[0].waited_jobs, vec!["job-1", "job-2"]);
1691 plan.settle_background_job("job-1", JobEnd::Succeeded);
1692 assert_eq!(plan.steps[0].status, StepStatus::Background);
1693 plan.steps.push(PlanStep {
1694 status: StepStatus::InProgress,
1695 description: "Report each time".into(),
1696 background_jobs: Vec::new(),
1697 waited_jobs: Vec::new(),
1698 ..plan.steps[0].clone()
1699 });
1700 plan.settle_background_job("job-2", JobEnd::Succeeded);
1701 assert!(!plan.is_finished());
1702 assert!(plan.settle_open_steps());
1703 assert!(plan.is_finished());
1704 assert_eq!(plan.steps[2].not_done, Some(NotDoneReason::LeftOpen));
1705 assert!(
1706 plan.render_compact_checklist()
1707 .contains("nothing was left working on it")
1708 );
1709 }
1710
1711 #[test]
1716 fn a_step_a_launch_took_on_is_never_left_open() {
1717 let mut plan = TaskPlan::new(
1718 "session_123",
1719 "test",
1720 "Two screenshots",
1721 vec![
1722 "Drupal homepage screenshot".into(),
1723 "WordPress homepage screenshot".into(),
1724 "Report each time".into(),
1725 ],
1726 "test",
1727 );
1728 assert!(plan.link_background_job(&[0], "job-drupal"));
1729 assert!(plan.link_background_job(&[1], "job-wordpress"));
1730 assert!(plan.settle_background_job("job-drupal", JobEnd::Succeeded));
1731 assert!(!plan.settle_open_steps());
1732 assert_eq!(plan.steps[1].status, StepStatus::Background);
1733 assert_eq!(plan.steps[2].not_done, None);
1734 assert_eq!(plan.steps[1].not_done, None);
1735 assert!(!plan.is_finished());
1736 let card = plan.render_compact_checklist();
1737 assert!(!card.contains("Stopped short"), "{card}");
1738 assert!(!card.contains("nothing was left working on it"), "{card}");
1739 assert!(plan.settle_background_job("job-wordpress", JobEnd::Succeeded));
1740 assert_eq!(plan.steps[1].status, StepStatus::Completed);
1741 }
1742
1743 #[test]
1744 fn dependency_graph_rejects_cycles() {
1745 let mut plan = TaskPlan::new(
1746 "session_123",
1747 "test",
1748 "Cyclic task",
1749 vec!["One".into(), "Two".into()],
1750 "test",
1751 );
1752 plan.steps[0].depends_on = vec![1];
1753 plan.steps[1].depends_on = vec![0];
1754
1755 assert!(plan.validate_graph().unwrap_err().contains("cycle"));
1756 }
1757
1758 #[test]
1759 fn test_format_for_prompt() {
1760 let mut plan = TaskPlan::new(
1761 "session_123",
1762 "Deploy",
1763 "Deploy to production",
1764 vec![
1765 "Run tests".to_string(),
1766 "Build".to_string(),
1767 "Deploy".to_string(),
1768 ],
1769 "test",
1770 );
1771
1772 plan.complete_current_step(Some("Tests passed".to_string()));
1773 plan.advance_to_next_step();
1774
1775 let formatted = plan.format_for_prompt();
1776 assert!(formatted.contains("Incomplete Task Plan"));
1777 assert!(formatted.contains("[x] 1. Run tests"));
1778 assert!(formatted.contains("[>] 2. Build"));
1779 assert!(formatted.contains("[ ] 3. Deploy"));
1780 }
1781
1782 #[test]
1783 fn test_deferred_status_round_trip() {
1784 assert_eq!(StepStatus::Deferred.as_str(), "deferred");
1785 assert_eq!(StepStatus::from_str("deferred"), Some(StepStatus::Deferred));
1786 }
1787
1788 #[test]
1789 fn test_unchecked_steps_excludes_completed_and_deferred() {
1790 let mut plan = TaskPlan::new(
1791 "s",
1792 "t",
1793 "d",
1794 vec!["a".into(), "b".into(), "c".into()],
1795 "track_requirements",
1796 );
1797 plan.steps[0].status = StepStatus::Completed;
1798 plan.steps[1].status = StepStatus::Deferred;
1799 plan.steps[2].status = StepStatus::Pending;
1800 let unchecked = plan.unchecked_steps();
1801 assert_eq!(unchecked.len(), 1);
1802 assert_eq!(unchecked[0].description, "c");
1803 }
1804
1805 #[test]
1806 fn test_render_compact_checklist_and_recap() {
1807 let mut plan = TaskPlan::new(
1808 "s",
1809 "t",
1810 "d",
1811 vec!["create script".into(), "send the file".into()],
1812 "track_requirements",
1813 );
1814 plan.steps[0].status = StepStatus::Completed;
1815 plan.steps[1].status = StepStatus::InProgress;
1816 plan.current_step = 1;
1817 let checklist = plan.render_compact_checklist();
1818 assert_eq!(
1819 checklist,
1820 "⚙️ Working · step 2 of 2\n\n✅ create script\n\n▶️ send the file"
1821 );
1822 assert!(!is_completed_checklist(&checklist));
1823 assert!(checklist.contains("create script"));
1824 assert!(checklist.contains("send the file"));
1825 let recap = plan.render_recap();
1826 assert!(recap.contains("create script"));
1827 assert!(recap.contains("send the file"));
1828 assert!(recap.contains("not done"));
1829 }
1830
1831 #[test]
1832 fn completed_plan_does_not_announce_durable_task_completion() {
1833 let mut plan = TaskPlan::new(
1834 "synthetic-session",
1835 "synthetic-task",
1836 "description",
1837 vec!["observe result".into()],
1838 "track_requirements",
1839 );
1840 plan.steps[0].status = StepStatus::Completed;
1841 plan.status = PlanStatus::Completed;
1842
1843 let checklist = plan.render_compact_checklist();
1844 assert_eq!(checklist, "✅ observe result");
1846 assert!(is_completed_checklist(&checklist));
1847 assert!(!checklist.contains("Task complete"));
1848
1849 let mut plan = TaskPlan::new(
1850 "synthetic-session",
1851 "synthetic-task",
1852 "description",
1853 vec!["first".into(), "second".into()],
1854 "track_requirements",
1855 );
1856 for step in &mut plan.steps {
1857 step.status = StepStatus::Completed;
1858 }
1859 plan.status = PlanStatus::Completed;
1860 let checklist = plan.render_compact_checklist();
1861 assert_eq!(checklist, "✅ Done · 2 of 2 steps\n\n✅ first\n\n✅ second");
1862 assert!(is_completed_checklist(&checklist));
1863 assert!(!checklist.contains("Finalizing"));
1864 }
1865
1866 #[test]
1870 fn handed_off_steps_render_as_running_in_the_background() {
1871 let mut plan = TaskPlan::new(
1872 "synthetic-session",
1873 "synthetic-task",
1874 "description",
1875 vec![
1876 "inspect".into(),
1877 "first setup".into(),
1878 "second setup".into(),
1879 "report both".into(),
1880 ],
1881 "track_requirements",
1882 );
1883 plan.steps[0].status = StepStatus::Completed;
1884 assert!(plan.link_background_job(&[1, 3], "job-a"));
1885 assert!(plan.link_background_job(&[2, 3], "job-b"));
1886 plan.status = PlanStatus::PartiallyCompleted;
1888
1889 let card = plan.render_compact_checklist();
1890 assert_eq!(
1891 card,
1892 "⏳ Continuing in the background · 1 of 4 done\n\n✅ inspect\n\n\
1893 ⏳ first setup (running in the background)\n\n\
1894 ⏳ second setup (running in the background)\n\n\
1895 ⏳ report both (running in the background)"
1896 );
1897 assert!(!is_completed_checklist(&card));
1898
1899 assert!(plan.settle_background_job("job-a", JobEnd::Succeeded));
1901 assert_eq!(plan.steps[1].status, StepStatus::Completed);
1902 assert_eq!(plan.steps[3].status, StepStatus::Background);
1903 assert!(
1904 plan.render_compact_checklist()
1905 .starts_with("⏳ Continuing in the background · 2 of 4 done")
1906 );
1907
1908 assert!(plan.settle_background_job("job-b", JobEnd::Failed));
1910 assert_eq!(plan.steps[2].status, StepStatus::Failed);
1911 assert_eq!(plan.steps[3].status, StepStatus::Failed);
1912 assert_eq!(plan.status, PlanStatus::Failed);
1913 assert!(
1914 plan.render_compact_checklist()
1915 .starts_with("❌ Stopped · 2 of 4 done")
1916 );
1917 assert!(!plan.settle_background_job("job-c", JobEnd::Succeeded));
1919 }
1920
1921 #[test]
1925 fn open_steps_wait_on_the_turns_background_jobs_and_settle_from_their_ends() {
1926 let mut plan = TaskPlan::new(
1927 "synthetic-session",
1928 "synthetic-task",
1929 "description",
1930 vec![
1931 "check tools".into(),
1932 "install site a".into(),
1933 "install site b".into(),
1934 ],
1935 "track_requirements",
1936 );
1937 plan.steps[0].status = StepStatus::Completed;
1938 plan.steps[1].status = StepStatus::Deferred;
1939 plan.steps[2].status = StepStatus::Deferred;
1940 plan.status = PlanStatus::PartiallyCompleted;
1941 assert!(
1942 plan.render_compact_checklist()
1943 .starts_with("⚠️ Stopped short")
1944 );
1945
1946 let jobs = vec!["job-a".to_string(), "job-b".to_string()];
1947 assert!(plan.wait_on_background_jobs(&jobs));
1948 let card = plan.render_compact_checklist();
1949 assert!(
1950 card.starts_with("⏳ Continuing in the background · 1 of 3 done"),
1951 "{card}"
1952 );
1953 assert!(
1954 !card.contains("Stopped short") && !card.contains("not done"),
1955 "{card}"
1956 );
1957
1958 assert!(plan.settle_background_job("job-a", JobEnd::Succeeded));
1959 assert!(
1960 plan.render_compact_checklist()
1961 .starts_with("⏳ Continuing in the background")
1962 );
1963 assert!(plan.settle_background_job("job-b", JobEnd::Succeeded));
1964 assert_eq!(plan.steps[1].status, StepStatus::Completed);
1965 assert_eq!(plan.steps[2].status, StepStatus::Completed);
1966 assert_eq!(plan.status, PlanStatus::Completed);
1967 let card = plan.render_compact_checklist();
1968 assert!(!card.contains("not done"), "{card}");
1969 assert!(is_completed_checklist(&card), "{card}");
1970 }
1971
1972 #[test]
1976 fn a_step_waiting_on_a_failed_run_is_not_done_with_the_reason() {
1977 let mut plan = TaskPlan::new(
1978 "synthetic-session",
1979 "synthetic-task",
1980 "description",
1981 vec!["wait for the build".into()],
1982 "track_requirements",
1983 );
1984 let jobs = vec!["job-a".to_string(), "job-b".to_string()];
1985 assert!(plan.wait_on_background_jobs(&jobs));
1986 assert!(plan.settle_background_job("job-a", JobEnd::Failed));
1987 assert_eq!(plan.steps[0].status, StepStatus::Background);
1988 assert!(!plan.is_finished());
1989 assert!(plan.settle_background_job("job-b", JobEnd::Succeeded));
1990 assert_eq!(plan.steps[0].status, StepStatus::Deferred);
1991 assert_eq!(plan.steps[0].not_done, Some(NotDoneReason::WaitedOnFailed));
1992 assert!(plan.is_finished());
1993 let card = plan.render_compact_checklist();
1994 assert!(
1995 card.contains("wait for the build (not done: the work it waited on failed)"),
1996 "{card}"
1997 );
1998 }
1999
2000 #[test]
2007 fn a_declined_helper_reads_as_declined_and_shared_steps_wait_for_every_run() {
2008 let mut plan = TaskPlan::new(
2009 "synthetic-session",
2010 "synthetic-task",
2011 "description",
2012 vec![
2013 "Install Drupal".into(),
2014 "Install WordPress".into(),
2015 "Screenshot both homepages".into(),
2016 ],
2017 "track_requirements",
2018 );
2019 assert!(plan.link_background_job(&[0, 2], "job-drupal"));
2020 assert!(plan.link_background_job(&[1, 2], "job-wordpress"));
2021 assert!(plan.settle_background_job("job-wordpress", JobEnd::Declined));
2022 assert_eq!(plan.steps[1].not_done, Some(NotDoneReason::OwnerDeclined));
2023 assert_eq!(plan.steps[2].status, StepStatus::Background);
2024 assert!(plan.settle_background_job("job-drupal", JobEnd::Succeeded));
2025 assert_eq!(plan.steps[0].status, StepStatus::Completed);
2026 assert_eq!(plan.steps[2].status, StepStatus::Deferred);
2027 assert_eq!(plan.steps[2].not_done, Some(NotDoneReason::OwnerDeclined));
2028 let card = plan.render_compact_checklist();
2029 assert!(
2030 card.starts_with(
2031 "⏭️ Not done: you declined a step its helper asked to take · 1 of 3 done"
2032 ),
2033 "{card}"
2034 );
2035 let done_rows = card.lines().filter(|line| line.starts_with('✅')).count();
2036 assert_eq!(done_rows, plan.card().done, "{card}");
2037 }
2038
2039 #[test]
2045 fn a_step_names_the_folder_its_run_really_made() {
2046 let mut plan = TaskPlan::new(
2047 "synthetic-session",
2048 "synthetic-task",
2049 "description",
2050 vec![
2051 "Install Drupal in claude-drupal-12".into(),
2052 "Install WordPress in claude-wordpress-1".into(),
2053 ],
2054 "track_requirements",
2055 );
2056 assert!(plan.link_background_job(&[0], "job-drupal"));
2057 assert!(plan.link_background_job(&[1], "job-wordpress"));
2058 assert!(plan.note_job_folders(
2059 "job-drupal",
2060 &["/Users/x/projects/claude-company-drupal-5879".to_string()]
2061 ));
2062 assert!(plan.note_job_folders(
2063 "job-wordpress",
2064 &["/Users/x/projects/claude-wordpress-1".to_string()]
2065 ));
2066 assert!(plan.settle_background_job("job-drupal", JobEnd::Succeeded));
2067 assert!(plan.settle_background_job("job-wordpress", JobEnd::Succeeded));
2068 let card = plan.render_compact_checklist();
2069 assert!(
2070 card.contains(
2071 "✅ Install Drupal in claude-drupal-12 (made claude-company-drupal-5879)"
2072 ),
2073 "{card}"
2074 );
2075 assert!(
2076 card.contains("✅ Install WordPress in claude-wordpress-1\n")
2077 || card.ends_with("✅ Install WordPress in claude-wordpress-1"),
2078 "{card}"
2079 );
2080 }
2081
2082 #[test]
2086 fn a_step_nothing_took_on_reads_not_attempted() {
2087 let mut plan = TaskPlan::new(
2088 "synthetic-session",
2089 "synthetic-task",
2090 "description",
2091 vec!["Install Drupal".into(), "Install WordPress".into()],
2092 "track_requirements",
2093 );
2094 plan.link_background_job(&[0], "job-a");
2095 assert!(plan.mark_not_attempted(&std::collections::BTreeSet::from([1])));
2096 assert_eq!(plan.steps[1].not_done, Some(NotDoneReason::NotAttempted));
2097 assert_eq!(plan.steps[0].status, StepStatus::Background);
2098 let card = plan.render_compact_checklist();
2099 assert!(
2100 card.contains("Install WordPress (not done: not attempted)"),
2101 "{card}"
2102 );
2103 assert!(plan.settle_background_job("job-a", JobEnd::Succeeded));
2104 assert_eq!(plan.steps[0].status, StepStatus::Completed);
2105 assert_eq!(plan.steps[1].not_done, Some(NotDoneReason::NotAttempted));
2106 }
2107
2108 #[test]
2109 fn background_steps_that_all_finish_complete_the_plan() {
2110 let mut plan = TaskPlan::new(
2111 "synthetic-session",
2112 "synthetic-task",
2113 "description",
2114 vec!["first".into(), "second".into()],
2115 "track_requirements",
2116 );
2117 plan.link_background_job(&[0, 1], "job-a");
2118 plan.status = PlanStatus::PartiallyCompleted;
2119 assert!(plan.settle_background_job("job-a", JobEnd::Succeeded));
2120 assert_eq!(plan.status, PlanStatus::Completed);
2121 assert!(is_completed_checklist(&plan.render_compact_checklist()));
2122 }
2123
2124 #[test]
2125 fn deferred_steps_resolve_to_partial_plan_with_visible_blocker_requirement() {
2126 let mut plan = TaskPlan::new(
2127 "synthetic-session",
2128 "synthetic-task",
2129 "description",
2130 vec!["first action".into(), "second action".into()],
2131 "track_requirements",
2132 );
2133 for step in &mut plan.steps {
2134 step.status = StepStatus::Deferred;
2135 }
2136 plan.sync_active_step();
2137
2138 assert_eq!(plan.status, PlanStatus::PartiallyCompleted);
2139 let checklist = plan.render_compact_checklist();
2140 assert!(checklist.starts_with("⚠️ Stopped short · 0 of 2 done"));
2141 assert!(checklist.contains("⏭️ first action (not done)"));
2142 assert!(
2143 !checklist.contains("deferred"),
2144 "no internal status word: {checklist}"
2145 );
2146 assert!(!is_completed_checklist(&checklist));
2147 assert!(checklist.contains("what was left undone and why"));
2148 assert!(!checklist.contains("must"));
2150 }
2151
2152 #[test]
2153 fn test_plan_status_is_incomplete() {
2154 assert!(PlanStatus::Planning.is_incomplete());
2155 assert!(PlanStatus::InProgress.is_incomplete());
2156 assert!(PlanStatus::Paused.is_incomplete());
2157 assert!(!PlanStatus::Completed.is_incomplete());
2158 assert!(!PlanStatus::PartiallyCompleted.is_incomplete());
2159 assert!(!PlanStatus::Failed.is_incomplete());
2160 assert!(!PlanStatus::Abandoned.is_incomplete());
2161 }
2162
2163 fn parallel_installs() -> TaskPlan {
2164 let mut plan = TaskPlan::new(
2165 "synthetic-session",
2166 "synthetic-task",
2167 "description",
2168 vec![
2169 "install the drupal site".into(),
2170 "install the wordpress site".into(),
2171 "report both".into(),
2172 ],
2173 "track_requirements",
2174 );
2175 plan.steps[0].status = StepStatus::Background;
2177 plan.steps[1].status = StepStatus::Background;
2178 plan
2179 }
2180
2181 #[test]
2187 fn a_second_parallel_launch_is_accepted_when_the_first_named_only_its_own_step() {
2188 let mut plan = parallel_installs();
2189 assert!(plan.link_background_job(&[0], "job-drupal"));
2190 plan.wait_on_background_jobs(&["job-drupal".to_string()]);
2193 let running = |_: &str| true;
2194 assert!(
2195 plan.steps_covered_by_running_jobs(&[1], running).is_empty(),
2196 "the WordPress step only waits on Drupal: {:?}",
2197 plan.steps[1]
2198 );
2199 assert_eq!(
2200 plan.steps_covered_by_running_jobs(&[0], running)
2201 .iter()
2202 .map(|covered| covered.index)
2203 .collect::<Vec<_>>(),
2204 vec![0],
2205 "Drupal's own step is still guarded"
2206 );
2207 assert!(plan.link_background_job(&[1], "job-wordpress"));
2208 assert!(plan.settle_background_job("job-drupal", JobEnd::Succeeded));
2210 assert_eq!(plan.steps[0].status, StepStatus::Completed);
2211 assert_eq!(plan.steps[1].status, StepStatus::Background);
2212 assert!(plan.settle_background_job("job-wordpress", JobEnd::Failed));
2213 assert_eq!(plan.steps[1].status, StepStatus::Failed);
2214 }
2215
2216 #[test]
2219 fn a_step_that_only_waits_never_blocks_a_launch() {
2220 let mut plan = parallel_installs();
2221 plan.steps[0].status = StepStatus::Pending;
2222 plan.steps[1].status = StepStatus::Pending;
2223 plan.wait_on_background_jobs(&["job-first".to_string()]);
2224 let running = |_: &str| true;
2225 assert!(plan.steps_covered_by_running_jobs(&[], running).is_empty());
2226 assert!(plan.steps_covered_by_running_jobs(&[1], running).is_empty());
2227 }
2228
2229 #[test]
2233 fn a_waiting_step_whose_own_helper_never_started_is_not_done() {
2234 let mut plan = parallel_installs();
2235 assert!(plan.link_background_job(&[0], "job-drupal"));
2236 plan.wait_on_background_jobs(&["job-drupal".to_string()]);
2237 assert!(plan.helper_did_not_start(&[1], "the launch was refused"));
2238 assert!(plan.settle_background_job("job-drupal", JobEnd::Succeeded));
2239 assert_eq!(plan.steps[0].status, StepStatus::Completed);
2240 assert_ne!(plan.steps[1].status, StepStatus::Completed);
2241 let card = plan.render_compact_checklist();
2242 assert!(!card.contains("Done ·"), "{card}");
2243 assert!(!card.contains("3 of 3"), "{card}");
2244 assert!(card.contains("didn't run"), "{card}");
2245 assert!(!card.contains("running in the background"), "{card}");
2246 }
2247}