Skip to main content

agentstategraph_tasks/
store.rs

1//! `TaskStore` — handle bound to a `Repository` + path prefix.
2//!
3//! All task and plan operations go through a `TaskStore`. Writes are
4//! committed to the repository with `IntentCategory::Plan`, so plan
5//! activity is natively filterable in log and blame queries. Multi-path
6//! transitions (e.g. `complete_task` updating the task and the plan's
7//! `_meta` together) use the speculation API so they land in a single
8//! commit.
9
10use std::collections::{HashMap, HashSet};
11use std::sync::Arc;
12
13use agentstategraph::{CallContext, CommitOptions, RepoError, Repository};
14use agentstategraph_core::IntentCategory;
15use chrono::Utc;
16use once_cell::sync::Lazy;
17use regex::Regex;
18
19/// Canonical blocker id pattern: `t-` followed by 1..9 digits. Validated
20/// at the substrate layer so malformed blocker ids (path-traversal
21/// attempts, nonsense strings) never reach the tree walker.
22static BLOCKER_ID_RE: Lazy<Regex> =
23    Lazy::new(|| Regex::new(r"^t-\d{1,9}$").expect("static blocker-id regex must compile"));
24
25fn validate_blocker_ids(blockers: &[TaskId]) -> Result<(), TaskStoreError> {
26    for b in blockers {
27        if !BLOCKER_ID_RE.is_match(&b.0) {
28            return Err(TaskStoreError::InvalidBlockerId(b.0.clone()));
29        }
30    }
31    Ok(())
32}
33
34/// Notes as a task stores them: blank text (empty or only whitespace) is no
35/// notes, anything else is kept exactly as given, up to [`MAX_NOTES_BYTES`].
36fn normalize_notes(notes: Option<&str>) -> Result<Option<String>, TaskStoreError> {
37    match notes {
38        None => Ok(None),
39        Some(text) if text.trim().is_empty() => Ok(None),
40        Some(text) if text.len() > MAX_NOTES_BYTES => Err(TaskStoreError::NotesTooLong {
41            len: text.len(),
42            max: MAX_NOTES_BYTES,
43        }),
44        Some(text) => Ok(Some(text.to_string())),
45    }
46}
47
48use crate::error::TaskStoreError;
49use crate::paths;
50use crate::state::{Transition, check_transition};
51use crate::types::{
52    MAX_NOTES_BYTES, OnCompleteHook, Plan, PlanStatus, Priority, Proof, Task, TaskId, TaskStatus,
53};
54use crate::verifier::{Verifier, VerifyEntry, VerifyReport};
55
56/// Optional extension fields for [`TaskStore::add_task_with_extensions`].
57///
58/// - `payload`: opaque JSON the task carries for a downstream consumer.
59///   The `-tasks` crate does not interpret it.
60/// - `parent_change`: identifier of the change this task gates, when
61///   created from a deferred `ChangeProposal`.
62/// - `on_complete`: hook the consumer dispatches when the task transitions
63///   to `Done`. The `-tasks` crate does not execute it.
64/// - `notes`: the task's notes, as [`TaskStore::set_notes`] takes them.
65///   Blank text is no notes; more than [`MAX_NOTES_BYTES`] is refused.
66#[derive(Default)]
67pub struct AddTaskOptions {
68    pub payload: Option<serde_json::Value>,
69    pub parent_change: Option<String>,
70    pub on_complete: Option<OnCompleteHook>,
71    pub notes: Option<String>,
72}
73
74/// A handle bound to a `Repository` and a path prefix. All operations on
75/// plans and tasks go through a `TaskStore`.
76pub struct TaskStore {
77    repo: Arc<Repository>,
78    prefix: String,
79    context: CallContext,
80}
81
82impl TaskStore {
83    /// Create a new task store bound to a path prefix in the given
84    /// repository. The prefix must NOT end with a slash.
85    ///
86    /// `agent_id` is used as the commit author for every task operation.
87    /// Same as [`TaskStore::with_context`] with `CallContext::new(agent_id)`.
88    pub fn new(
89        repo: Arc<Repository>,
90        prefix: impl Into<String>,
91        agent_id: impl Into<String>,
92    ) -> Self {
93        Self::with_context(repo, prefix, CallContext::new(agent_id))
94    }
95
96    /// Create a task store whose commits carry `context`'s provenance: its
97    /// agent, authorizing principal, delegation chain and device. A host
98    /// that knows who is calling builds a store per caller this way, so plan
99    /// commits are attributed the same as its other writes. The
100    /// `created_by`, `started_by`, `completed_by` and `closed_by` fields
101    /// record the context's agent id.
102    pub fn with_context(
103        repo: Arc<Repository>,
104        prefix: impl Into<String>,
105        context: CallContext,
106    ) -> Self {
107        let mut prefix = prefix.into();
108        if prefix.ends_with('/') {
109            prefix.pop();
110        }
111        Self {
112            repo,
113            prefix,
114            context,
115        }
116    }
117
118    pub fn prefix(&self) -> &str {
119        &self.prefix
120    }
121
122    pub fn agent_id(&self) -> &str {
123        &self.context.agent_id
124    }
125
126    /// The provenance this store's commits carry.
127    pub fn context(&self) -> &CallContext {
128        &self.context
129    }
130
131    pub(crate) fn repo(&self) -> &Arc<Repository> {
132        &self.repo
133    }
134
135    // -----------------------------------------------------------------------
136    // Plan operations
137    // -----------------------------------------------------------------------
138
139    /// Maximum number of CAS retries for concurrent write operations.
140    pub(crate) const MAX_CAS_RETRIES: u32 = 32;
141
142    /// Create a new plan. Fails if a plan with the same name already exists.
143    ///
144    /// Uses a CAS retry loop so concurrent writers across processes are safe:
145    /// if the ref moves between the existence check and the commit, the loop
146    /// retries up to `MAX_CAS_RETRIES` times before returning
147    /// `TaskStoreError::WriteConflict`.
148    pub fn create_plan(
149        &self,
150        ref_name: &str,
151        name: &str,
152        description: Option<String>,
153    ) -> Result<Plan, TaskStoreError> {
154        for _ in 0..Self::MAX_CAS_RETRIES {
155            // Snapshot BEFORE the existence check so the CAS can detect any
156            // interleaved write.
157            let head = self.repo.head(ref_name)?;
158
159            if self.plan_exists(ref_name, name)? {
160                return Err(TaskStoreError::PlanAlreadyExists(name.to_string()));
161            }
162
163            let plan = Plan {
164                name: name.to_string(),
165                description: description.clone(),
166                status: PlanStatus::Active,
167                created_at: Utc::now(),
168                created_by: self.context.agent_id.clone(),
169                archived_at: None,
170                summary: None,
171                closed_at: None,
172                closed_by: None,
173            };
174
175            let meta_path = paths::plan_meta(&self.prefix, name);
176            let value = serde_json::to_value(&plan)?;
177
178            match self.repo.set_json_cas(
179                ref_name,
180                head,
181                &meta_path,
182                &value,
183                self.commit_opts(format!("Create plan {}", name)),
184            ) {
185                Ok(_) => return Ok(plan),
186                Err(RepoError::WriteConflict) => continue,
187                Err(e) => return Err(e.into()),
188            }
189        }
190        Err(TaskStoreError::WriteConflict)
191    }
192
193    /// List every plan under the store's prefix. Returns plans in the
194    /// order they are stored (alphabetical by name, since state trees
195    /// use BTreeMap underneath).
196    pub fn list_plans(&self, ref_name: &str) -> Result<Vec<Plan>, TaskStoreError> {
197        let root = match self.repo.get_json(ref_name, &self.prefix) {
198            Ok(v) => v,
199            Err(e) if is_path_not_found(&e) => return Ok(Vec::new()),
200            Err(e) => return Err(e.into()),
201        };
202
203        let serde_json::Value::Object(map) = root else {
204            return Ok(Vec::new());
205        };
206
207        // The read above holds every plan's metadata already; reading each
208        // plan again cost a round trip per plan on a remote store.
209        map.iter()
210            .map(|(name, plan)| plan_from_tree(name, plan))
211            .collect()
212    }
213
214    /// Every plan with its tasks (sorted by id), from one read of the plans
215    /// tree: what a listing that shows task counts needs, without a read per
216    /// plan.
217    pub fn list_plans_with_tasks(
218        &self,
219        ref_name: &str,
220    ) -> Result<Vec<(Plan, Vec<Task>)>, TaskStoreError> {
221        let root = match self.repo.get_json(ref_name, &self.prefix) {
222            Ok(v) => v,
223            Err(e) if is_path_not_found(&e) => return Ok(Vec::new()),
224            Err(e) => return Err(e.into()),
225        };
226        let serde_json::Value::Object(map) = root else {
227            return Ok(Vec::new());
228        };
229        map.iter()
230            .map(|(name, plan)| Ok((plan_from_tree(name, plan)?, tasks_from_tree(plan)?)))
231            .collect()
232    }
233
234    /// Fetch a single plan by name.
235    pub fn get_plan(&self, ref_name: &str, name: &str) -> Result<Plan, TaskStoreError> {
236        let meta_path = paths::plan_meta(&self.prefix, name);
237        let value = self
238            .repo
239            .get_json(ref_name, &meta_path)
240            .map_err(|e| map_not_found(e, || TaskStoreError::PlanNotFound(name.to_string())))?;
241        Ok(serde_json::from_value(value)?)
242    }
243
244    /// Archive a plan — a soft, reversible transition that marks the
245    /// plan as no longer active but leaves all task data intact. Valid
246    /// for any status (active, completed, empty) — archival never
247    /// touches tasks, proofs, or abandonment reasons.
248    ///
249    /// Uses a CAS retry loop so concurrent plan mutations on the same
250    /// branch can't silently overwrite one another. Each retry re-reads
251    /// the plan from the snapshotted head, so a competing write that
252    /// advanced the ref is picked up on the next pass rather than lost.
253    pub fn archive_plan(&self, ref_name: &str, name: &str) -> Result<Plan, TaskStoreError> {
254        let meta_path = paths::plan_meta(&self.prefix, name);
255        for _ in 0..Self::MAX_CAS_RETRIES {
256            // Snapshot the head, then read the plan from that same head so
257            // the commit we build applies on top of what we validated.
258            let head = self.repo.head(ref_name)?;
259            let mut plan = self.get_plan(ref_name, name)?;
260            plan.status = PlanStatus::Archived;
261            plan.archived_at = Some(Utc::now());
262
263            let value = serde_json::to_value(&plan)?;
264            match self.repo.set_json_cas(
265                ref_name,
266                head,
267                &meta_path,
268                &value,
269                self.commit_opts(format!("Archive plan {}", name)),
270            ) {
271                Ok(_) => return Ok(plan),
272                Err(RepoError::WriteConflict) => continue,
273                Err(e) => return Err(e.into()),
274            }
275        }
276        Err(TaskStoreError::WriteConflict)
277    }
278
279    /// Close a plan, recording a required `summary`.
280    ///
281    /// This is the explicit, gated replacement for the old auto-promotion:
282    /// terminal task transitions no longer complete the plan on their own.
283    /// Closing requires (1) a non-empty `summary` — the plan-level analog of
284    /// a task's `proof` — and (2) that every task is already terminal
285    /// (`Done`/`Abandoned`), so a plan cannot be closed with work still open.
286    ///
287    /// Idempotent on an already-closed (`Completed`) plan: returns it
288    /// unchanged. Refuses an `Archived` plan. Sets `status = Completed`,
289    /// `summary`, `closed_at`, and `closed_by`.
290    pub fn close_plan(
291        &self,
292        ref_name: &str,
293        name: &str,
294        summary: &str,
295    ) -> Result<Plan, TaskStoreError> {
296        if summary.trim().is_empty() {
297            return Err(TaskStoreError::SummaryRequired);
298        }
299        let meta_path = paths::plan_meta(&self.prefix, name);
300        for _ in 0..Self::MAX_CAS_RETRIES {
301            let head = self.repo.head(ref_name)?;
302            let mut plan = self.get_plan(ref_name, name)?;
303            match plan.status {
304                // Idempotent: closing a closed plan is a no-op.
305                PlanStatus::Completed => return Ok(plan),
306                PlanStatus::Archived => {
307                    return Err(TaskStoreError::CannotClose {
308                        plan: name.to_string(),
309                        reason: "plan is archived".to_string(),
310                    });
311                }
312                PlanStatus::Active => {}
313            }
314
315            let tasks = self.list_tasks(ref_name, name)?;
316            if tasks.is_empty() {
317                return Err(TaskStoreError::CannotClose {
318                    plan: name.to_string(),
319                    reason: "plan has no tasks".to_string(),
320                });
321            }
322            if let Some(open) = tasks.iter().find(|t| !t.status.is_terminal()) {
323                return Err(TaskStoreError::CannotClose {
324                    plan: name.to_string(),
325                    reason: format!(
326                        "task {} is still {:?}; every task must be done or abandoned first",
327                        open.id.0, open.status
328                    ),
329                });
330            }
331
332            plan.status = PlanStatus::Completed;
333            plan.summary = Some(summary.trim().to_string());
334            plan.closed_at = Some(Utc::now());
335            plan.closed_by = Some(self.context.agent_id.clone());
336
337            let value = serde_json::to_value(&plan)?;
338            match self.repo.set_json_cas(
339                ref_name,
340                head,
341                &meta_path,
342                &value,
343                self.commit_opts(format!("Close plan {}", name)),
344            ) {
345                Ok(_) => return Ok(plan),
346                Err(RepoError::WriteConflict) => continue,
347                Err(e) => return Err(e.into()),
348            }
349        }
350        Err(TaskStoreError::WriteConflict)
351    }
352
353    /// Delete a plan and every task it contains. Destructive — use
354    /// `archive_plan` if the history should remain discoverable.
355    pub fn delete_plan(&self, ref_name: &str, name: &str) -> Result<(), TaskStoreError> {
356        if !self.plan_exists(ref_name, name)? {
357            return Err(TaskStoreError::PlanNotFound(name.to_string()));
358        }
359        let root = paths::plan_root(&self.prefix, name);
360        self.repo.delete(
361            ref_name,
362            &root,
363            self.commit_opts(format!("Delete plan {}", name)),
364        )?;
365        Ok(())
366    }
367
368    // -----------------------------------------------------------------------
369    // Task operations
370    // -----------------------------------------------------------------------
371
372    /// Add a new task to a plan. Task ids are assigned monotonically —
373    /// the next available `t-NNN` is picked by scanning existing entries.
374    /// `assigned_to` is optional — pass an agent id to record ownership.
375    pub fn add_task(
376        &self,
377        ref_name: &str,
378        plan: &str,
379        title: &str,
380        priority: Priority,
381        parent_id: Option<TaskId>,
382        blocked_by: Vec<TaskId>,
383        assigned_to: Option<String>,
384    ) -> Result<Task, TaskStoreError> {
385        self.add_task_with_extensions(
386            ref_name,
387            plan,
388            title,
389            priority,
390            parent_id,
391            blocked_by,
392            assigned_to,
393            AddTaskOptions::default(),
394        )
395    }
396
397    /// Like `add_task` but also accepts the policy-fallback extension
398    /// fields (POLICY_V1.md §22.4) and notes. See [`AddTaskOptions`] for
399    /// field docs.
400    ///
401    /// Uses a CAS retry loop so concurrent writers across processes are safe.
402    /// On each retry, `next_task_number` re-scans the current tree, naturally
403    /// picking the next available id even if a concurrent writer added a task
404    /// in the meantime.
405    pub fn add_task_with_extensions(
406        &self,
407        ref_name: &str,
408        plan: &str,
409        title: &str,
410        priority: Priority,
411        parent_id: Option<TaskId>,
412        blocked_by: Vec<TaskId>,
413        assigned_to: Option<String>,
414        opts: AddTaskOptions,
415    ) -> Result<Task, TaskStoreError> {
416        let AddTaskOptions {
417            payload,
418            parent_change,
419            on_complete,
420            notes,
421        } = opts;
422        let notes = normalize_notes(notes.as_deref())?;
423        if !self.plan_exists(ref_name, plan)? {
424            return Err(TaskStoreError::PlanNotFound(plan.to_string()));
425        }
426
427        if let Some(ref parent) = parent_id {
428            let parent_task = self.get_task(ref_name, plan, parent)?;
429            if parent_task.parent_id.is_some() {
430                return Err(TaskStoreError::ParentIsSubtask(parent.clone()));
431            }
432        }
433
434        validate_blocker_ids(&blocked_by)?;
435        for blocker in &blocked_by {
436            self.get_task(ref_name, plan, blocker)?;
437        }
438
439        for _ in 0..Self::MAX_CAS_RETRIES {
440            // Snapshot BEFORE the next_task_number read so the CAS can detect
441            // any interleaved write that might have claimed the same id.
442            let head = self.repo.head(ref_name)?;
443
444            let next_num = self.next_task_number(ref_name, plan)?;
445            let id = TaskId::new(next_num);
446
447            let task = Task {
448                id: id.clone(),
449                title: title.to_string(),
450                notes: notes.clone(),
451                status: TaskStatus::Pending,
452                priority,
453                parent_id: parent_id.clone(),
454                blocked_by: blocked_by.clone(),
455                created_at: Utc::now(),
456                created_by: self.context.agent_id.clone(),
457                started_at: None,
458                started_by: None,
459                completed_at: None,
460                completed_by: None,
461                proof: None,
462                abandoned_at: None,
463                abandoned_reason: None,
464                assigned_to: assigned_to.clone(),
465                payload: payload.clone(),
466                parent_change: parent_change.clone(),
467                on_complete: on_complete.clone(),
468            };
469
470            let task_path = paths::task(&self.prefix, plan, &id);
471            let value = serde_json::to_value(&task)?;
472
473            match self.repo.set_json_cas(
474                ref_name,
475                head,
476                &task_path,
477                &value,
478                self.commit_opts(format!("Add task {}/{}", plan, id)),
479            ) {
480                Ok(_) => return Ok(task),
481                Err(RepoError::WriteConflict) => continue,
482                Err(e) => return Err(e.into()),
483            }
484        }
485        Err(TaskStoreError::WriteConflict)
486    }
487
488    /// List every task id in a plan, cheaply — this walks tree paths
489    /// without deserializing task bodies. Use this when you only need
490    /// to know which tasks exist (e.g. picking the next task number,
491    /// checking blocker existence). Prefer `list_tasks` when you need
492    /// task data.
493    pub fn task_ids(&self, ref_name: &str, plan: &str) -> Result<Vec<TaskId>, TaskStoreError> {
494        let root_path = paths::plan_root(&self.prefix, plan);
495        let leaves = match self.repo.list_paths(ref_name, &root_path, None) {
496            Ok(v) => v,
497            Err(e) if is_path_not_found(&e) => {
498                return Err(TaskStoreError::PlanNotFound(plan.to_string()));
499            }
500            Err(e) => return Err(e.into()),
501        };
502
503        let prefix_with_slash = format!("{}/", root_path);
504        let mut ids: std::collections::BTreeSet<TaskId> = std::collections::BTreeSet::new();
505        for leaf in leaves {
506            let Some(suffix) = leaf.strip_prefix(&prefix_with_slash) else {
507                continue;
508            };
509            let first = suffix.split('/').next().unwrap_or("");
510            if first.is_empty() || first == paths::META_KEY {
511                continue;
512            }
513            ids.insert(TaskId(first.to_string()));
514        }
515        Ok(ids.into_iter().collect())
516    }
517
518    /// List every task in a plan. Ordered by task id. This fully
519    /// deserializes every task — O(n) in total field count. For id-only
520    /// operations prefer `task_ids`.
521    pub fn list_tasks(&self, ref_name: &str, plan: &str) -> Result<Vec<Task>, TaskStoreError> {
522        // One read of the plan's tree: a plan exists when it has metadata.
523        let root_path = paths::plan_root(&self.prefix, plan);
524        let root = self
525            .repo
526            .get_json(ref_name, &root_path)
527            .map_err(|e| map_not_found(e, || TaskStoreError::PlanNotFound(plan.to_string())))?;
528        if root.get(paths::META_KEY).is_none() {
529            return Err(TaskStoreError::PlanNotFound(plan.to_string()));
530        }
531        tasks_from_tree(&root)
532    }
533
534    pub fn get_task(
535        &self,
536        ref_name: &str,
537        plan: &str,
538        id: &TaskId,
539    ) -> Result<Task, TaskStoreError> {
540        let path = paths::task(&self.prefix, plan, id);
541        let value = self.repo.get_json(ref_name, &path).map_err(|e| {
542            map_not_found(e, || TaskStoreError::TaskNotFound {
543                plan: plan.to_string(),
544                id: id.clone(),
545            })
546        })?;
547        Ok(serde_json::from_value(value)?)
548    }
549
550    /// Transition `pending → in_progress`. Fails with `Blocked` if any
551    /// blocker is not `done`, or `BlockerNotFound` if any blocker id no
552    /// longer exists in the plan (e.g. because the plan was rebuilt
553    /// after a delete).
554    pub fn start_task(
555        &self,
556        ref_name: &str,
557        plan: &str,
558        id: &TaskId,
559    ) -> Result<Task, TaskStoreError> {
560        self.update_task(
561            ref_name,
562            plan,
563            id,
564            format!("Start {}/{}", plan, id),
565            |task| {
566                check_transition(task.status, Transition::Start)?;
567
568                let BlockerCheck { missing, pending } =
569                    self.classify_blockers(ref_name, plan, &task.blocked_by)?;
570                if !missing.is_empty() {
571                    return Err(TaskStoreError::BlockerNotFound { blockers: missing });
572                }
573                if !pending.is_empty() {
574                    return Err(TaskStoreError::Blocked { blockers: pending });
575                }
576
577                task.status = TaskStatus::InProgress;
578                task.started_at = Some(Utc::now());
579                task.started_by = Some(self.context.agent_id.clone());
580                Ok(())
581            },
582        )
583    }
584
585    /// Transition `in_progress → done`. Requires a `Proof` — it's stored
586    /// but NOT verified here (use `verify_plan` for that).
587    ///
588    /// A terminal task transition does NOT auto-promote the plan to
589    /// `Completed`. Closing a plan is an explicit, summary-gated action
590    /// (`close_plan`) so implementations own their close workflow and can
591    /// require a summary — the plan-level analog of a task's `proof`.
592    pub fn complete_task(
593        &self,
594        ref_name: &str,
595        plan: &str,
596        id: &TaskId,
597        proof: Proof,
598    ) -> Result<Task, TaskStoreError> {
599        self.update_task(
600            ref_name,
601            plan,
602            id,
603            format!("Complete {}/{}", plan, id),
604            |task| {
605                check_transition(task.status, Transition::Complete)?;
606                task.status = TaskStatus::Done;
607                task.proof = Some(proof.clone());
608                task.completed_at = Some(Utc::now());
609                task.completed_by = Some(self.context.agent_id.clone());
610                Ok(())
611            },
612        )
613    }
614
615    /// Transition to `abandoned`. Legal from both `pending` and
616    /// `in_progress`. Reason is required. Like `complete_task`, it does not
617    /// touch the plan's status.
618    pub fn abandon_task(
619        &self,
620        ref_name: &str,
621        plan: &str,
622        id: &TaskId,
623        reason: &str,
624    ) -> Result<Task, TaskStoreError> {
625        if reason.trim().is_empty() {
626            return Err(TaskStoreError::ReasonRequired);
627        }
628        self.update_task(
629            ref_name,
630            plan,
631            id,
632            format!("Abandon {}/{}", plan, id),
633            |task| {
634                check_transition(task.status, Transition::Abandon)?;
635                task.status = TaskStatus::Abandoned;
636                task.abandoned_at = Some(Utc::now());
637                task.abandoned_reason = Some(reason.to_string());
638                Ok(())
639            },
640        )
641    }
642
643    pub fn set_priority(
644        &self,
645        ref_name: &str,
646        plan: &str,
647        id: &TaskId,
648        priority: Priority,
649    ) -> Result<Task, TaskStoreError> {
650        let desc = format!("Set priority {:?} on {}/{}", priority, plan, id);
651        self.update_task(ref_name, plan, id, desc, |task| {
652            task.priority = priority;
653            Ok(())
654        })
655    }
656
657    /// Replace a task's title. The title must not be blank. Status, proof,
658    /// blockers and timestamps are left as they are; the commit records who
659    /// changed it.
660    pub fn set_title(
661        &self,
662        ref_name: &str,
663        plan: &str,
664        id: &TaskId,
665        title: &str,
666    ) -> Result<Task, TaskStoreError> {
667        if title.trim().is_empty() {
668            return Err(TaskStoreError::TitleRequired);
669        }
670        let desc = format!("Retitle {}/{}", plan, id);
671        self.update_task(ref_name, plan, id, desc, |task| {
672            task.title = title.to_string();
673            Ok(())
674        })
675    }
676
677    /// Replace a task's notes, or clear them with `None` or blank text.
678    ///
679    /// Notes may span lines and are kept exactly as given, up to
680    /// [`MAX_NOTES_BYTES`] of UTF-8; longer notes are refused with
681    /// [`TaskStoreError::NotesTooLong`] and the task is left as it was. Like
682    /// `set_title`, this works at any status, done and abandoned included,
683    /// and leaves everything else as it is. Each edit is a commit that
684    /// records who made it.
685    pub fn set_notes(
686        &self,
687        ref_name: &str,
688        plan: &str,
689        id: &TaskId,
690        notes: Option<&str>,
691    ) -> Result<Task, TaskStoreError> {
692        let notes = normalize_notes(notes)?;
693        let desc = match notes {
694            Some(_) => format!("Set notes on {}/{}", plan, id),
695            None => format!("Clear notes on {}/{}", plan, id),
696        };
697        self.update_task(ref_name, plan, id, desc, |task| {
698            task.notes = notes.clone();
699            Ok(())
700        })
701    }
702
703    /// Replace a task's blocker list. Every blocker must be a task in the same
704    /// plan, and the new list must not make the task wait on itself, directly
705    /// or through other tasks: a cycle would leave every task in it blocked
706    /// for good.
707    pub fn set_blockers(
708        &self,
709        ref_name: &str,
710        plan: &str,
711        id: &TaskId,
712        blockers: Vec<TaskId>,
713    ) -> Result<Task, TaskStoreError> {
714        validate_blocker_ids(&blockers)?;
715        let desc = format!("Update blockers on {}/{}", plan, id);
716        self.update_task(ref_name, plan, id, desc, |task| {
717            let tasks = self.list_tasks(ref_name, plan)?;
718            for blocker in &blockers {
719                if !tasks.iter().any(|t| &t.id == blocker) {
720                    return Err(TaskStoreError::TaskNotFound {
721                        plan: plan.to_string(),
722                        id: blocker.clone(),
723                    });
724                }
725            }
726            if let Some(cycle) = blocker_cycle(&tasks, &task.id, &blockers) {
727                return Err(TaskStoreError::BlockerCycle { cycle });
728            }
729            task.blocked_by = blockers.clone();
730            Ok(())
731        })
732    }
733
734    /// Set `assigned_to` on a task.
735    pub fn assign_task(
736        &self,
737        ref_name: &str,
738        plan: &str,
739        id: &TaskId,
740        agent: &str,
741    ) -> Result<Task, TaskStoreError> {
742        let desc = format!("Assign {}/{} to {}", plan, id, agent);
743        self.update_task(ref_name, plan, id, desc, |task| {
744            task.assigned_to = Some(agent.to_string());
745            Ok(())
746        })
747    }
748
749    /// Clear `assigned_to` on a task.
750    pub fn unassign_task(
751        &self,
752        ref_name: &str,
753        plan: &str,
754        id: &TaskId,
755    ) -> Result<Task, TaskStoreError> {
756        self.update_task(
757            ref_name,
758            plan,
759            id,
760            format!("Unassign {}/{}", plan, id),
761            |task| {
762                task.assigned_to = None;
763                Ok(())
764            },
765        )
766    }
767
768    // -----------------------------------------------------------------------
769    // Query helpers
770    // -----------------------------------------------------------------------
771
772    /// Highest-priority `pending` task whose blockers are all `done`.
773    /// Ties broken by ascending task id (insertion order).
774    pub fn next_task(&self, ref_name: &str, plan: &str) -> Result<Option<Task>, TaskStoreError> {
775        self.next_task_for(ref_name, plan, None, true)
776    }
777
778    /// Like `next_task`, but filter by assignment.
779    ///
780    /// - `assigned_to = None` → any pending unblocked task (same as
781    ///   `next_task`).
782    /// - `assigned_to = Some(agent)`, `include_unassigned = true` →
783    ///   tasks assigned to `agent` OR unassigned.
784    /// - `assigned_to = Some(agent)`, `include_unassigned = false` →
785    ///   only tasks explicitly assigned to `agent`.
786    pub fn next_task_for(
787        &self,
788        ref_name: &str,
789        plan: &str,
790        assigned_to: Option<&str>,
791        include_unassigned: bool,
792    ) -> Result<Option<Task>, TaskStoreError> {
793        let tasks = self.list_tasks(ref_name, plan)?;
794        let mut candidates: Vec<&Task> = tasks
795            .iter()
796            .filter(|t| t.status == TaskStatus::Pending)
797            .filter(|t| t.blocked_by.iter().all(|b| blocker_satisfied(&tasks, b)))
798            .filter(|t| match assigned_to {
799                None => true,
800                Some(agent) => match &t.assigned_to {
801                    Some(a) => a == agent,
802                    None => include_unassigned,
803                },
804            })
805            .collect();
806        candidates.sort_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
807        Ok(candidates.first().map(|t| (*t).clone()))
808    }
809
810    /// List plans filtered by status. `None` returns all plans.
811    pub fn list_plans_by_status(
812        &self,
813        ref_name: &str,
814        status: Option<PlanStatus>,
815    ) -> Result<Vec<Plan>, TaskStoreError> {
816        let plans = self.list_plans(ref_name)?;
817        match status {
818            None => Ok(plans),
819            Some(s) => Ok(plans.into_iter().filter(|p| p.status == s).collect()),
820        }
821    }
822
823    /// Compute the rollup status of a parent task from its direct
824    /// subtasks. Read-only — does not mutate storage.
825    ///
826    /// Rules:
827    /// - `Done` if every non-abandoned subtask is `Done`.
828    /// - `InProgress` if any subtask is `InProgress`.
829    /// - `Pending` otherwise.
830    ///
831    /// If the parent has no subtasks, returns the parent's own status.
832    pub fn derived_status(
833        &self,
834        ref_name: &str,
835        plan: &str,
836        parent_id: &TaskId,
837    ) -> Result<TaskStatus, TaskStoreError> {
838        let tasks = self.list_tasks(ref_name, plan)?;
839        let parent = tasks.iter().find(|t| &t.id == parent_id).ok_or_else(|| {
840            TaskStoreError::TaskNotFound {
841                plan: plan.to_string(),
842                id: parent_id.clone(),
843            }
844        })?;
845
846        let subtasks: Vec<&Task> = tasks
847            .iter()
848            .filter(|t| t.parent_id.as_ref() == Some(parent_id))
849            .collect();
850
851        if subtasks.is_empty() {
852            return Ok(parent.status);
853        }
854
855        if subtasks.iter().any(|t| t.status == TaskStatus::InProgress) {
856            return Ok(TaskStatus::InProgress);
857        }
858
859        let non_abandoned: Vec<&&Task> = subtasks
860            .iter()
861            .filter(|t| t.status != TaskStatus::Abandoned)
862            .collect();
863
864        if !non_abandoned.is_empty() && non_abandoned.iter().all(|t| t.status == TaskStatus::Done) {
865            return Ok(TaskStatus::Done);
866        }
867
868        Ok(TaskStatus::Pending)
869    }
870
871    /// Walk every `done` task and run the given verifier against each proof.
872    /// Non-`done` tasks are skipped.
873    pub fn verify_plan(
874        &self,
875        ref_name: &str,
876        plan: &str,
877        verifier: &dyn Verifier,
878    ) -> Result<VerifyReport, TaskStoreError> {
879        let tasks = self.list_tasks(ref_name, plan)?;
880        let mut results = Vec::new();
881        for task in tasks.iter().filter(|t| t.status == TaskStatus::Done) {
882            let proof = task.proof.as_ref().ok_or(TaskStoreError::ProofRequired)?;
883            let outcome = verifier.verify(proof);
884            results.push(VerifyEntry {
885                task_id: task.id.clone(),
886                result: outcome,
887            });
888        }
889        Ok(VerifyReport {
890            plan: plan.to_string(),
891            results,
892        })
893    }
894
895    // -----------------------------------------------------------------------
896    // Internals
897    // -----------------------------------------------------------------------
898
899    fn plan_exists(&self, ref_name: &str, name: &str) -> Result<bool, TaskStoreError> {
900        match self.get_plan(ref_name, name) {
901            Ok(_) => Ok(true),
902            Err(TaskStoreError::PlanNotFound(_)) => Ok(false),
903            Err(e) => Err(e),
904        }
905    }
906
907    fn next_task_number(&self, ref_name: &str, plan: &str) -> Result<u32, TaskStoreError> {
908        let ids = self.task_ids(ref_name, plan)?;
909        let max = ids
910            .iter()
911            .filter_map(|id| id.number().ok())
912            .max()
913            .unwrap_or(0);
914        Ok(max + 1)
915    }
916
917    fn classify_blockers(
918        &self,
919        ref_name: &str,
920        plan: &str,
921        blockers: &[TaskId],
922    ) -> Result<BlockerCheck, TaskStoreError> {
923        if blockers.is_empty() {
924            return Ok(BlockerCheck::default());
925        }
926        let tasks = self.list_tasks(ref_name, plan)?;
927        let mut missing = Vec::new();
928        let mut pending = Vec::new();
929        for b in blockers {
930            match tasks.iter().find(|t| &t.id == b) {
931                None => missing.push(b.clone()),
932                Some(t) if t.status != TaskStatus::Done => pending.push(b.clone()),
933                _ => {}
934            }
935        }
936        Ok(BlockerCheck { missing, pending })
937    }
938
939    /// Read-modify-write one task without losing a concurrent update.
940    ///
941    /// Every transition reads the whole task, changes a field or two, and
942    /// writes the whole task back. Landing that with a plain `set_json` moved
943    /// the ref safely but wrote the value read earlier, so a concurrent update
944    /// to the same task was reverted while both calls returned Ok (a
945    /// complete racing an assign lost one or the other every time). Snapshot
946    /// the head before reading, apply `change` to what was read, and land it
947    /// with `set_json_cas` against that head; if anything moved the ref in
948    /// between, re-read and re-apply — which also re-validates the transition
949    /// against the fresh task.
950    fn update_task<F>(
951        &self,
952        ref_name: &str,
953        plan: &str,
954        id: &TaskId,
955        description: String,
956        mut change: F,
957    ) -> Result<Task, TaskStoreError>
958    where
959        F: FnMut(&mut Task) -> Result<(), TaskStoreError>,
960    {
961        for _ in 0..Self::MAX_CAS_RETRIES {
962            let head = self.repo.head(ref_name)?;
963            let mut task = self.get_task(ref_name, plan, id)?;
964            change(&mut task)?;
965            let path = paths::task(&self.prefix, plan, &task.id);
966            let value = serde_json::to_value(&task)?;
967            match self.repo.set_json_cas(
968                ref_name,
969                head,
970                &path,
971                &value,
972                self.commit_opts(description.clone()),
973            ) {
974                Ok(_) => return Ok(task),
975                Err(RepoError::WriteConflict) => continue,
976                Err(e) => return Err(e.into()),
977            }
978        }
979        Err(TaskStoreError::WriteConflict)
980    }
981
982    pub(crate) fn commit_opts(&self, description: impl Into<String>) -> CommitOptions {
983        self.context
984            .commit_options(IntentCategory::Plan, description)
985    }
986}
987
988/// A blocker is satisfied iff it names a task in the same plan whose
989/// status is `Done`. Abandoned blockers are NOT considered satisfied —
990/// an agent who abandons a blocker must explicitly re-open the
991/// blockers on the dependent task (via `set_blockers`) before starting
992/// it. Missing blockers (the task no longer exists) are also not
993/// satisfied and surface as `BlockerNotFound` at `start_task` time.
994fn blocker_satisfied(tasks: &[Task], id: &TaskId) -> bool {
995    tasks
996        .iter()
997        .any(|t| &t.id == id && t.status == TaskStatus::Done)
998}
999
1000/// The cycle that making `blockers` the blockers of `id` would close, as the
1001/// path from `id` back to itself: `[t-001, t-003, t-001]`, or `[t-001, t-001]`
1002/// for a task that would block itself. `None` when the plan's blocker graph
1003/// stays acyclic. The other tasks' blockers come from `tasks`.
1004fn blocker_cycle(tasks: &[Task], id: &TaskId, blockers: &[TaskId]) -> Option<Vec<TaskId>> {
1005    let edges: HashMap<&TaskId, &[TaskId]> = tasks
1006        .iter()
1007        .map(|t| (&t.id, t.blocked_by.as_slice()))
1008        .collect();
1009    let mut visited = HashSet::new();
1010    let mut path = vec![id.clone()];
1011    blockers
1012        .iter()
1013        .any(|b| reaches(b, id, &edges, &mut visited, &mut path))
1014        .then_some(path)
1015}
1016
1017/// Depth-first along `blocked_by` from `node`: true when it reaches `target`,
1018/// with `path` then holding the route there.
1019fn reaches<'a>(
1020    node: &'a TaskId,
1021    target: &TaskId,
1022    edges: &HashMap<&'a TaskId, &'a [TaskId]>,
1023    visited: &mut HashSet<&'a TaskId>,
1024    path: &mut Vec<TaskId>,
1025) -> bool {
1026    path.push(node.clone());
1027    if node == target {
1028        return true;
1029    }
1030    if visited.insert(node) {
1031        for next in edges.get(node).copied().unwrap_or_default() {
1032            if reaches(next, target, edges, visited, path) {
1033                return true;
1034            }
1035        }
1036    }
1037    path.pop();
1038    false
1039}
1040
1041#[derive(Default, Debug)]
1042struct BlockerCheck {
1043    /// Blocker ids that are not currently `Done` but DO exist in the plan.
1044    pending: Vec<TaskId>,
1045    /// Blocker ids that no longer resolve to any task in the plan.
1046    missing: Vec<TaskId>,
1047}
1048
1049/// True only when a read failed because the *path* is genuinely absent — a
1050/// key that was never written. This must NOT match `TreeError::ObjectNotFound`,
1051/// which means an object referenced by the tree is missing from the store
1052/// (repository corruption / a dangling interior node). Conflating the two made
1053/// `list_plans`/`list_tasks` silently return an empty collection over a
1054/// corrupt tree, masking data loss as "no plans". Corruption now propagates.
1055fn is_path_not_found(e: &agentstategraph::RepoError) -> bool {
1056    matches!(
1057        e,
1058        agentstategraph::RepoError::Tree(agentstategraph::tree::TreeError::PathNotFound(_))
1059    )
1060}
1061
1062/// A plan's metadata from its subtree of the plans tree (`plan` is the value
1063/// at `<prefix>/<name>`).
1064fn plan_from_tree(name: &str, plan: &serde_json::Value) -> Result<Plan, TaskStoreError> {
1065    let meta = plan
1066        .get(paths::META_KEY)
1067        .ok_or_else(|| TaskStoreError::PlanNotFound(name.to_string()))?;
1068    Ok(serde_json::from_value(meta.clone())?)
1069}
1070
1071/// The tasks in a plan's subtree, sorted by id.
1072fn tasks_from_tree(plan: &serde_json::Value) -> Result<Vec<Task>, TaskStoreError> {
1073    let serde_json::Value::Object(map) = plan else {
1074        return Ok(Vec::new());
1075    };
1076    let mut tasks = map
1077        .iter()
1078        .filter(|(key, _)| key.as_str() != paths::META_KEY)
1079        .map(|(_, value)| serde_json::from_value::<Task>(value.clone()))
1080        .collect::<Result<Vec<_>, _>>()?;
1081    tasks.sort_by_key(|t| t.id.clone());
1082    Ok(tasks)
1083}
1084
1085fn map_not_found<F>(e: agentstategraph::RepoError, make: F) -> TaskStoreError
1086where
1087    F: FnOnce() -> TaskStoreError,
1088{
1089    if is_path_not_found(&e) {
1090        make()
1091    } else {
1092        e.into()
1093    }
1094}
1095
1096#[cfg(test)]
1097mod path_not_found_tests {
1098    use super::is_path_not_found;
1099    use agentstategraph::RepoError;
1100    use agentstategraph::core::ObjectId;
1101    use agentstategraph::tree::TreeError;
1102
1103    #[test]
1104    fn path_not_found_is_classified_as_empty() {
1105        let e = RepoError::Tree(TreeError::PathNotFound("/plans/foo".into()));
1106        assert!(is_path_not_found(&e));
1107    }
1108
1109    #[test]
1110    fn object_not_found_is_not_empty() {
1111        // A dangling interior object is corruption, not an absent path — it must
1112        // NOT be swallowed as an empty collection.
1113        let e = RepoError::Tree(TreeError::ObjectNotFound(ObjectId::from_bytes([7u8; 32])));
1114        assert!(
1115            !is_path_not_found(&e),
1116            "ObjectNotFound must propagate as an error, not read as empty"
1117        );
1118    }
1119}