Skip to main content

aidaemon_work/plans/
mod.rs

1//! Persistent Task Plans for reliable multi-step task execution.
2//!
3//! This module provides a planning system that:
4//! - Persists multi-step task state to SQLite
5//! - Keeps a task's checklist across a restart (the resume itself is built
6//!   from the event log, see `agent/runtime/resume.rs`)
7//! - Provides explicit step-by-step progress tracking
8//! - Supports resume capability for long-running tasks
9
10pub mod checklist_args;
11mod store;
12
13pub use store::{PlanStore, migrate_task_plans};
14
15/// Start of the user-facing render in this tool's output. The agent loop
16/// locates it to lift the checklist onto the live status surface, so any
17/// model-only notice must precede it.
18pub 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/// A persistent multi-step task plan.
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct TaskPlan {
31    /// Unique identifier (UUID)
32    pub id: String,
33
34    /// Session this plan belongs to
35    pub session_id: String,
36
37    /// Human-readable description (from user request)
38    pub description: String,
39
40    /// The original user message that triggered this plan
41    pub trigger_message: String,
42
43    /// Ordered list of steps
44    pub steps: Vec<PlanStep>,
45
46    /// Index of current step (0-based)
47    pub current_step: usize,
48
49    /// Overall plan status
50    pub status: PlanStatus,
51
52    /// Arbitrary checkpoint data (tool outputs, intermediate results)
53    pub checkpoint: JsonValue,
54
55    /// Why the plan was created (complexity heuristic result)
56    pub creation_reason: String,
57
58    /// Task ID from event store (links plan to events)
59    pub task_id: Option<String>,
60
61    pub created_at: DateTime<Utc>,
62    pub updated_at: DateTime<Utc>,
63}
64
65impl TaskPlan {
66    /// Create a new task plan with the given steps.
67    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    /// Get the current step, if any.
123    pub fn current_step_ref(&self) -> Option<&PlanStep> {
124        self.steps.get(self.current_step)
125    }
126
127    /// Get the current step mutably, if any.
128    pub fn current_step_mut(&mut self) -> Option<&mut PlanStep> {
129        self.steps.get_mut(self.current_step)
130    }
131
132    /// Keep the user-facing execution pointer aligned with checklist state.
133    /// While work remains, exactly one pending step is promoted to in-progress.
134    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    /// Calculate total duration in seconds.
162    pub fn duration_secs(&self) -> u64 {
163        (self.updated_at - self.created_at).num_seconds().max(0) as u64
164    }
165
166    /// Count completed steps.
167    pub fn completed_steps(&self) -> usize {
168        self.steps
169            .iter()
170            .filter(|s| s.status == StepStatus::Completed)
171            .count()
172    }
173
174    /// Completed action steps no receipt verified: the only steps the card
175    /// flags ([`PlanStep::unverified`]).
176    pub fn unverified_steps(&self) -> usize {
177        self.steps.iter().filter(|s| s.unverified()).count()
178    }
179
180    /// The steps at `indices` were confirmed by typed evidence (the run's
181    /// receipts proved their checklist items): no longer said done only.
182    /// Returns whether any step changed.
183    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    /// The helper meant for the steps at `indices` never started (its
198    /// `spawn_agent` call failed): nothing works on them, so they are not
199    /// done, and the card says they didn't run. A step already done or set
200    /// aside is left alone. Returns whether any step changed.
201    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    /// Check if all steps are done (completed, failed, or skipped).
234    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    /// Derive the terminal plan state from typed step outcomes. A deferred
247    /// item is resolved for scheduling purposes but is not successful work.
248    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    /// Validate the persisted step dependency graph.
267    pub fn validate_graph(&self) -> Result<(), String> {
268        self.step_graph().map(|_| ())
269    }
270
271    /// Pending steps whose prerequisites have reached accepted terminal state.
272    /// The current executor selects one deterministically; task-level workers
273    /// can use the same graph shape for actual parallel branches.
274    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    /// Advance to the next step. Returns true if there was a next step.
341    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    /// Mark the current step as completed with a summary.
365    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    /// Mark the current step as failed with an error message.
375    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    /// Increment retry count for current step and reset to in-progress.
385    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    /// Steps still requiring action (not completed/deferred/failed/skipped).
397    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    /// Whether a background job is still working on any step.
405    pub fn has_background_steps(&self) -> bool {
406        self.steps
407            .iter()
408            .any(|step| step.status == StepStatus::Background)
409    }
410
411    /// Hand the steps at `indices` to the background job `job_id`. A step
412    /// owns its runs in order and its outcome is its latest run's: a step
413    /// an earlier run failed or stopped short on is taken over by this one
414    /// (a retry), and only this job's end settles it. A step already done
415    /// or skipped is left alone. Returns whether any step changed.
416    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            // Its own run now: the jobs it waited on no longer settle it.
429            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            // A step whose helper didn't start may have resolved the plan;
441            // it is being worked on again.
442            if !self.status.is_incomplete() {
443                self.status = PlanStatus::InProgress;
444            }
445            self.updated_at = Utc::now();
446        }
447        changed
448    }
449
450    /// The steps a launch takes on: the steps it names that the plan lists,
451    /// and each step whose owner units all fall within the units the launch
452    /// says it carries out (`owner_units`). Typed links only: a launch
453    /// whose named item is not a step of this plan, but which names the
454    /// owner's unit, takes on the plan's own step for that unit, never a
455    /// new row.
456    ///
457    /// A unit one of its named steps already carries is taken on through
458    /// that step: the launch's own row for the unit, not every row of it.
459    /// Several steps can share one unit ("install both sites"); a batch's
460    /// children each name their own, and expanding the shared unit gave
461    /// every child every row, so each row read both children's folders
462    /// (live 2026-11-14: "Install Drupal … (made claude-company-wordpress-2,
463    /// claude-company-drupal-2)").
464    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    /// A step still open whose every owner unit a run took on (through the
496    /// steps those runs were handed) is being done by those runs: it waits
497    /// on each of them and settles from their ends, never left open or
498    /// called unattempted while they do its units (a screenshot of both
499    /// sites, done by the two helpers installing them). Returns whether
500    /// anything changed.
501    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    /// The steps a new helper would do that a helper still running already
545    /// does, each with the running jobs on it. `indices` are the steps the
546    /// new launch names (`checklist_items`). A launch that names none is
547    /// judged against every open step: it is covered only when each of them
548    /// is already being done (live 2026-11-14: the turn launched a WordPress
549    /// and a Drupal helper, then a third helper for the WordPress install
550    /// while the first still ran). A step whose helpers all ended is not
551    /// covered, whatever its status still says, so a step an earlier helper
552    /// ended without finishing can be launched again. `running` says whether
553    /// a job is still running (the run records know that, not the plan).
554    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    /// The turn handed its work to background jobs `job_ids` without naming
603    /// the steps they do (`checklist_items`): every step still open (marked
604    /// handed off with no job yet, or already waiting on an earlier job)
605    /// waits on them, so the card reads "continuing in the background", never
606    /// "stopped short", while they run. Their typed ends settle such a step
607    /// ([`PlanStep::waited_jobs`]). Returns whether anything changed.
608    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            // A step already waiting on an earlier job waits on this one too
615            // (live 2026-11-13: two helpers started by one turn; the second
616            // was never on the plan, so the first's end settled the steps
617            // while the second still ran, and its own end found no plan).
618            // A step the model marked handed off ("background") before any
619            // launch took it waits on the launches too: the mark says it
620            // delegated, the jobs are what it delegated to (live 2026-11-13:
621            // two such steps were skipped here, no run was ever linked to
622            // them, and the turn's end set them aside as "not done" while
623            // both helpers went on to succeed).
624            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    /// A step the checklist marked "background" that no run took on or
649    /// waits on is not running: it is open again, judged like any open step
650    /// (a launch takes it, the turn's end settles it). The mark alone never
651    /// leaves a row "running in the background" with nothing running.
652    /// Returns whether anything changed.
653    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    /// The folders background job `job_id` made (its claim evidence), on
669    /// the steps it took on, before its end settles them. Returns whether
670    /// any step changed.
671    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    /// Record the end of background job `job_id`, as its run record says.
691    /// A step handed to several jobs (or waiting on them) settles once the
692    /// last of them ended, from all their typed ends: completed when every
693    /// one succeeded, failed when one failed (a step handed to it; a step
694    /// that only waited on it is not done, with that reason), and not done
695    /// when one stopped before finishing or ended short because the owner
696    /// declined one of its steps. While others still run it stays in the
697    /// background, so a later run's success is never lost (live 2026-11-13:
698    /// the WordPress helper's end marked steps both helpers shared as not
699    /// done, the Drupal helper then finished them, and the card read "1 of
700    /// 5 done" above its helpers' finished lines). The plan resolves once
701    /// nothing is left to run. Returns whether any step changed.
702    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        // The worse of two ends: a failure, then a stop, then a decline.
713        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            // A step a job of its own took on settles from its own runs
728            // only: an end it merely waited on is not its outcome (live
729            // 2026-11-14: Drupal's success marked the WordPress step done).
730            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            // Live 2026-11-13: a step that only waited on a background job
743            // read "(not done)" after the job succeeded. Its runs' typed
744            // ends are what settle it.
745            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    /// Its turn is over and nothing it handed work to is still running: a
771    /// step still open (pending, in progress, or waiting on a job no longer
772    /// running) can no longer be done by anything, so it settles as not done
773    /// ([`NotDoneReason::LeftOpen`]) and the plan resolves. A card never
774    /// stays "working" on a step nothing is working on (live 2026-11-13: a
775    /// "Report each helper's measured time" step held a card on "Working ·
776    /// step 4 of 4" for 14 minutes after both helpers ended). Returns
777    /// whether anything changed.
778    ///
779    /// While a job a launch handed a step to has not ended (it is still
780    /// listed on the step), the plan's work is still going and nothing
781    /// settles: that job's own end settles its step
782    /// ([`Self::settle_background_job`]) and then the rest, however the
783    /// card's runs were counted when this settle ran. Live 2026-11-13: the
784    /// first helper's end settled the card while the second, launched for
785    /// the WordPress step, was not yet counted on it; the card read
786    /// "Stopped short · 1 of 3 (not done: nothing was left working on it)",
787    /// then "Continuing", then "Stopped".
788    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        // Every step already has its outcome (the request's last turn did
812        // the rest): the plan's own state follows them, so its header never
813        // reads "Working" over rows that are all settled.
814        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    /// The run's ledger says nothing ever took on the steps at `indices`
824    /// ([`NotDoneReason::NotAttempted`]): each settles as not done with that
825    /// reason, unless it is done or skipped. A step that only waited on the
826    /// turn's jobs without being handed to one waits no longer: no job is
827    /// doing it. Returns whether anything changed.
828    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    /// Record that the steps not done in this plan were held back because
859    /// the turn could not make changes: a failed or deferred step becomes a
860    /// deferred step with [`NotDoneReason::ChangesOff`], which the card shows
861    /// as correctly not done. Returns whether anything changed.
862    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    /// The reason every step left undone shares, when all of them were held
884    /// back for a known reason (and at least one was).
885    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    /// The plan as the card shows it: [`Self::render_compact_checklist`] and
900    /// its step count, which decides whether the card is kept.
901    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    /// Compact, channel-friendly checklist for the live status card.
920    ///
921    /// One header line carries the state and the count; the steps follow, a
922    /// blank line apart so wrapped descriptions stay readable on a phone. A
923    /// one-step plan is just that step (a header and a "1 of 1" would only
924    /// repeat it). A fully completed card starts with ✅
925    /// ([`is_completed_checklist`]), so the card drops the turn's own step
926    /// line. A step that turned out not to be
927    /// needed, or that was held back for a known reason, is never shown as a
928    /// failure.
929    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        // Every completed step counts as done; the action steps nothing
938        // verified are said once, in plain words, on the final card only.
939        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            // Work handed to a job that reports back is still being done:
983            // never "stopped short" while it runs.
984            _ if in_background => {
985                format!("⏳ Continuing in the background · {done} of {total} done{said_note}")
986            }
987            // Everything left was held back for a known reason: the turn did
988            // what it was allowed to, which is not a failure.
989            _ 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            // Every step resolved, and an action step only on the model's
1000            // word: never a ✅ the evidence does not back.
1001            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            // The execution plan is resolved; the reply is still on its way,
1010            // which the typing indicator shows. Never claim the task is over.
1011            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                // Its row says only that it didn't run; why is said once,
1031                // under the rows, however many steps it applies to.
1032                (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                // `deferred` is the model's typed "set aside": the owner
1043                // reads what it means for them.
1044                (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            // A blank line between steps: descriptions wrap on a phone, and
1050            // without a gap the wrapped lines run into the next step.
1051            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        // Why the steps marked "didn't run" never ran: said once, not on
1058        // each row (live 2026-11-14: "(didn't run: its helper didn't
1059        // start)" twice on one card, then the same steps again below).
1060        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    /// End-of-turn recap of what got done vs what remains/deferred.
1071    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    /// Format the plan for system prompt injection.
1087    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/// A checklist step a running helper already does
1136/// ([`TaskPlan::steps_covered_by_running_jobs`]).
1137#[derive(Debug, Clone, PartialEq, Eq)]
1138pub struct CoveredStep {
1139    pub index: usize,
1140    pub description: String,
1141    /// The running jobs (launch ids) on it.
1142    pub jobs: Vec<String>,
1143}
1144
1145/// A single step in a task plan.
1146#[derive(Debug, Clone, Serialize, Deserialize)]
1147pub struct PlanStep {
1148    /// Step index (0-based)
1149    pub index: usize,
1150
1151    /// Human-readable description
1152    pub description: String,
1153
1154    /// Indices of prerequisite steps. Missing on legacy rows means the steps
1155    /// are independent; newly generated plans persist explicit serial edges.
1156    #[serde(default)]
1157    pub depends_on: Vec<usize>,
1158
1159    /// Typed evidence contract for automatic completion. If empty/false, only
1160    /// an explicit checklist update may complete the step.
1161    #[serde(default)]
1162    pub required_mutation_effects: ToolMutationEffects,
1163    #[serde(default)]
1164    pub requires_observation: bool,
1165    /// Exact canonical targets (path, URL, or resource ID), never prose.
1166    #[serde(default)]
1167    pub expected_targets: Vec<String>,
1168    /// The owner's units of work this step carries out (`owner_units` on
1169    /// its checklist item): the typed identity a re-declaration and a
1170    /// launch find the step by, wherever it sits in the list.
1171    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1172    pub owner_units: Vec<usize>,
1173    /// Tool-call receipt IDs that proved this step.
1174    #[serde(default)]
1175    pub evidence_receipt_ids: Vec<String>,
1176
1177    /// Background jobs (their launch ids) that took this step on and still
1178    /// work on it: a launch named it in its typed `checklist_items`. Each
1179    /// job's end settles the step ([`TaskPlan::settle_background_job`]), and
1180    /// only these make a new helper for the step a duplicate.
1181    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1182    pub background_jobs: Vec<String>,
1183
1184    /// Background jobs this step only waits on: it was left open while the
1185    /// turn's jobs ran, and no launch named it. It reads as running while
1186    /// they do and, while no job of its own took it on, settles from their
1187    /// typed ends: done once every one succeeded, not done (with the reason)
1188    /// once one failed or stopped. Waiting on a job is not being done by it:
1189    /// it never makes a launch for the step a duplicate.
1190    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1191    pub waited_jobs: Vec<String>,
1192
1193    /// The folders the runs that took this step on made for it, from their
1194    /// claim evidence (what each found absent and then created), recorded
1195    /// as each run ended. The card names them, so a run that made another
1196    /// folder than the step's words named shows the real one (live
1197    /// 2026-11-14: the card read claude-drupal-12, the site was made in
1198    /// claude-company-drupal-5879).
1199    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1200    pub made_folders: Vec<String>,
1201
1202    /// Why a step that was not done was left undone, when the daemon knows it
1203    /// from typed state (never from the step's text). Such a step was held
1204    /// back correctly, so the card does not show it as a failure.
1205    #[serde(default, skip_serializing_if = "Option::is_none")]
1206    pub not_done: Option<NotDoneReason>,
1207
1208    /// How its state is known: settled by typed evidence, completed on the
1209    /// executing model's word alone (its checklist update said done and no
1210    /// receipt or helper's result proved it; evidence clears it), or handed
1211    /// to a helper that never started (a later launch takes it again).
1212    #[serde(default, skip_serializing_if = "StepEvidence::is_settled")]
1213    pub evidence: StepEvidence,
1214
1215    /// Step status
1216    pub status: StepStatus,
1217
1218    /// Tool calls made during this step (event IDs or tool:timestamp)
1219    pub tool_call_ids: Vec<String>,
1220
1221    /// Summary of what was accomplished
1222    pub result_summary: Option<String>,
1223
1224    /// Error message if step failed
1225    pub error: Option<String>,
1226
1227    /// Number of retry attempts
1228    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    /// The owner's units of work the item carries out.
1243    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    /// Its words on the card, with the folders its runs made that its words
1252    /// do not already name: the real folder, from the claim evidence.
1253    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    /// Completed on the model's word alone, and a step that declared a
1273    /// side effect: the one kind of step the card flags. A step that
1274    /// changes nothing (a check, a read) needs no receipt: the reply says
1275    /// what it found.
1276    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    /// Any background job is still listed on it: one that took it on, or
1283    /// one it waits on.
1284    pub fn has_background_jobs(&self) -> bool {
1285        !self.background_jobs.is_empty() || !self.waited_jobs.is_empty()
1286    }
1287
1288    /// It was handed to a helper that never started.
1289    pub fn helper_not_started(&self) -> bool {
1290        self.evidence == StepEvidence::HelperNotStarted
1291    }
1292
1293    /// Calculate step duration in seconds (if completed).
1294    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/// Overall plan status.
1303#[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    /// LLM is generating steps
1318    Planning,
1319    /// Executing steps
1320    InProgress,
1321    /// Paused (session ended, waiting for user, or interrupted)
1322    Paused,
1323    /// All steps completed successfully
1324    Completed,
1325    /// Scheduling is resolved, but one or more requested steps were deferred.
1326    PartiallyCompleted,
1327    /// Unrecoverable failure
1328    Failed,
1329    /// User explicitly cancelled
1330    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    /// Check if this status represents an incomplete/active plan.
1344    pub fn is_incomplete(&self) -> bool {
1345        matches!(
1346            self,
1347            PlanStatus::Planning | PlanStatus::InProgress | PlanStatus::Paused
1348        )
1349    }
1350}
1351
1352/// Status of a single step.
1353#[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    /// Not yet started
1368    Pending,
1369    /// Currently executing
1370    InProgress,
1371    /// Completed successfully
1372    Completed,
1373    /// Failed (may retry)
1374    Failed,
1375    /// Skipped (dependency failed or user skipped)
1376    Skipped,
1377    /// Explicitly abandoned by the model (counts as resolved, not unchecked).
1378    Deferred,
1379    /// Handed to a background job that reports back: still being worked on,
1380    /// outside this run. Only the job's end moves it to completed or failed.
1381    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
1395/// How the card marks an action step nothing verified.
1396const UNVERIFIED: &str = "I couldn't verify this one";
1397/// How the card marks a step whose helper never started.
1398const HELPER_NOT_STARTED: &str = "didn't run: its helper didn't start";
1399
1400/// Why a step was correctly left undone.
1401#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1402#[serde(rename_all = "snake_case")]
1403pub enum NotDoneReason {
1404    /// The turn could not change anything (read-only access or a request
1405    /// that forbids changes), and this step needed a change.
1406    ChangesOff,
1407    /// The background helper it was handed ended before finishing it (its
1408    /// run record says stopped: not a failure).
1409    HelperStopped,
1410    /// Its turn ended and nothing was left working on it.
1411    LeftOpen,
1412    /// A background job it waited on failed (its run record says so).
1413    WaitedOnFailed,
1414    /// The owner declined a step the helper it was handed asked to take,
1415    /// and it ended without finishing (its run record says so): the
1416    /// owner's answer, never a failure.
1417    OwnerDeclined,
1418    /// The owner stopped the helper it was handed before it finished: a
1419    /// stop, never a failure.
1420    OwnerStopped,
1421    /// Nothing ever took it on: no call did it, no job was launched for it,
1422    /// and the owner was not asked (the run's ledger says so).
1423    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/// How a background job ended, as its run record says: what its steps
1441/// become. Only `Failed` marks a step as couldn't be done.
1442#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1443pub enum JobEnd {
1444    Succeeded,
1445    Stopped,
1446    /// It stopped short because the owner declined one of its steps.
1447    Declined,
1448    /// The owner stopped it before it finished.
1449    StoppedByOwner,
1450    Failed,
1451}
1452
1453/// Whether a card from [`TaskPlan::render_compact_checklist`] shows every
1454/// step finished (the channel's live status reads cards the same way).
1455pub 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    /// A step a running helper does is covered: a second launch for it is
1475    /// a duplicate. Once that helper ended without finishing it, it is open
1476    /// to a retry again.
1477    #[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        // Every open step is being done: a launch naming none covers nothing new.
1494        assert_eq!(plan.steps_covered_by_running_jobs(&[], running).len(), 2);
1495
1496        // The WordPress helper stopped short: its step may be launched again.
1497        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        // A retry names its step: unnamed, it reads as more of what still runs.
1504        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    /// A step whose helper is gone (a restart lost its run record) is not
1512    /// covered, even while its status still reads as in the background.
1513    #[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    /// A launch that names no steps is covered only when every open step
1528    /// already has a running helper: with one step free, it may be that one.
1529    #[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        // Naming the covered step is still a duplicate.
1538        assert_eq!(
1539            plan.steps_covered_by_running_jobs(&[0, 1], |job| job == "job-wp")
1540                .len(),
1541            1
1542        );
1543    }
1544
1545    /// A step a launch left waiting on the turn's jobs (no `checklist_items`)
1546    /// is not being done by them: it waits, and a launch for it is not a
1547    /// duplicate (live 2026-11-14: the WordPress helper was refused because
1548    /// its step waited on the Drupal job).
1549    #[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    /// A step owns its runs in order and its outcome is its latest run's:
1561    /// a step an earlier helper failed or stopped short on is taken over by
1562    /// a later one for the same step, and that run's success completes it.
1563    #[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    /// A second job a turn starts joins the steps already waiting on the
1674    /// first; once both ended, a step left open settles as not done and the
1675    /// plan resolves: nothing reads "working" with nothing working.
1676    #[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    /// Live 2026-11-13: two helpers launched, one per site. The first one's
1712    /// end settled the card before the second was counted on it, and its
1713    /// step read "nothing was left working on it" while it ran. A step a
1714    /// launch took on waits for that launch's own end.
1715    #[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        // One step: the step itself, no header or "1 of 1".
1845        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    /// Steps handed to background jobs read as still being done: the card
1867    /// never says "stopped short" or "not done" while they run, whatever
1868    /// verdict the run itself recorded.
1869    #[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        // The run itself ends partial: work continues elsewhere.
1887        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        // One job done: its own step is done; the shared one waits for both.
1900        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        // The other fails: its step and the shared one failed, never done.
1909        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        // A job nothing waits on changes nothing.
1918        assert!(!plan.settle_background_job("job-c", JobEnd::Succeeded));
1919    }
1920
1921    /// A turn that hands work to background jobs without linking its open
1922    /// steps never reads "stopped short" or "not done" while they run, and
1923    /// once every job succeeded the steps waiting on them are done.
1924    #[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    /// A step waiting on runs settles once the last of them ended: not
1973    /// done, with the plain reason, when one of them failed, even though
1974    /// another succeeded.
1975    #[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    /// Live 2026-11-13: the owner declined the WordPress helper's password
2001    /// rotation; it ended short while the Drupal helper still ran, and the
2002    /// card read "Not done: its helper stopped before it finished · 1 of 5
2003    /// done" above its helpers' finished lines. A step both helpers shared
2004    /// waits for both; the WordPress step reads why it was not done; the
2005    /// header's count is the rows' count.
2006    #[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    /// Live 2026-11-14: the Drupal step read claude-drupal-12, but its
2040    /// helper made claude-company-drupal-5879. The folder a job's claim
2041    /// evidence recorded goes on the steps it took on, and the card names
2042    /// it when the step's words don't; a step that already names it reads
2043    /// as before, and a step the job never took on gets nothing.
2044    #[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    /// Live 2026-11-13: one helper launched for the Drupal step; the
2083    /// WordPress step was never taken on. The card says so with its typed
2084    /// reason, and the running helper still settles its own step.
2085    #[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        // The footer speaks to the user; it is not an instruction to the model.
2149        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        // The model marked both installs handed off before either launch.
2176        plan.steps[0].status = StepStatus::Background;
2177        plan.steps[1].status = StepStatus::Background;
2178        plan
2179    }
2180
2181    /// Live 2026-11-14: two parallel helpers, Drupal and WordPress. The
2182    /// Drupal launch named only its own step, yet the WordPress step, left
2183    /// waiting on the turn's launches, counted as already being done by the
2184    /// Drupal job and the WordPress launch was refused. Waiting on a run is
2185    /// not being done by it.
2186    #[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        // The checklist is posted again while Drupal runs: the open steps
2191        // wait on the turn's launch.
2192        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        // Drupal's end settles only its own step; WordPress's is its run's.
2209        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    /// A step that only waits on a running job never blocks a launch, named
2217    /// or not.
2218    #[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    /// The WordPress step's own helper never started while it waited on
2230    /// Drupal's: Drupal's success does not make it done, and the header
2231    /// counts it as not done (live 2026-11-14: "Done · 4 of 4 steps").
2232    #[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}