Skip to main content

aidaemon_work/plans/
store.rs

1//! PlanStore - SQLite persistence for task plans.
2
3use chrono::{DateTime, Utc};
4use sqlx::{Row, SqlitePool};
5
6use super::{PlanStatus, TaskPlan};
7
8/// Persistent storage for task plans.
9pub struct PlanStore {
10    pool: SqlitePool,
11}
12
13/// One writer at a time for every read-change-store of a plan. A plan is
14/// stored whole, so two writers that read it at once each store their own
15/// copy and the later one drops the earlier one's change (two helpers one
16/// `spawn_agent` batch starts link their steps concurrently). Process-wide,
17/// so every `PlanStore` over the database shares it.
18static PLAN_WRITES: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
19
20impl PlanStore {
21    /// Create a new PlanStore with the given database pool.
22    /// Runs migrations to create the task_plans table.
23    pub async fn new(pool: SqlitePool) -> anyhow::Result<Self> {
24        let store = Self { pool };
25        store.migrate().await?;
26        Ok(store)
27    }
28
29    /// Get the underlying database pool.
30    pub fn pool(&self) -> SqlitePool {
31        self.pool.clone()
32    }
33
34    /// Run database migrations for the task_plans table.
35    async fn migrate(&self) -> anyhow::Result<()> {
36        migrate_task_plans(&self.pool).await
37    }
38
39    // =========================================================================
40    // Write Operations
41    // =========================================================================
42
43    /// Create a new plan.
44    pub async fn create(&self, plan: &TaskPlan) -> anyhow::Result<()> {
45        let steps_json = serde_json::to_string(&plan.steps)?;
46        let checkpoint_json = serde_json::to_string(&plan.checkpoint)?;
47
48        sqlx::query(
49            r#"
50            INSERT INTO task_plans (
51                id, session_id, description, trigger_message, steps,
52                current_step, status, checkpoint, creation_reason,
53                task_id, created_at, updated_at
54            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
55            "#,
56        )
57        .bind(&plan.id)
58        .bind(&plan.session_id)
59        .bind(&plan.description)
60        .bind(&plan.trigger_message)
61        .bind(&steps_json)
62        .bind(plan.current_step as i64)
63        .bind(plan.status.as_str())
64        .bind(&checkpoint_json)
65        .bind(&plan.creation_reason)
66        .bind(&plan.task_id)
67        .bind(plan.created_at.to_rfc3339())
68        .bind(plan.updated_at.to_rfc3339())
69        .execute(&self.pool)
70        .await?;
71
72        Ok(())
73    }
74
75    /// Update an existing plan (full replacement).
76    pub async fn update(&self, plan: &TaskPlan) -> anyhow::Result<()> {
77        let steps_json = serde_json::to_string(&plan.steps)?;
78        let checkpoint_json = serde_json::to_string(&plan.checkpoint)?;
79        let now = Utc::now().to_rfc3339();
80
81        sqlx::query(
82            r#"
83            UPDATE task_plans SET
84                description = ?,
85                trigger_message = ?,
86                steps = ?,
87                current_step = ?,
88                status = ?,
89                checkpoint = ?,
90                creation_reason = ?,
91                task_id = ?,
92                updated_at = ?
93            WHERE id = ?
94            "#,
95        )
96        .bind(&plan.description)
97        .bind(&plan.trigger_message)
98        .bind(&steps_json)
99        .bind(plan.current_step as i64)
100        .bind(plan.status.as_str())
101        .bind(&checkpoint_json)
102        .bind(&plan.creation_reason)
103        .bind(&plan.task_id)
104        .bind(&now)
105        .bind(&plan.id)
106        .execute(&self.pool)
107        .await?;
108
109        Ok(())
110    }
111
112    /// The session's latest plan, when it belongs to `task_id` (any task
113    /// when `None`): the checklist a launch's `checklist_items` index into.
114    pub async fn latest(
115        &self,
116        session_id: &str,
117        task_id: Option<&str>,
118    ) -> anyhow::Result<Option<TaskPlan>> {
119        Ok(self
120            .get_recent_for_session(session_id, 1)
121            .await?
122            .into_iter()
123            .next()
124            .filter(|plan| task_id.is_none() || plan.task_id.as_deref() == task_id))
125    }
126
127    /// The session's latest plan, when it belongs to `task_id` (any task
128    /// when `None`), changed by `change` under the plan write lock and
129    /// stored when `change` says it changed. Returns the stored plan, or
130    /// `None` when there was no such plan or nothing changed.
131    async fn change_latest(
132        &self,
133        session_id: &str,
134        task_id: Option<&str>,
135        change: impl FnOnce(&mut TaskPlan) -> bool,
136    ) -> anyhow::Result<Option<TaskPlan>> {
137        let _write = PLAN_WRITES.lock().await;
138        let Some(mut plan) = self
139            .get_recent_for_session(session_id, 1)
140            .await?
141            .into_iter()
142            .next()
143            .filter(|plan| task_id.is_none() || plan.task_id.as_deref() == task_id)
144        else {
145            return Ok(None);
146        };
147        if !change(&mut plan) {
148            return Ok(None);
149        }
150        self.update(&plan).await?;
151        Ok(Some(plan))
152    }
153
154    /// Plan `plan_id` changed by `change` under the plan write lock, stored
155    /// when `change` says it changed. Returns the plan as it now stands.
156    pub async fn modify(
157        &self,
158        plan_id: &str,
159        change: impl FnOnce(&mut TaskPlan) -> bool,
160    ) -> anyhow::Result<Option<TaskPlan>> {
161        let _write = PLAN_WRITES.lock().await;
162        let Some(mut plan) = self.get(plan_id).await? else {
163            return Ok(None);
164        };
165        if change(&mut plan) {
166            self.update(&plan).await?;
167        }
168        Ok(Some(plan))
169    }
170
171    /// Create or replace the active checklist for a session. Full-set replace:
172    /// the provided items become the plan's steps. Reuses an existing incomplete
173    /// plan (same id) when present so updates are idempotent.
174    pub async fn upsert_checklist(
175        &self,
176        session_id: &str,
177        task_id: Option<&str>,
178        trigger: &str,
179        items: &[(String, crate::plans::StepStatus)],
180    ) -> anyhow::Result<TaskPlan> {
181        let graph_items: Vec<crate::plans::ChecklistItem> = items
182            .iter()
183            .map(|(description, status)| crate::plans::ChecklistItem {
184                description: description.clone(),
185                status: *status,
186                depends_on: Vec::new(),
187                required_mutation_effects: crate::traits::ToolMutationEffects::NONE,
188                requires_observation: false,
189                expected_targets: Vec::new(),
190                owner_units: Vec::new(),
191            })
192            .collect();
193        self.upsert_checklist_graph(session_id, task_id, trigger, &graph_items)
194            .await
195    }
196
197    /// Create or replace a checklist with explicit prerequisite edges.
198    pub async fn upsert_checklist_graph(
199        &self,
200        session_id: &str,
201        task_id: Option<&str>,
202        trigger: &str,
203        items: &[crate::plans::ChecklistItem],
204    ) -> anyhow::Result<TaskPlan> {
205        use crate::plans::{PlanStep, StepStatus};
206        let now = Utc::now();
207        let steps: Vec<PlanStep> = items
208            .iter()
209            .enumerate()
210            .map(|(index, item)| PlanStep {
211                index,
212                description: item.description.clone(),
213                depends_on: item.depends_on.clone(),
214                required_mutation_effects: item.required_mutation_effects,
215                requires_observation: item.requires_observation,
216                expected_targets: item.expected_targets.clone(),
217                owner_units: item.owner_units.clone(),
218                evidence_receipt_ids: Vec::new(),
219                background_jobs: Vec::new(),
220                waited_jobs: Vec::new(),
221                made_folders: Vec::new(),
222                not_done: None,
223                // The model's own tick: done on its word until evidence
224                // confirms it.
225                evidence: if item.status == StepStatus::Completed {
226                    crate::plans::StepEvidence::ModelSaid
227                } else {
228                    crate::plans::StepEvidence::Settled
229                },
230                status: item.status,
231                tool_call_ids: Vec::new(),
232                result_summary: None,
233                error: None,
234                retry_count: 0,
235                started_at: if matches!(item.status, StepStatus::InProgress | StepStatus::Completed)
236                {
237                    Some(now)
238                } else {
239                    None
240                },
241                completed_at: if matches!(item.status, StepStatus::Completed) {
242                    Some(now)
243                } else {
244                    None
245                },
246            })
247            .collect();
248        let validation_plan = TaskPlan {
249            id: "checklist-validation".to_string(),
250            session_id: session_id.to_string(),
251            description: trigger.to_string(),
252            trigger_message: trigger.to_string(),
253            steps: steps.clone(),
254            current_step: 0,
255            status: PlanStatus::InProgress,
256            checkpoint: serde_json::Value::Object(serde_json::Map::new()),
257            creation_reason: "graph_validation".to_string(),
258            task_id: task_id.map(str::to_string),
259            created_at: now,
260            updated_at: now,
261        };
262        validation_plan
263            .validate_graph()
264            .map_err(anyhow::Error::msg)?;
265        let current_step = steps
266            .iter()
267            .position(|s| matches!(s.status, StepStatus::Pending | StepStatus::InProgress))
268            .unwrap_or(0);
269
270        let _write = PLAN_WRITES.lock().await;
271        // Only this request's own open plan is reused: a plan belongs to
272        // the request that declared it, and a turn that continues that
273        // request has adopted it ([`Self::carry_into_turn`]). An earlier
274        // request's open plan is never the new request's (live 2026-11-14:
275        // a new request's card showed "✅ Install WordPress … verify the
276        // site" from a run hours before).
277        let reusable = self
278            .get_incomplete_for_session(session_id)
279            .await?
280            .filter(|plan| plan.task_id.as_deref() == task_id);
281        if let Some(mut existing) = reusable {
282            // A step a background job is still doing stays with that job:
283            // a checklist update cannot finish or drop work it did not do.
284            // Only the job's end settles it. A step is found by its typed
285            // identity (its owner units, else its unchanged words), not by
286            // where the new list puts it ([`aidaemon_events::step_identity`]):
287            // live 2026-11-14, a re-declaration right after two launches
288            // moved their rows, their runs' links were dropped, and rows the
289            // helpers were doing read "not attempted" and never settled.
290            let mut steps = steps;
291            fn key(step: &PlanStep) -> aidaemon_events::step_identity::StepKey<'_> {
292                aidaemon_events::step_identity::StepKey {
293                    description: &step.description,
294                    owner_units: &step.owner_units,
295                }
296            }
297            let (same, carried) = {
298                let old_keys: Vec<_> = existing.steps.iter().map(key).collect();
299                let new_keys: Vec<_> = steps.iter().map(key).collect();
300                (
301                    aidaemon_events::step_identity::same_steps(&old_keys, &new_keys),
302                    aidaemon_events::step_identity::carried_work(&old_keys, &new_keys),
303                )
304            };
305            let mut orphaned_jobs: Vec<String> = Vec::new();
306            for (previous, (same, carried)) in
307                existing.steps.iter().zip(same.into_iter().zip(carried))
308            {
309                // The same step keeps the evidence that proved it: an
310                // update ticking it again neither erases its proof nor
311                // turns proven work into the model's word.
312                if let Some(step) = same.and_then(|index| steps.get_mut(index)) {
313                    for receipt in &previous.evidence_receipt_ids {
314                        if !step.evidence_receipt_ids.contains(receipt) {
315                            step.evidence_receipt_ids.push(receipt.clone());
316                        }
317                    }
318                    if step.status == StepStatus::Completed
319                        && previous.status == StepStatus::Completed
320                        && previous.evidence != crate::plans::StepEvidence::ModelSaid
321                    {
322                        step.evidence = crate::plans::StepEvidence::Settled;
323                        step.completed_at = previous.completed_at;
324                    }
325                    // Still the step whose helper didn't start, until a
326                    // launch takes it or the model resolves it.
327                    if previous.helper_not_started()
328                        && matches!(step.status, StepStatus::Pending | StepStatus::InProgress)
329                    {
330                        step.status = StepStatus::Failed;
331                        step.evidence = crate::plans::StepEvidence::HelperNotStarted;
332                        step.error = previous.error.clone();
333                        step.completed_at = previous.completed_at;
334                    }
335                }
336                if !(previous.status == StepStatus::Background && previous.has_background_jobs()) {
337                    continue;
338                }
339                // Its runs go with the work: to the same step, else to each
340                // step carrying the same owner units.
341                if carried.is_empty() {
342                    for job in previous.background_jobs.iter().chain(&previous.waited_jobs) {
343                        if !orphaned_jobs.contains(job) {
344                            orphaned_jobs.push(job.clone());
345                        }
346                    }
347                    continue;
348                }
349                for index in carried {
350                    let Some(step) = steps.get_mut(index) else {
351                        continue;
352                    };
353                    step.status = StepStatus::Background;
354                    for job in &previous.background_jobs {
355                        if !step.background_jobs.contains(job) {
356                            step.background_jobs.push(job.clone());
357                        }
358                    }
359                    for job in &previous.waited_jobs {
360                        if !step.waited_jobs.contains(job) && !step.background_jobs.contains(job) {
361                            step.waited_jobs.push(job.clone());
362                        }
363                    }
364                    for folder in &previous.made_folders {
365                        if !step.made_folders.contains(folder) {
366                            step.made_folders.push(folder.clone());
367                        }
368                    }
369                    step.started_at = match (step.started_at, previous.started_at) {
370                        (Some(a), Some(b)) => Some(a.min(b)),
371                        (a, b) => a.or(b),
372                    };
373                    step.completed_at = None;
374                }
375            }
376            existing.steps = steps;
377            existing.current_step = current_step;
378            existing.updated_at = now;
379            // Runs whose work the new list no longer names still end: the
380            // steps left open wait on them, so their ends settle the plan.
381            existing.wait_on_background_jobs(&orphaned_jobs);
382            existing.sync_active_step();
383            self.update(&existing).await?;
384            Ok(existing)
385        } else {
386            let mut plan = TaskPlan::new(
387                session_id,
388                trigger,
389                "Requirement checklist",
390                Vec::new(),
391                "track_requirements",
392            );
393            plan.steps = steps;
394            plan.current_step = current_step;
395            plan.task_id = task_id.map(|t| t.to_string());
396            plan.sync_active_step();
397            self.create(&plan).await?;
398            Ok(plan)
399        }
400    }
401
402    /// Hand steps of the session's checklist for `task_id` to the background
403    /// job `job_id` ([`TaskPlan::link_background_job`]). Returns the updated
404    /// plan, or `None` when there is no such checklist or nothing changed.
405    pub async fn link_background_job(
406        &self,
407        session_id: &str,
408        task_id: Option<&str>,
409        indices: &[usize],
410        job_id: &str,
411    ) -> anyhow::Result<Option<TaskPlan>> {
412        self.change_latest(session_id, task_id, |plan| {
413            plan.link_background_job(indices, job_id)
414        })
415        .await
416    }
417
418    /// The helper for the steps at `indices` of the session's checklist for
419    /// `task_id` never started ([`TaskPlan::helper_did_not_start`]).
420    /// Returns the updated plan, or `None` when nothing changed.
421    pub async fn helper_did_not_start(
422        &self,
423        session_id: &str,
424        task_id: Option<&str>,
425        indices: &[usize],
426        reason: &str,
427    ) -> anyhow::Result<Option<TaskPlan>> {
428        self.change_latest(session_id, task_id, |plan| {
429            plan.helper_did_not_start(indices, reason)
430        })
431        .await
432    }
433
434    /// The session's checklist for `task_id`: its latest plan, when that
435    /// plan belongs to the task.
436    pub async fn for_task(
437        &self,
438        session_id: &str,
439        task_id: &str,
440    ) -> anyhow::Result<Option<TaskPlan>> {
441        Ok(self
442            .get_recent_for_session(session_id, 1)
443            .await?
444            .into_iter()
445            .next()
446            .filter(|plan| plan.task_id.as_deref() == Some(task_id)))
447    }
448
449    /// The run's receipts proved the checklist items at `indices` of the
450    /// session's checklist for `task_id` ([`TaskPlan::confirm_steps`]).
451    /// Returns the updated plan, or `None` when nothing changed.
452    pub async fn confirm_steps(
453        &self,
454        session_id: &str,
455        task_id: &str,
456        indices: &std::collections::BTreeSet<usize>,
457    ) -> anyhow::Result<Option<TaskPlan>> {
458        self.change_latest(session_id, Some(task_id), |plan| {
459            plan.confirm_steps(indices)
460        })
461        .await
462    }
463
464    /// Settle the steps at `indices` of the session's checklist for
465    /// `task_id` as not attempted ([`TaskPlan::mark_not_attempted`]).
466    pub async fn mark_not_attempted(
467        &self,
468        session_id: &str,
469        task_id: &str,
470        indices: &std::collections::BTreeSet<usize>,
471    ) -> anyhow::Result<Option<TaskPlan>> {
472        self.change_latest(session_id, Some(task_id), |plan| {
473            plan.mark_not_attempted(indices)
474        })
475        .await
476    }
477
478    /// The session's checklist for `task_id` waits on background jobs
479    /// `job_ids` ([`TaskPlan::wait_on_background_jobs`]). Returns the updated
480    /// plan, or `None` when there is no such checklist or nothing changed.
481    pub async fn wait_on_background_jobs(
482        &self,
483        session_id: &str,
484        task_id: Option<&str>,
485        job_ids: &[String],
486    ) -> anyhow::Result<Option<TaskPlan>> {
487        self.change_latest(session_id, task_id, |plan| {
488            plan.wait_on_background_jobs(job_ids)
489        })
490        .await
491    }
492
493    /// The folders background job `job_id` made, on the session's checklist
494    /// steps it took on ([`TaskPlan::note_job_folders`]).
495    pub async fn note_job_folders(
496        &self,
497        session_id: &str,
498        job_id: &str,
499        folders: &[String],
500    ) -> anyhow::Result<()> {
501        if folders.is_empty() {
502            return Ok(());
503        }
504        let _write = PLAN_WRITES.lock().await;
505        for mut plan in self.get_recent_for_session(session_id, 5).await? {
506            if plan.note_job_folders(job_id, folders) {
507                self.update(&plan).await?;
508                return Ok(());
509            }
510        }
511        Ok(())
512    }
513
514    /// Record the end of background job `job_id` on the session's checklist
515    /// that handed it work ([`TaskPlan::settle_background_job`]). Returns the
516    /// updated plan, or `None` when no checklist step waited on that job.
517    pub async fn settle_background_job(
518        &self,
519        session_id: &str,
520        job_id: &str,
521        end: super::JobEnd,
522    ) -> anyhow::Result<Option<TaskPlan>> {
523        let _write = PLAN_WRITES.lock().await;
524        for mut plan in self.get_recent_for_session(session_id, 5).await? {
525            if plan.settle_background_job(job_id, end) {
526                self.update(&plan).await?;
527                return Ok(Some(plan));
528            }
529        }
530        Ok(None)
531    }
532
533    /// Settle plan `plan_id`'s open steps as not done
534    /// ([`TaskPlan::settle_open_steps`]). Returns the plan as it now stands.
535    pub async fn settle_open_steps(&self, plan_id: &str) -> anyhow::Result<Option<TaskPlan>> {
536        self.modify(plan_id, TaskPlan::settle_open_steps).await
537    }
538
539    /// Update just the status of a plan.
540    pub async fn set_status(&self, plan_id: &str, status: PlanStatus) -> anyhow::Result<()> {
541        let now = Utc::now().to_rfc3339();
542
543        sqlx::query(
544            r#"
545            UPDATE task_plans SET status = ?, updated_at = ? WHERE id = ?
546            "#,
547        )
548        .bind(status.as_str())
549        .bind(&now)
550        .bind(plan_id)
551        .execute(&self.pool)
552        .await?;
553
554        Ok(())
555    }
556
557    /// Set a checkpoint value (merges into existing checkpoint).
558    pub async fn set_checkpoint(
559        &self,
560        plan_id: &str,
561        key: &str,
562        value: serde_json::Value,
563    ) -> anyhow::Result<()> {
564        // Fetch current checkpoint
565        let row = sqlx::query("SELECT checkpoint FROM task_plans WHERE id = ?")
566            .bind(plan_id)
567            .fetch_optional(&self.pool)
568            .await?;
569
570        let mut checkpoint: serde_json::Map<String, serde_json::Value> = match row {
571            Some(r) => {
572                let json_str: String = r.get("checkpoint");
573                serde_json::from_str(&json_str).unwrap_or_default()
574            }
575            None => return Err(anyhow::anyhow!("Plan not found: {}", plan_id)),
576        };
577
578        // Merge new value
579        checkpoint.insert(key.to_string(), value);
580
581        let checkpoint_json = serde_json::to_string(&checkpoint)?;
582        let now = Utc::now().to_rfc3339();
583
584        sqlx::query(
585            r#"
586            UPDATE task_plans SET checkpoint = ?, updated_at = ? WHERE id = ?
587            "#,
588        )
589        .bind(&checkpoint_json)
590        .bind(&now)
591        .bind(plan_id)
592        .execute(&self.pool)
593        .await?;
594
595        Ok(())
596    }
597
598    /// Reconcile a successful tool-call receipt into explicit checklist evidence
599    /// contracts. Step descriptions are display-only and never decide completion.
600    pub async fn reconcile_checklist_after_tool_success(
601        &self,
602        session_id: &str,
603        semantics: &crate::traits::ToolCallSemantics,
604        receipt_id: &str,
605        result: &str,
606    ) -> anyhow::Result<Option<TaskPlan>> {
607        use crate::plans::StepStatus;
608
609        let Some(mut plan) = self.get_incomplete_for_session(session_id).await? else {
610            return Ok(None);
611        };
612
613        let mut changed = false;
614        for step in &mut plan.steps {
615            if !matches!(step.status, StepStatus::Pending | StepStatus::InProgress) {
616                continue;
617            }
618            let has_evidence_contract =
619                !step.required_mutation_effects.is_empty() || step.requires_observation;
620            if !has_evidence_contract {
621                continue;
622            }
623            let effects_match = step.required_mutation_effects.is_empty()
624                || semantics
625                    .mutation_effects
626                    .satisfies(step.required_mutation_effects);
627            let observation_matches = !step.requires_observation || semantics.observes_state();
628            let targets_match = step.expected_targets.is_empty()
629                || step.expected_targets.iter().all(|expected| {
630                    semantics
631                        .target_hints
632                        .iter()
633                        .any(|actual| same_target(&actual.value, expected))
634                });
635
636            if effects_match && observation_matches && targets_match {
637                step.status = StepStatus::Completed;
638                step.evidence = crate::plans::StepEvidence::Settled;
639                step.completed_at = Some(Utc::now());
640                step.result_summary = Some(aidaemon_events::text::truncate_str(result, 200));
641                if !step
642                    .evidence_receipt_ids
643                    .iter()
644                    .any(|existing| existing == receipt_id)
645                {
646                    step.evidence_receipt_ids.push(receipt_id.to_string());
647                }
648                changed = true;
649            }
650        }
651
652        if !changed {
653            return Ok(None);
654        }
655
656        plan.sync_active_step();
657        self.update(&plan).await?;
658        Ok(Some(plan))
659    }
660
661    /// A turn that continues the same request (a runtime continuation, a
662    /// resume, or a turn that adopted the request's open obligations)
663    /// carries the request's open checklist: the session's open plan moves
664    /// to this turn's task, so its card, its helpers' links and its outcome
665    /// all read it. A new request calls nothing here and starts its own
666    /// plan. Returns the carried plan.
667    pub async fn carry_into_turn(
668        &self,
669        session_id: &str,
670        task_id: &str,
671    ) -> anyhow::Result<Option<TaskPlan>> {
672        let _write = PLAN_WRITES.lock().await;
673        let Some(mut plan) = self.get_incomplete_for_session(session_id).await? else {
674            return Ok(None);
675        };
676        if plan.task_id.as_deref() != Some(task_id) {
677            plan.task_id = Some(task_id.to_string());
678            plan.updated_at = Utc::now();
679            self.update(&plan).await?;
680        }
681        Ok(Some(plan))
682    }
683
684    /// Link a plan to a task ID from the event store.
685    pub async fn set_task_id(&self, plan_id: &str, task_id: &str) -> anyhow::Result<()> {
686        let now = Utc::now().to_rfc3339();
687
688        sqlx::query(
689            r#"
690            UPDATE task_plans SET task_id = ?, updated_at = ? WHERE id = ?
691            "#,
692        )
693        .bind(task_id)
694        .bind(&now)
695        .bind(plan_id)
696        .execute(&self.pool)
697        .await?;
698
699        Ok(())
700    }
701
702    // =========================================================================
703    // Read Operations
704    // =========================================================================
705
706    /// Get a plan by ID.
707    pub async fn get(&self, plan_id: &str) -> anyhow::Result<Option<TaskPlan>> {
708        let row = sqlx::query(
709            r#"
710            SELECT id, session_id, description, trigger_message, steps,
711                   current_step, status, checkpoint, creation_reason,
712                   task_id, created_at, updated_at
713            FROM task_plans WHERE id = ?
714            "#,
715        )
716        .bind(plan_id)
717        .fetch_optional(&self.pool)
718        .await?;
719
720        match row {
721            Some(r) => Ok(Some(self.row_to_plan(&r)?)),
722            None => Ok(None),
723        }
724    }
725
726    /// Get the incomplete plan for a session (if any).
727    /// Returns the most recently updated incomplete plan.
728    pub async fn get_incomplete_for_session(
729        &self,
730        session_id: &str,
731    ) -> anyhow::Result<Option<TaskPlan>> {
732        let row = sqlx::query(
733            r#"
734            SELECT id, session_id, description, trigger_message, steps,
735                   current_step, status, checkpoint, creation_reason,
736                   task_id, created_at, updated_at
737            FROM task_plans
738            WHERE session_id = ?
739              AND status IN ('planning', 'in_progress', 'paused')
740            ORDER BY updated_at DESC
741            LIMIT 1
742            "#,
743        )
744        .bind(session_id)
745        .fetch_optional(&self.pool)
746        .await?;
747
748        match row {
749            Some(r) => Ok(Some(self.row_to_plan(&r)?)),
750            None => Ok(None),
751        }
752    }
753
754    /// Get recent plans for a session.
755    pub async fn get_recent_for_session(
756        &self,
757        session_id: &str,
758        limit: usize,
759    ) -> anyhow::Result<Vec<TaskPlan>> {
760        let rows = sqlx::query(
761            r#"
762            SELECT id, session_id, description, trigger_message, steps,
763                   current_step, status, checkpoint, creation_reason,
764                   task_id, created_at, updated_at
765            FROM task_plans
766            WHERE session_id = ?
767            ORDER BY updated_at DESC
768            LIMIT ?
769            "#,
770        )
771        .bind(session_id)
772        .bind(limit as i64)
773        .fetch_all(&self.pool)
774        .await?;
775
776        let mut plans = Vec::new();
777        for row in rows {
778            plans.push(self.row_to_plan(&row)?);
779        }
780        Ok(plans)
781    }
782
783    /// Get all plans that are in progress.
784    pub async fn get_all_in_progress(&self) -> anyhow::Result<Vec<TaskPlan>> {
785        let rows = sqlx::query(
786            r#"
787            SELECT id, session_id, description, trigger_message, steps,
788                   current_step, status, checkpoint, creation_reason,
789                   task_id, created_at, updated_at
790            FROM task_plans
791            WHERE status = 'in_progress'
792            ORDER BY updated_at DESC
793            "#,
794        )
795        .fetch_all(&self.pool)
796        .await?;
797
798        let mut plans = Vec::new();
799        for row in rows {
800            plans.push(self.row_to_plan(&row)?);
801        }
802        Ok(plans)
803    }
804
805    /// Get completed plans since a given time (for consolidation).
806    pub async fn get_completed_since(
807        &self,
808        session_id: &str,
809        since: DateTime<Utc>,
810    ) -> anyhow::Result<Vec<TaskPlan>> {
811        let rows = sqlx::query(
812            r#"
813            SELECT id, session_id, description, trigger_message, steps,
814                   current_step, status, checkpoint, creation_reason,
815                   task_id, created_at, updated_at
816            FROM task_plans
817            WHERE session_id = ?
818              AND status = 'completed'
819              AND updated_at >= ?
820            ORDER BY updated_at DESC
821            "#,
822        )
823        .bind(session_id)
824        .bind(since.to_rfc3339())
825        .fetch_all(&self.pool)
826        .await?;
827
828        let mut plans = Vec::new();
829        for row in rows {
830            plans.push(self.row_to_plan(&row)?);
831        }
832        Ok(plans)
833    }
834
835    // =========================================================================
836    // Cleanup Operations
837    // =========================================================================
838
839    // =========================================================================
840    // Helpers
841    // =========================================================================
842
843    fn row_to_plan(&self, row: &sqlx::sqlite::SqliteRow) -> anyhow::Result<TaskPlan> {
844        let id: String = row.get("id");
845        let session_id: String = row.get("session_id");
846        let description: String = row.get("description");
847        let trigger_message: String = row.get("trigger_message");
848        let steps_json: String = row.get("steps");
849        let current_step: i64 = row.get("current_step");
850        let status_str: String = row.get("status");
851        let checkpoint_json: String = row.get("checkpoint");
852        let creation_reason: String = row.get("creation_reason");
853        let task_id: Option<String> = row.get("task_id");
854        let created_at_str: String = row.get("created_at");
855        let updated_at_str: String = row.get("updated_at");
856
857        let steps = steps_from_json(&steps_json)?;
858        let checkpoint = serde_json::from_str(&checkpoint_json)?;
859        let status = PlanStatus::from_str(&status_str).unwrap_or(PlanStatus::InProgress);
860        let created_at = DateTime::parse_from_rfc3339(&created_at_str)?.with_timezone(&Utc);
861        let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)?.with_timezone(&Utc);
862
863        Ok(TaskPlan {
864            id,
865            session_id,
866            description,
867            trigger_message,
868            steps,
869            current_step: current_step as usize,
870            status,
871            checkpoint,
872            creation_reason,
873            task_id,
874            created_at,
875            updated_at,
876        })
877    }
878}
879
880/// Creates the `task_plans` table and its indexes; idempotent.
881pub async fn migrate_task_plans(pool: &SqlitePool) -> anyhow::Result<()> {
882    // Create task_plans table
883    sqlx::query(
884        r#"
885        CREATE TABLE IF NOT EXISTS task_plans (
886            id TEXT PRIMARY KEY,
887            session_id TEXT NOT NULL,
888            description TEXT NOT NULL,
889            trigger_message TEXT NOT NULL,
890            steps TEXT NOT NULL,
891            current_step INTEGER NOT NULL DEFAULT 0,
892            status TEXT NOT NULL DEFAULT 'in_progress',
893            checkpoint TEXT NOT NULL DEFAULT '{}',
894            creation_reason TEXT NOT NULL,
895            task_id TEXT,
896            created_at TEXT NOT NULL,
897            updated_at TEXT NOT NULL
898        )
899        "#,
900    )
901    .execute(pool)
902    .await?;
903
904    // Index for finding incomplete plans for a session
905    sqlx::query(
906        r#"
907        CREATE INDEX IF NOT EXISTS idx_plans_session_status
908        ON task_plans(session_id, status)
909        "#,
910    )
911    .execute(pool)
912    .await?;
913
914    // Index for cleanup of old completed plans
915    sqlx::query(
916        r#"
917        CREATE INDEX IF NOT EXISTS idx_plans_updated
918        ON task_plans(updated_at)
919        "#,
920    )
921    .execute(pool)
922    .await?;
923
924    tracing::info!("Task plans table migration complete");
925    Ok(())
926}
927
928/// A plan's steps as stored. Rows written before steps carried a typed
929/// [`crate::plans::StepEvidence`] kept it as two flags (`said_done`,
930/// `helper_not_started`); they read as the evidence they meant.
931fn steps_from_json(json: &str) -> anyhow::Result<Vec<crate::plans::PlanStep>> {
932    use crate::plans::StepEvidence;
933    let mut raw: Vec<serde_json::Value> = serde_json::from_str(json)?;
934    for step in &mut raw {
935        let Some(fields) = step.as_object_mut() else {
936            continue;
937        };
938        let flag = |fields: &mut serde_json::Map<String, serde_json::Value>, name: &str| {
939            fields
940                .remove(name)
941                .and_then(|value| value.as_bool())
942                .unwrap_or(false)
943        };
944        let said_done = flag(fields, "said_done");
945        let not_started = flag(fields, "helper_not_started");
946        // Rows written before a step kept the jobs it waits on apart listed
947        // them as its own jobs under a `waits_on_jobs` flag.
948        if flag(fields, "waits_on_jobs") && !fields.contains_key("waited_jobs") {
949            let jobs = fields
950                .remove("background_jobs")
951                .unwrap_or_else(|| serde_json::Value::Array(Vec::new()));
952            fields.insert("waited_jobs".to_string(), jobs);
953        }
954        if fields.contains_key("evidence") {
955            continue;
956        }
957        let evidence = if not_started {
958            StepEvidence::HelperNotStarted
959        } else if said_done {
960            StepEvidence::ModelSaid
961        } else {
962            continue;
963        };
964        fields.insert("evidence".to_string(), serde_json::to_value(evidence)?);
965    }
966    raw.into_iter()
967        .map(|step| serde_json::from_value(step).map_err(anyhow::Error::from))
968        .collect()
969}
970
971/// Whether a receipt's target is the step's expected one: the same text, or
972/// the same existing file however each was written (a Windows short name
973/// such as `RUNNER~1` against its long form, a link against its target).
974fn same_target(actual: &str, expected: &str) -> bool {
975    if actual == expected {
976        return true;
977    }
978    match (dunce::canonicalize(actual), dunce::canonicalize(expected)) {
979        (Ok(actual), Ok(expected)) => actual == expected,
980        _ => false,
981    }
982}
983
984#[cfg(test)]
985mod tests {
986    use super::*;
987    use sqlx::sqlite::SqlitePoolOptions;
988
989    async fn create_test_store() -> PlanStore {
990        let pool = SqlitePoolOptions::new()
991            .max_connections(1)
992            .connect("sqlite::memory:")
993            .await
994            .unwrap();
995        PlanStore::new(pool).await.unwrap()
996    }
997
998    /// A step the model ticks is done on its word. A check or a read needs
999    /// no receipt: the reply reports what it found, so the card shows it
1000    /// done with no note. Only an action step that declared a side effect
1001    /// and that nothing verified is flagged, in plain words; evidence (a
1002    /// receipt, a helper's success) clears the flag, and an update ticking
1003    /// the step again keeps the proof (live 2026-11-13: "Finished · 3 of 3
1004    /// done, 1 not confirmed by a tool" on a read-only check).
1005    #[tokio::test]
1006    async fn only_an_action_step_nothing_verified_is_flagged() {
1007        use crate::plans::{ChecklistItem, StepEvidence, StepStatus};
1008        use crate::traits::ToolMutationEffects;
1009        let store = create_test_store().await;
1010        let item = |text: &str, effects: ToolMutationEffects, status: StepStatus| ChecklistItem {
1011            description: text.to_string(),
1012            status,
1013            depends_on: Vec::new(),
1014            required_mutation_effects: effects,
1015            requires_observation: false,
1016            expected_targets: Vec::new(),
1017            owner_units: Vec::new(),
1018        };
1019        let ticked = |done: bool| {
1020            let status = if done {
1021                StepStatus::Completed
1022            } else {
1023                StepStatus::Pending
1024            };
1025            vec![
1026                item(
1027                    "Check whether ~/projects/claude-test-a.txt is already occupied",
1028                    ToolMutationEffects::NONE,
1029                    status,
1030                ),
1031                item(
1032                    "Write the letters file",
1033                    ToolMutationEffects::LOCAL_WORKSPACE_WRITE,
1034                    status,
1035                ),
1036                item(
1037                    "Report both",
1038                    ToolMutationEffects::NONE,
1039                    StepStatus::InProgress,
1040                ),
1041            ]
1042        };
1043        store
1044            .upsert_checklist_graph("s1", Some("t1"), "test", &ticked(false))
1045            .await
1046            .unwrap();
1047        let plan = store
1048            .upsert_checklist_graph("s1", Some("t1"), "test", &ticked(true))
1049            .await
1050            .unwrap();
1051        let card = plan.render_compact_checklist();
1052        assert!(card.starts_with("⚙️ Working · step 3 of 3"), "{card}");
1053        assert!(
1054            card.contains("✅ Check whether ~/projects/claude-test-a.txt is already occupied\n"),
1055            "{card}"
1056        );
1057        assert!(
1058            card.contains("☑️ Write the letters file (I couldn't verify this one)"),
1059            "{card}"
1060        );
1061        assert_eq!(plan.unverified_steps(), 1);
1062
1063        let proven = std::collections::BTreeSet::from([0]);
1064        store.confirm_steps("s1", "t1", &proven).await.unwrap();
1065        let plan = store
1066            .upsert_checklist_graph("s1", Some("t1"), "test", &ticked(true))
1067            .await
1068            .unwrap();
1069        assert_eq!(
1070            plan.steps[0].evidence,
1071            StepEvidence::Settled,
1072            "a later tick keeps the proof"
1073        );
1074        assert_eq!(plan.steps[1].evidence, StepEvidence::ModelSaid);
1075
1076        store
1077            .link_background_job("s1", Some("t1"), &[2], "job-1")
1078            .await
1079            .unwrap()
1080            .unwrap();
1081        let plan = store
1082            .settle_background_job("s1", "job-1", crate::plans::JobEnd::Succeeded)
1083            .await
1084            .unwrap()
1085            .unwrap();
1086        let card = plan.render_compact_checklist();
1087        assert!(
1088            card.starts_with("☑️ Finished · 3 of 3 done; I couldn't verify 1"),
1089            "{card}"
1090        );
1091        assert!(card.contains("✅ Report both"), "{card}");
1092        assert!(!crate::plans::is_completed_checklist(&card), "{card}");
1093        assert!(!card.to_lowercase().contains("tool"), "{card}");
1094
1095        // Every step a check: done, with nothing to flag.
1096        let checks = vec![item(
1097            "Check the first site",
1098            ToolMutationEffects::NONE,
1099            StepStatus::Completed,
1100        )];
1101        let plan = store
1102            .upsert_checklist_graph("s2", Some("t2"), "test", &checks)
1103            .await
1104            .unwrap();
1105        assert_eq!(plan.render_compact_checklist(), "✅ Check the first site");
1106    }
1107
1108    /// Rows stored before steps carried typed evidence read as the
1109    /// evidence their flags meant.
1110    #[test]
1111    fn legacy_step_flags_read_as_typed_evidence() {
1112        use crate::plans::StepEvidence;
1113        let mut plan = TaskPlan::new("s", "t", "d", vec!["a".into(), "b".into(), "c".into()], "r");
1114        plan.steps[0].evidence = StepEvidence::ModelSaid;
1115        let mut raw = serde_json::to_value(&plan.steps).unwrap();
1116        let steps = raw.as_array_mut().unwrap();
1117        steps[0].as_object_mut().unwrap().remove("evidence");
1118        steps[0]["said_done"] = true.into();
1119        steps[1]["helper_not_started"] = true.into();
1120        let read = steps_from_json(&raw.to_string()).unwrap();
1121        assert_eq!(read[0].evidence, StepEvidence::ModelSaid);
1122        assert_eq!(read[1].evidence, StepEvidence::HelperNotStarted);
1123        assert_eq!(read[2].evidence, StepEvidence::Settled);
1124    }
1125
1126    /// Rows stored before a step kept the jobs it only waits on apart read
1127    /// those jobs as waited on, never as its own.
1128    #[test]
1129    fn legacy_waiting_flag_reads_as_waited_jobs() {
1130        let plan = TaskPlan::new("s", "t", "d", vec!["a".into(), "b".into()], "r");
1131        let mut raw = serde_json::to_value(&plan.steps).unwrap();
1132        let steps = raw.as_array_mut().unwrap();
1133        steps[0]["background_jobs"] = serde_json::json!(["job-a"]);
1134        steps[0]["waits_on_jobs"] = true.into();
1135        steps[1]["background_jobs"] = serde_json::json!(["job-b"]);
1136        let read = steps_from_json(&raw.to_string()).unwrap();
1137        assert!(read[0].background_jobs.is_empty());
1138        assert_eq!(read[0].waited_jobs, vec!["job-a".to_string()]);
1139        assert_eq!(read[1].background_jobs, vec!["job-b".to_string()]);
1140        assert!(read[1].waited_jobs.is_empty());
1141    }
1142
1143    /// A step whose helper never started is not done, the finished card says
1144    /// plainly that it didn't run, and a later launch for it takes it again.
1145    #[tokio::test]
1146    async fn a_step_whose_helper_did_not_start_reads_as_not_run_until_one_does() {
1147        use crate::plans::StepStatus;
1148        let store = create_test_store().await;
1149        let items = vec![
1150            ("Install the first site".to_string(), StepStatus::InProgress),
1151            ("Install the second site".to_string(), StepStatus::Pending),
1152        ];
1153        store
1154            .upsert_checklist("s1", Some("t1"), "test", &items)
1155            .await
1156            .unwrap();
1157        store
1158            .link_background_job("s1", Some("t1"), &[0], "job-1")
1159            .await
1160            .unwrap()
1161            .unwrap();
1162        store
1163            .helper_did_not_start("s1", Some("t1"), &[1], "its helper didn't start")
1164            .await
1165            .unwrap()
1166            .unwrap();
1167        let plan = store
1168            .settle_background_job("s1", "job-1", crate::plans::JobEnd::Succeeded)
1169            .await
1170            .unwrap()
1171            .unwrap();
1172        let card = plan.render_compact_checklist();
1173        assert!(card.starts_with("❌ Stopped · 1 of 2 done"), "{card}");
1174        assert!(
1175            card.contains("⚠️ Install the second site (didn't run)"),
1176            "{card}"
1177        );
1178        // Why is said once, under the rows.
1179        assert!(
1180            card.ends_with("Didn't run: its helper didn't start."),
1181            "{card}"
1182        );
1183        assert_eq!(card.matches("helper didn't start").count(), 1, "{card}");
1184
1185        let plan = store
1186            .link_background_job("s1", Some("t1"), &[1], "job-2")
1187            .await
1188            .unwrap()
1189            .expect("a retried launch takes the step");
1190        assert_eq!(plan.steps[1].status, StepStatus::Background);
1191        assert!(!plan.steps[1].helper_not_started());
1192        assert_eq!(plan.status, PlanStatus::InProgress);
1193    }
1194
1195    #[tokio::test]
1196    async fn typed_receipt_completes_only_its_exact_checklist_contract() {
1197        use crate::plans::{ChecklistItem, StepStatus};
1198        use crate::traits::{ToolCallSemantics, ToolMutationEffects, ToolTargetHintKind};
1199        let store = create_test_store().await;
1200        store
1201            .upsert_checklist_graph(
1202                "s1",
1203                None,
1204                "test",
1205                &[ChecklistItem {
1206                    description: "Opaque synthetic requirement".into(),
1207                    status: StepStatus::Pending,
1208                    depends_on: Vec::new(),
1209                    required_mutation_effects: ToolMutationEffects::EXTERNAL_DELIVERY,
1210                    requires_observation: false,
1211                    expected_targets: vec!["/tmp/report.pdf".into()],
1212                    owner_units: Vec::new(),
1213                }],
1214            )
1215            .await
1216            .unwrap();
1217
1218        let wrong_target = ToolCallSemantics::mutation_with(ToolMutationEffects::EXTERNAL_DELIVERY)
1219            .with_target_hint(ToolTargetHintKind::Path, "/tmp/other.pdf");
1220        assert!(
1221            store
1222                .reconcile_checklist_after_tool_success(
1223                    "s1",
1224                    &wrong_target,
1225                    "receipt-wrong",
1226                    "delivered",
1227                )
1228                .await
1229                .unwrap()
1230                .is_none()
1231        );
1232
1233        let exact = ToolCallSemantics::mutation_with(ToolMutationEffects::EXTERNAL_DELIVERY)
1234            .with_target_hint(ToolTargetHintKind::Path, "/tmp/report.pdf");
1235        store
1236            .reconcile_checklist_after_tool_success("s1", &exact, "receipt-exact", "delivered")
1237            .await
1238            .unwrap();
1239
1240        let plan = store
1241            .get_recent_for_session("s1", 1)
1242            .await
1243            .unwrap()
1244            .pop()
1245            .unwrap();
1246        assert_eq!(plan.steps[0].status, StepStatus::Completed);
1247        assert_eq!(plan.steps[0].evidence_receipt_ids, vec!["receipt-exact"]);
1248        assert_eq!(plan.status, PlanStatus::Completed);
1249    }
1250
1251    #[tokio::test]
1252    async fn checklist_prose_cannot_complete_without_a_typed_evidence_contract() {
1253        use crate::plans::StepStatus;
1254        use crate::traits::{ToolCallSemantics, ToolMutationEffects};
1255        let store = create_test_store().await;
1256        store
1257            .upsert_checklist(
1258                "s1",
1259                None,
1260                "test",
1261                &[("Send the report file now".into(), StepStatus::Pending)],
1262            )
1263            .await
1264            .unwrap();
1265        let delivery = ToolCallSemantics::mutation_with(ToolMutationEffects::EXTERNAL_DELIVERY);
1266        assert!(
1267            store
1268                .reconcile_checklist_after_tool_success("s1", &delivery, "receipt-1", "delivered",)
1269                .await
1270                .unwrap()
1271                .is_none()
1272        );
1273    }
1274
1275    #[tokio::test]
1276    async fn test_upsert_checklist_creates_then_replaces() {
1277        use crate::plans::StepStatus;
1278        let store = create_test_store().await;
1279        let items = vec![
1280            ("create script".to_string(), StepStatus::InProgress),
1281            ("send the file".to_string(), StepStatus::Pending),
1282        ];
1283        let plan = store
1284            .upsert_checklist("sess-1", Some("task-1"), "make+send", &items)
1285            .await
1286            .unwrap();
1287        assert_eq!(plan.steps.len(), 2);
1288        let id = plan.id.clone();
1289
1290        let items2 = vec![
1291            ("create script".to_string(), StepStatus::Completed),
1292            ("send the file".to_string(), StepStatus::Completed),
1293        ];
1294        let plan2 = store
1295            .upsert_checklist("sess-1", Some("task-1"), "make+send", &items2)
1296            .await
1297            .unwrap();
1298        assert_eq!(
1299            plan2.id, id,
1300            "should update existing plan, not create a new one"
1301        );
1302        assert_eq!(plan2.completed_steps(), 2);
1303
1304        // Persisted state reflects the replacement.
1305        let fetched = store.get(&id).await.unwrap().unwrap();
1306        assert_eq!(fetched.completed_steps(), 2);
1307    }
1308
1309    /// Each owner request gets its own plan: a new request's checklist
1310    /// never reuses (or shows) an earlier request's open plan, while a turn
1311    /// that continues the request carries it (live 2026-11-14: a new
1312    /// request's card showed "✅ Install WordPress … verify the site").
1313    #[tokio::test]
1314    async fn a_new_request_gets_its_own_plan_and_a_continuation_carries_it() {
1315        use crate::plans::StepStatus;
1316        let store = create_test_store().await;
1317        let earlier = store
1318            .upsert_checklist(
1319                "chat",
1320                Some("request-1"),
1321                "wp",
1322                &[
1323                    (
1324                        "Install WordPress and verify the site".to_string(),
1325                        StepStatus::Completed,
1326                    ),
1327                    ("Send the login link".to_string(), StepStatus::Pending),
1328                ],
1329            )
1330            .await
1331            .unwrap();
1332
1333        let fresh = store
1334            .upsert_checklist(
1335                "chat",
1336                Some("request-2"),
1337                "drupal",
1338                &[
1339                    ("Install Drupal".to_string(), StepStatus::InProgress),
1340                    ("Verify Drupal".to_string(), StepStatus::Pending),
1341                ],
1342            )
1343            .await
1344            .unwrap();
1345        assert_ne!(fresh.id, earlier.id, "a new request starts its own plan");
1346        let card = fresh.card().text;
1347        assert!(!card.contains("WordPress"), "{card}");
1348        let kept = store.get(&earlier.id).await.unwrap().unwrap();
1349        assert_eq!(kept.task_id.as_deref(), Some("request-1"));
1350        assert_eq!(kept.steps.len(), 2);
1351
1352        // A later turn of request 2 carries its plan.
1353        let carried = store
1354            .carry_into_turn("chat", "request-2-turn-2")
1355            .await
1356            .unwrap()
1357            .unwrap();
1358        assert_eq!(carried.id, fresh.id);
1359        let again = store
1360            .upsert_checklist(
1361                "chat",
1362                Some("request-2-turn-2"),
1363                "drupal",
1364                &[
1365                    ("Install Drupal".to_string(), StepStatus::Completed),
1366                    ("Verify Drupal".to_string(), StepStatus::InProgress),
1367                ],
1368            )
1369            .await
1370            .unwrap();
1371        assert_eq!(again.id, fresh.id);
1372        assert!(
1373            store
1374                .for_task("chat", "request-2-turn-2")
1375                .await
1376                .unwrap()
1377                .is_some()
1378        );
1379    }
1380
1381    #[tokio::test]
1382    async fn test_create_and_get() {
1383        let store = create_test_store().await;
1384
1385        let plan = TaskPlan::new(
1386            "session_123",
1387            "Deploy the app",
1388            "Production deployment",
1389            vec![
1390                "Test".to_string(),
1391                "Build".to_string(),
1392                "Deploy".to_string(),
1393            ],
1394            "high_stakes",
1395        );
1396
1397        store.create(&plan).await.unwrap();
1398
1399        let retrieved = store.get(&plan.id).await.unwrap().unwrap();
1400        assert_eq!(retrieved.id, plan.id);
1401        assert_eq!(retrieved.description, "Production deployment");
1402        assert_eq!(retrieved.steps.len(), 3);
1403    }
1404
1405    #[tokio::test]
1406    async fn test_get_incomplete_for_session() {
1407        let store = create_test_store().await;
1408
1409        // Create a completed plan
1410        let mut plan1 = TaskPlan::new(
1411            "session_123",
1412            "Task 1",
1413            "First task",
1414            vec!["Step".to_string()],
1415            "test",
1416        );
1417        plan1.status = PlanStatus::Completed;
1418        store.create(&plan1).await.unwrap();
1419
1420        // Create an in-progress plan
1421        let plan2 = TaskPlan::new(
1422            "session_123",
1423            "Task 2",
1424            "Second task",
1425            vec!["Step".to_string()],
1426            "test",
1427        );
1428        store.create(&plan2).await.unwrap();
1429
1430        // Should find the in-progress plan
1431        let incomplete = store
1432            .get_incomplete_for_session("session_123")
1433            .await
1434            .unwrap();
1435        assert!(incomplete.is_some());
1436        assert_eq!(incomplete.unwrap().description, "Second task");
1437
1438        // Different session should find nothing
1439        let other = store
1440            .get_incomplete_for_session("session_456")
1441            .await
1442            .unwrap();
1443        assert!(other.is_none());
1444    }
1445
1446    #[tokio::test]
1447    async fn test_update_status() {
1448        let store = create_test_store().await;
1449
1450        let plan = TaskPlan::new(
1451            "session_123",
1452            "Test",
1453            "Test task",
1454            vec!["Step".to_string()],
1455            "test",
1456        );
1457        store.create(&plan).await.unwrap();
1458
1459        store
1460            .set_status(&plan.id, PlanStatus::Paused)
1461            .await
1462            .unwrap();
1463
1464        let retrieved = store.get(&plan.id).await.unwrap().unwrap();
1465        assert_eq!(retrieved.status, PlanStatus::Paused);
1466    }
1467
1468    #[tokio::test]
1469    async fn test_checkpoint() {
1470        let store = create_test_store().await;
1471
1472        let plan = TaskPlan::new(
1473            "session_123",
1474            "Test",
1475            "Test task",
1476            vec!["Step".to_string()],
1477            "test",
1478        );
1479        store.create(&plan).await.unwrap();
1480
1481        store
1482            .set_checkpoint(&plan.id, "image_tag", serde_json::json!("v1.2.3"))
1483            .await
1484            .unwrap();
1485        store
1486            .set_checkpoint(&plan.id, "commit_sha", serde_json::json!("abc123"))
1487            .await
1488            .unwrap();
1489
1490        let retrieved = store.get(&plan.id).await.unwrap().unwrap();
1491        assert_eq!(retrieved.checkpoint["image_tag"], "v1.2.3");
1492        assert_eq!(retrieved.checkpoint["commit_sha"], "abc123");
1493    }
1494
1495    /// A checklist update cannot settle a step a background job is doing:
1496    /// it stays with the job until the job ends.
1497    #[tokio::test]
1498    async fn checklist_update_keeps_steps_a_background_job_is_doing() {
1499        use crate::plans::StepStatus;
1500        let store = create_test_store().await;
1501        let items = |status: StepStatus| {
1502            vec![
1503                ("inspect".to_string(), StepStatus::Completed),
1504                ("set up".to_string(), status),
1505            ]
1506        };
1507        store
1508            .upsert_checklist(
1509                "s",
1510                Some("t"),
1511                "track_requirements",
1512                &items(StepStatus::Pending),
1513            )
1514            .await
1515            .unwrap();
1516        store
1517            .link_background_job("s", Some("t"), &[1], "job-a")
1518            .await
1519            .unwrap()
1520            .expect("linked");
1521
1522        let plan = store
1523            .upsert_checklist(
1524                "s",
1525                Some("t"),
1526                "track_requirements",
1527                &items(StepStatus::Deferred),
1528            )
1529            .await
1530            .unwrap();
1531        assert_eq!(plan.steps[1].status, StepStatus::Background);
1532        assert_eq!(plan.steps[1].background_jobs, vec!["job-a".to_string()]);
1533
1534        let plan = store
1535            .settle_background_job("s", "job-a", crate::plans::JobEnd::Succeeded)
1536            .await
1537            .unwrap()
1538            .expect("settled");
1539        assert_eq!(plan.steps[1].status, StepStatus::Completed);
1540        assert_eq!(plan.status, PlanStatus::Completed);
1541    }
1542
1543    /// Live 2026-11-14: the plan listed the installs and a screenshot of
1544    /// each site; one call launched a helper per site, each taking on its
1545    /// install by the owner's unit; then the turn re-declared the plan in
1546    /// the helpers' words, rows moved. Each install row keeps its run, the
1547    /// screenshot waits on both, and the last run's end settles the plan
1548    /// done, no row left running.
1549    #[tokio::test]
1550    async fn a_re_declared_plan_keeps_each_step_with_its_run_and_settles_done() {
1551        use crate::plans::{ChecklistItem, JobEnd, StepStatus};
1552        let store = create_test_store().await;
1553        let item = |text: &str, units: &[usize], status: StepStatus| ChecklistItem {
1554            description: text.to_string(),
1555            status,
1556            depends_on: Vec::new(),
1557            required_mutation_effects: crate::traits::ToolMutationEffects::LOCAL_WORKSPACE_WRITE,
1558            requires_observation: false,
1559            expected_targets: Vec::new(),
1560            owner_units: units.to_vec(),
1561        };
1562        let plan = store
1563            .upsert_checklist_graph(
1564                "s",
1565                Some("t"),
1566                "track_requirements",
1567                &[
1568                    item(
1569                        "Install your Claude-company Drupal site",
1570                        &[0],
1571                        StepStatus::Pending,
1572                    ),
1573                    item(
1574                        "Install your Claude-company WordPress site",
1575                        &[1],
1576                        StepStatus::Pending,
1577                    ),
1578                    item(
1579                        "Capture a homepage screenshot of each site",
1580                        &[0, 1],
1581                        StepStatus::Pending,
1582                    ),
1583                ],
1584            )
1585            .await
1586            .unwrap();
1587        // Each launch names an item this plan doesn't list, and its unit.
1588        let drupal = plan.launch_steps(&[7], &[0]);
1589        let wordpress = plan.launch_steps(&[], &[1]);
1590        assert_eq!((drupal.clone(), wordpress.clone()), (vec![0], vec![1]));
1591        store
1592            .link_background_job("s", Some("t"), &drupal, "job-d")
1593            .await
1594            .unwrap();
1595        let plan = store
1596            .link_background_job("s", Some("t"), &wordpress, "job-w")
1597            .await
1598            .unwrap()
1599            .expect("linked");
1600        assert_eq!(plan.steps[2].status, StepStatus::Background);
1601        assert_eq!(plan.steps[2].waited_jobs, vec!["job-d", "job-w"]);
1602
1603        let plan = store
1604            .upsert_checklist_graph(
1605                "s",
1606                Some("t"),
1607                "track_requirements",
1608                &[
1609                    item("Check DDEV", &[], StepStatus::Completed),
1610                    item(
1611                        "Install Claude company WordPress in wp-2",
1612                        &[1],
1613                        StepStatus::Background,
1614                    ),
1615                    item(
1616                        "Install Claude company Drupal in drupal-2",
1617                        &[0],
1618                        StepStatus::Background,
1619                    ),
1620                    item(
1621                        "Capture a homepage screenshot of each site",
1622                        &[0, 1],
1623                        StepStatus::Pending,
1624                    ),
1625                ],
1626            )
1627            .await
1628            .unwrap();
1629        assert_eq!(
1630            plan.steps.len(),
1631            4,
1632            "a re-declaration adds no row for work it lists"
1633        );
1634        assert_eq!(plan.steps[1].background_jobs, vec!["job-w"]);
1635        assert_eq!(plan.steps[2].background_jobs, vec!["job-d"]);
1636        assert_eq!(plan.steps[3].waited_jobs, vec!["job-d", "job-w"]);
1637
1638        store
1639            .settle_background_job("s", "job-d", JobEnd::Succeeded)
1640            .await
1641            .unwrap()
1642            .expect("settled");
1643        let plan = store
1644            .settle_background_job("s", "job-w", JobEnd::Succeeded)
1645            .await
1646            .unwrap()
1647            .expect("settled");
1648        assert!(
1649            plan.steps
1650                .iter()
1651                .all(|step| step.status == StepStatus::Completed),
1652            "{:?}",
1653            plan.steps
1654                .iter()
1655                .map(|step| step.status)
1656                .collect::<Vec<_>>()
1657        );
1658        assert_eq!(plan.status, PlanStatus::Completed);
1659    }
1660
1661    /// Live 2026-11-13: the model marked the two helper steps "background",
1662    /// then one `spawn_agent` batch started both helpers without naming
1663    /// steps. The marked steps take both launches (the launches link
1664    /// concurrently and neither link is lost), and both runs' success
1665    /// settles them done: the card's header says done, as its total does.
1666    #[tokio::test]
1667    async fn a_batch_of_two_delegated_steps_settles_done_from_both_runs() {
1668        use crate::plans::{ChecklistItem, JobEnd, StepStatus};
1669        use std::sync::Arc;
1670        let store = Arc::new(create_test_store().await);
1671        let item = |text: &str, status: StepStatus| ChecklistItem {
1672            description: text.to_string(),
1673            status,
1674            depends_on: Vec::new(),
1675            // The helpers' steps change their sites; the check and the
1676            // report change nothing.
1677            required_mutation_effects: if status == StepStatus::Background {
1678                crate::traits::ToolMutationEffects::LOCAL_WORKSPACE_WRITE
1679            } else {
1680                crate::traits::ToolMutationEffects::NONE
1681            },
1682            requires_observation: false,
1683            expected_targets: Vec::new(),
1684            owner_units: Vec::new(),
1685        };
1686        store
1687            .upsert_checklist_graph(
1688                "chat",
1689                Some("t"),
1690                "track_requirements",
1691                &[
1692                    item("Check both sites", StepStatus::Completed),
1693                    item(
1694                        "Have a helper finish the Drupal site",
1695                        StepStatus::Background,
1696                    ),
1697                    item(
1698                        "Have a helper finish the WordPress site",
1699                        StepStatus::Background,
1700                    ),
1701                    item("Report each helper's result", StepStatus::Pending),
1702                ],
1703            )
1704            .await
1705            .unwrap();
1706        let jobs = ["job-drupal", "job-wordpress"].map(|job| vec![job.to_string()]);
1707        let (first, second) = tokio::join!(
1708            store.wait_on_background_jobs("chat", Some("t"), &jobs[0]),
1709            store.wait_on_background_jobs("chat", Some("t"), &jobs[1]),
1710        );
1711        assert!(first.unwrap().is_some() && second.unwrap().is_some());
1712        let plan = store.for_task("chat", "t").await.unwrap().unwrap();
1713        for (index, step) in plan.steps.iter().enumerate().skip(1) {
1714            assert_eq!(step.status, StepStatus::Background, "step {index}");
1715            assert_eq!(
1716                step.waited_jobs,
1717                vec!["job-drupal".to_string(), "job-wordpress".to_string()],
1718                "step {index} waits on both launches"
1719            );
1720        }
1721        assert!(
1722            plan.card()
1723                .text
1724                .starts_with("⏳ Continuing in the background · 1 of 4 done")
1725        );
1726
1727        let plan = store
1728            .settle_background_job("chat", "job-drupal", JobEnd::Succeeded)
1729            .await
1730            .unwrap()
1731            .unwrap();
1732        assert_eq!(
1733            plan.steps[1].status,
1734            StepStatus::Background,
1735            "one run still runs"
1736        );
1737        let plan = store
1738            .settle_background_job("chat", "job-wordpress", JobEnd::Succeeded)
1739            .await
1740            .unwrap()
1741            .unwrap();
1742        assert!(
1743            plan.steps
1744                .iter()
1745                .all(|step| step.status == StepStatus::Completed)
1746        );
1747        assert_eq!(plan.status, PlanStatus::Completed);
1748        let card = plan.card().text;
1749        assert!(card.starts_with("✅ Done · 4 of 4 steps"), "{card}");
1750        assert!(!card.contains("not done"), "{card}");
1751    }
1752}