agentstategraph-tasks 1.4.2

Shared task-store primitives built on AgentStateGraph
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
//! `TaskStore` — handle bound to a `Repository` + path prefix.
//!
//! All task and plan operations go through a `TaskStore`. Writes are
//! committed to the repository with `IntentCategory::Plan`, so plan
//! activity is natively filterable in log and blame queries. Multi-path
//! transitions (e.g. `complete_task` updating the task and the plan's
//! `_meta` together) use the speculation API so they land in a single
//! commit.

use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use agentstategraph::{CommitOptions, RepoError, Repository};
use agentstategraph_core::IntentCategory;
use chrono::Utc;
use once_cell::sync::Lazy;
use regex::Regex;

/// Canonical blocker id pattern: `t-` followed by 1..9 digits. Validated
/// at the substrate layer so malformed blocker ids (path-traversal
/// attempts, nonsense strings) never reach the tree walker.
static BLOCKER_ID_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"^t-\d{1,9}$").expect("static blocker-id regex must compile"));

fn validate_blocker_ids(blockers: &[TaskId]) -> Result<(), TaskStoreError> {
    for b in blockers {
        if !BLOCKER_ID_RE.is_match(&b.0) {
            return Err(TaskStoreError::InvalidBlockerId(b.0.clone()));
        }
    }
    Ok(())
}

use crate::error::TaskStoreError;
use crate::paths;
use crate::state::{Transition, check_transition};
use crate::types::{OnCompleteHook, Plan, PlanStatus, Priority, Proof, Task, TaskId, TaskStatus};
use crate::verifier::{Verifier, VerifyEntry, VerifyReport};

/// Optional extension fields for [`TaskStore::add_task_with_extensions`].
///
/// - `payload`: opaque JSON the task carries for a downstream consumer.
///   The `-tasks` crate does not interpret it.
/// - `parent_change`: identifier of the change this task gates, when
///   created from a deferred `ChangeProposal`.
/// - `on_complete`: hook the consumer dispatches when the task transitions
///   to `Done`. The `-tasks` crate does not execute it.
#[derive(Default)]
pub struct AddTaskOptions {
    pub payload: Option<serde_json::Value>,
    pub parent_change: Option<String>,
    pub on_complete: Option<OnCompleteHook>,
}

/// A handle bound to a `Repository` and a path prefix. All operations on
/// plans and tasks go through a `TaskStore`.
pub struct TaskStore {
    repo: Arc<Repository>,
    prefix: String,
    agent_id: String,
}

impl TaskStore {
    /// Create a new task store bound to a path prefix in the given
    /// repository. The prefix must NOT end with a slash.
    ///
    /// `agent_id` is used as the commit author for every task operation.
    pub fn new(
        repo: Arc<Repository>,
        prefix: impl Into<String>,
        agent_id: impl Into<String>,
    ) -> Self {
        let mut prefix = prefix.into();
        if prefix.ends_with('/') {
            prefix.pop();
        }
        Self {
            repo,
            prefix,
            agent_id: agent_id.into(),
        }
    }

    pub fn prefix(&self) -> &str {
        &self.prefix
    }

    pub fn agent_id(&self) -> &str {
        &self.agent_id
    }

    // -----------------------------------------------------------------------
    // Plan operations
    // -----------------------------------------------------------------------

    /// Maximum number of CAS retries for concurrent write operations.
    const MAX_CAS_RETRIES: u32 = 32;

    /// Create a new plan. Fails if a plan with the same name already exists.
    ///
    /// Uses a CAS retry loop so concurrent writers across processes are safe:
    /// if the ref moves between the existence check and the commit, the loop
    /// retries up to `MAX_CAS_RETRIES` times before returning
    /// `TaskStoreError::WriteConflict`.
    pub fn create_plan(
        &self,
        ref_name: &str,
        name: &str,
        description: Option<String>,
    ) -> Result<Plan, TaskStoreError> {
        for _ in 0..Self::MAX_CAS_RETRIES {
            // Snapshot BEFORE the existence check so the CAS can detect any
            // interleaved write.
            let head = self.repo.head(ref_name)?;

            if self.plan_exists(ref_name, name)? {
                return Err(TaskStoreError::PlanAlreadyExists(name.to_string()));
            }

            let plan = Plan {
                name: name.to_string(),
                description: description.clone(),
                status: PlanStatus::Active,
                created_at: Utc::now(),
                created_by: self.agent_id.clone(),
                archived_at: None,
                summary: None,
                closed_at: None,
                closed_by: None,
            };

            let meta_path = paths::plan_meta(&self.prefix, name);
            let value = serde_json::to_value(&plan)?;

            match self.repo.set_json_cas(
                ref_name,
                head,
                &meta_path,
                &value,
                self.commit_opts(format!("Create plan {}", name)),
            ) {
                Ok(_) => return Ok(plan),
                Err(RepoError::WriteConflict) => continue,
                Err(e) => return Err(e.into()),
            }
        }
        Err(TaskStoreError::WriteConflict)
    }

    /// List every plan under the store's prefix. Returns plans in the
    /// order they are stored (alphabetical by name, since state trees
    /// use BTreeMap underneath).
    pub fn list_plans(&self, ref_name: &str) -> Result<Vec<Plan>, TaskStoreError> {
        let root = match self.repo.get_json(ref_name, &self.prefix) {
            Ok(v) => v,
            Err(e) if is_path_not_found(&e) => return Ok(Vec::new()),
            Err(e) => return Err(e.into()),
        };

        let serde_json::Value::Object(map) = root else {
            return Ok(Vec::new());
        };

        // The read above holds every plan's metadata already; reading each
        // plan again cost a round trip per plan on a remote store.
        map.iter()
            .map(|(name, plan)| plan_from_tree(name, plan))
            .collect()
    }

    /// Every plan with its tasks (sorted by id), from one read of the plans
    /// tree: what a listing that shows task counts needs, without a read per
    /// plan.
    pub fn list_plans_with_tasks(
        &self,
        ref_name: &str,
    ) -> Result<Vec<(Plan, Vec<Task>)>, TaskStoreError> {
        let root = match self.repo.get_json(ref_name, &self.prefix) {
            Ok(v) => v,
            Err(e) if is_path_not_found(&e) => return Ok(Vec::new()),
            Err(e) => return Err(e.into()),
        };
        let serde_json::Value::Object(map) = root else {
            return Ok(Vec::new());
        };
        map.iter()
            .map(|(name, plan)| Ok((plan_from_tree(name, plan)?, tasks_from_tree(plan)?)))
            .collect()
    }

    /// Fetch a single plan by name.
    pub fn get_plan(&self, ref_name: &str, name: &str) -> Result<Plan, TaskStoreError> {
        let meta_path = paths::plan_meta(&self.prefix, name);
        let value = self
            .repo
            .get_json(ref_name, &meta_path)
            .map_err(|e| map_not_found(e, || TaskStoreError::PlanNotFound(name.to_string())))?;
        Ok(serde_json::from_value(value)?)
    }

    /// Archive a plan — a soft, reversible transition that marks the
    /// plan as no longer active but leaves all task data intact. Valid
    /// for any status (active, completed, empty) — archival never
    /// touches tasks, proofs, or abandonment reasons.
    ///
    /// Uses a CAS retry loop so concurrent plan mutations on the same
    /// branch can't silently overwrite one another. Each retry re-reads
    /// the plan from the snapshotted head, so a competing write that
    /// advanced the ref is picked up on the next pass rather than lost.
    pub fn archive_plan(&self, ref_name: &str, name: &str) -> Result<Plan, TaskStoreError> {
        let meta_path = paths::plan_meta(&self.prefix, name);
        for _ in 0..Self::MAX_CAS_RETRIES {
            // Snapshot the head, then read the plan from that same head so
            // the commit we build applies on top of what we validated.
            let head = self.repo.head(ref_name)?;
            let mut plan = self.get_plan(ref_name, name)?;
            plan.status = PlanStatus::Archived;
            plan.archived_at = Some(Utc::now());

            let value = serde_json::to_value(&plan)?;
            match self.repo.set_json_cas(
                ref_name,
                head,
                &meta_path,
                &value,
                self.commit_opts(format!("Archive plan {}", name)),
            ) {
                Ok(_) => return Ok(plan),
                Err(RepoError::WriteConflict) => continue,
                Err(e) => return Err(e.into()),
            }
        }
        Err(TaskStoreError::WriteConflict)
    }

    /// Close a plan, recording a required `summary`.
    ///
    /// This is the explicit, gated replacement for the old auto-promotion:
    /// terminal task transitions no longer complete the plan on their own.
    /// Closing requires (1) a non-empty `summary` — the plan-level analog of
    /// a task's `proof` — and (2) that every task is already terminal
    /// (`Done`/`Abandoned`), so a plan cannot be closed with work still open.
    ///
    /// Idempotent on an already-closed (`Completed`) plan: returns it
    /// unchanged. Refuses an `Archived` plan. Sets `status = Completed`,
    /// `summary`, `closed_at`, and `closed_by`.
    pub fn close_plan(
        &self,
        ref_name: &str,
        name: &str,
        summary: &str,
    ) -> Result<Plan, TaskStoreError> {
        if summary.trim().is_empty() {
            return Err(TaskStoreError::SummaryRequired);
        }
        let meta_path = paths::plan_meta(&self.prefix, name);
        for _ in 0..Self::MAX_CAS_RETRIES {
            let head = self.repo.head(ref_name)?;
            let mut plan = self.get_plan(ref_name, name)?;
            match plan.status {
                // Idempotent: closing a closed plan is a no-op.
                PlanStatus::Completed => return Ok(plan),
                PlanStatus::Archived => {
                    return Err(TaskStoreError::CannotClose {
                        plan: name.to_string(),
                        reason: "plan is archived".to_string(),
                    });
                }
                PlanStatus::Active => {}
            }

            let tasks = self.list_tasks(ref_name, name)?;
            if tasks.is_empty() {
                return Err(TaskStoreError::CannotClose {
                    plan: name.to_string(),
                    reason: "plan has no tasks".to_string(),
                });
            }
            if let Some(open) = tasks.iter().find(|t| !t.status.is_terminal()) {
                return Err(TaskStoreError::CannotClose {
                    plan: name.to_string(),
                    reason: format!(
                        "task {} is still {:?}; every task must be done or abandoned first",
                        open.id.0, open.status
                    ),
                });
            }

            plan.status = PlanStatus::Completed;
            plan.summary = Some(summary.trim().to_string());
            plan.closed_at = Some(Utc::now());
            plan.closed_by = Some(self.agent_id.clone());

            let value = serde_json::to_value(&plan)?;
            match self.repo.set_json_cas(
                ref_name,
                head,
                &meta_path,
                &value,
                self.commit_opts(format!("Close plan {}", name)),
            ) {
                Ok(_) => return Ok(plan),
                Err(RepoError::WriteConflict) => continue,
                Err(e) => return Err(e.into()),
            }
        }
        Err(TaskStoreError::WriteConflict)
    }

    /// Delete a plan and every task it contains. Destructive — use
    /// `archive_plan` if the history should remain discoverable.
    pub fn delete_plan(&self, ref_name: &str, name: &str) -> Result<(), TaskStoreError> {
        if !self.plan_exists(ref_name, name)? {
            return Err(TaskStoreError::PlanNotFound(name.to_string()));
        }
        let root = paths::plan_root(&self.prefix, name);
        self.repo.delete(
            ref_name,
            &root,
            self.commit_opts(format!("Delete plan {}", name)),
        )?;
        Ok(())
    }

    // -----------------------------------------------------------------------
    // Task operations
    // -----------------------------------------------------------------------

    /// Add a new task to a plan. Task ids are assigned monotonically —
    /// the next available `t-NNN` is picked by scanning existing entries.
    /// `assigned_to` is optional — pass an agent id to record ownership.
    pub fn add_task(
        &self,
        ref_name: &str,
        plan: &str,
        title: &str,
        priority: Priority,
        parent_id: Option<TaskId>,
        blocked_by: Vec<TaskId>,
        assigned_to: Option<String>,
    ) -> Result<Task, TaskStoreError> {
        self.add_task_with_extensions(
            ref_name,
            plan,
            title,
            priority,
            parent_id,
            blocked_by,
            assigned_to,
            AddTaskOptions::default(),
        )
    }

    /// Like `add_task` but also accepts the policy-fallback extension
    /// fields (POLICY_V1.md §22.4). See [`AddTaskOptions`] for field docs.
    ///
    /// Uses a CAS retry loop so concurrent writers across processes are safe.
    /// On each retry, `next_task_number` re-scans the current tree, naturally
    /// picking the next available id even if a concurrent writer added a task
    /// in the meantime.
    pub fn add_task_with_extensions(
        &self,
        ref_name: &str,
        plan: &str,
        title: &str,
        priority: Priority,
        parent_id: Option<TaskId>,
        blocked_by: Vec<TaskId>,
        assigned_to: Option<String>,
        opts: AddTaskOptions,
    ) -> Result<Task, TaskStoreError> {
        let AddTaskOptions {
            payload,
            parent_change,
            on_complete,
        } = opts;
        if !self.plan_exists(ref_name, plan)? {
            return Err(TaskStoreError::PlanNotFound(plan.to_string()));
        }

        if let Some(ref parent) = parent_id {
            let parent_task = self.get_task(ref_name, plan, parent)?;
            if parent_task.parent_id.is_some() {
                return Err(TaskStoreError::ParentIsSubtask(parent.clone()));
            }
        }

        validate_blocker_ids(&blocked_by)?;
        for blocker in &blocked_by {
            self.get_task(ref_name, plan, blocker)?;
        }

        for _ in 0..Self::MAX_CAS_RETRIES {
            // Snapshot BEFORE the next_task_number read so the CAS can detect
            // any interleaved write that might have claimed the same id.
            let head = self.repo.head(ref_name)?;

            let next_num = self.next_task_number(ref_name, plan)?;
            let id = TaskId::new(next_num);

            let task = Task {
                id: id.clone(),
                title: title.to_string(),
                status: TaskStatus::Pending,
                priority,
                parent_id: parent_id.clone(),
                blocked_by: blocked_by.clone(),
                created_at: Utc::now(),
                created_by: self.agent_id.clone(),
                started_at: None,
                started_by: None,
                completed_at: None,
                completed_by: None,
                proof: None,
                abandoned_at: None,
                abandoned_reason: None,
                assigned_to: assigned_to.clone(),
                payload: payload.clone(),
                parent_change: parent_change.clone(),
                on_complete: on_complete.clone(),
            };

            let task_path = paths::task(&self.prefix, plan, &id);
            let value = serde_json::to_value(&task)?;

            match self.repo.set_json_cas(
                ref_name,
                head,
                &task_path,
                &value,
                self.commit_opts(format!("Add task {}/{}", plan, id)),
            ) {
                Ok(_) => return Ok(task),
                Err(RepoError::WriteConflict) => continue,
                Err(e) => return Err(e.into()),
            }
        }
        Err(TaskStoreError::WriteConflict)
    }

    /// List every task id in a plan, cheaply — this walks tree paths
    /// without deserializing task bodies. Use this when you only need
    /// to know which tasks exist (e.g. picking the next task number,
    /// checking blocker existence). Prefer `list_tasks` when you need
    /// task data.
    pub fn task_ids(&self, ref_name: &str, plan: &str) -> Result<Vec<TaskId>, TaskStoreError> {
        let root_path = paths::plan_root(&self.prefix, plan);
        let leaves = match self.repo.list_paths(ref_name, &root_path, None) {
            Ok(v) => v,
            Err(e) if is_path_not_found(&e) => {
                return Err(TaskStoreError::PlanNotFound(plan.to_string()));
            }
            Err(e) => return Err(e.into()),
        };

        let prefix_with_slash = format!("{}/", root_path);
        let mut ids: std::collections::BTreeSet<TaskId> = std::collections::BTreeSet::new();
        for leaf in leaves {
            let Some(suffix) = leaf.strip_prefix(&prefix_with_slash) else {
                continue;
            };
            let first = suffix.split('/').next().unwrap_or("");
            if first.is_empty() || first == paths::META_KEY {
                continue;
            }
            ids.insert(TaskId(first.to_string()));
        }
        Ok(ids.into_iter().collect())
    }

    /// List every task in a plan. Ordered by task id. This fully
    /// deserializes every task — O(n) in total field count. For id-only
    /// operations prefer `task_ids`.
    pub fn list_tasks(&self, ref_name: &str, plan: &str) -> Result<Vec<Task>, TaskStoreError> {
        // One read of the plan's tree: a plan exists when it has metadata.
        let root_path = paths::plan_root(&self.prefix, plan);
        let root = self
            .repo
            .get_json(ref_name, &root_path)
            .map_err(|e| map_not_found(e, || TaskStoreError::PlanNotFound(plan.to_string())))?;
        if root.get(paths::META_KEY).is_none() {
            return Err(TaskStoreError::PlanNotFound(plan.to_string()));
        }
        tasks_from_tree(&root)
    }

    pub fn get_task(
        &self,
        ref_name: &str,
        plan: &str,
        id: &TaskId,
    ) -> Result<Task, TaskStoreError> {
        let path = paths::task(&self.prefix, plan, id);
        let value = self.repo.get_json(ref_name, &path).map_err(|e| {
            map_not_found(e, || TaskStoreError::TaskNotFound {
                plan: plan.to_string(),
                id: id.clone(),
            })
        })?;
        Ok(serde_json::from_value(value)?)
    }

    /// Transition `pending → in_progress`. Fails with `Blocked` if any
    /// blocker is not `done`, or `BlockerNotFound` if any blocker id no
    /// longer exists in the plan (e.g. because the plan was rebuilt
    /// after a delete).
    pub fn start_task(
        &self,
        ref_name: &str,
        plan: &str,
        id: &TaskId,
    ) -> Result<Task, TaskStoreError> {
        self.update_task(
            ref_name,
            plan,
            id,
            format!("Start {}/{}", plan, id),
            |task| {
                check_transition(task.status, Transition::Start)?;

                let BlockerCheck { missing, pending } =
                    self.classify_blockers(ref_name, plan, &task.blocked_by)?;
                if !missing.is_empty() {
                    return Err(TaskStoreError::BlockerNotFound { blockers: missing });
                }
                if !pending.is_empty() {
                    return Err(TaskStoreError::Blocked { blockers: pending });
                }

                task.status = TaskStatus::InProgress;
                task.started_at = Some(Utc::now());
                task.started_by = Some(self.agent_id.clone());
                Ok(())
            },
        )
    }

    /// Transition `in_progress → done`. Requires a `Proof` — it's stored
    /// but NOT verified here (use `verify_plan` for that).
    ///
    /// A terminal task transition does NOT auto-promote the plan to
    /// `Completed`. Closing a plan is an explicit, summary-gated action
    /// (`close_plan`) so implementations own their close workflow and can
    /// require a summary — the plan-level analog of a task's `proof`.
    pub fn complete_task(
        &self,
        ref_name: &str,
        plan: &str,
        id: &TaskId,
        proof: Proof,
    ) -> Result<Task, TaskStoreError> {
        self.update_task(
            ref_name,
            plan,
            id,
            format!("Complete {}/{}", plan, id),
            |task| {
                check_transition(task.status, Transition::Complete)?;
                task.status = TaskStatus::Done;
                task.proof = Some(proof.clone());
                task.completed_at = Some(Utc::now());
                task.completed_by = Some(self.agent_id.clone());
                Ok(())
            },
        )
    }

    /// Transition to `abandoned`. Legal from both `pending` and
    /// `in_progress`. Reason is required. Like `complete_task`, it does not
    /// touch the plan's status.
    pub fn abandon_task(
        &self,
        ref_name: &str,
        plan: &str,
        id: &TaskId,
        reason: &str,
    ) -> Result<Task, TaskStoreError> {
        if reason.trim().is_empty() {
            return Err(TaskStoreError::ReasonRequired);
        }
        self.update_task(
            ref_name,
            plan,
            id,
            format!("Abandon {}/{}", plan, id),
            |task| {
                check_transition(task.status, Transition::Abandon)?;
                task.status = TaskStatus::Abandoned;
                task.abandoned_at = Some(Utc::now());
                task.abandoned_reason = Some(reason.to_string());
                Ok(())
            },
        )
    }

    pub fn set_priority(
        &self,
        ref_name: &str,
        plan: &str,
        id: &TaskId,
        priority: Priority,
    ) -> Result<Task, TaskStoreError> {
        let desc = format!("Set priority {:?} on {}/{}", priority, plan, id);
        self.update_task(ref_name, plan, id, desc, |task| {
            task.priority = priority;
            Ok(())
        })
    }

    /// Replace a task's title. The title must not be blank. Status, proof,
    /// blockers and timestamps are left as they are; the commit records who
    /// changed it.
    pub fn set_title(
        &self,
        ref_name: &str,
        plan: &str,
        id: &TaskId,
        title: &str,
    ) -> Result<Task, TaskStoreError> {
        if title.trim().is_empty() {
            return Err(TaskStoreError::TitleRequired);
        }
        let desc = format!("Retitle {}/{}", plan, id);
        self.update_task(ref_name, plan, id, desc, |task| {
            task.title = title.to_string();
            Ok(())
        })
    }

    /// Replace a task's blocker list. Every blocker must be a task in the same
    /// plan, and the new list must not make the task wait on itself, directly
    /// or through other tasks: a cycle would leave every task in it blocked
    /// for good.
    pub fn set_blockers(
        &self,
        ref_name: &str,
        plan: &str,
        id: &TaskId,
        blockers: Vec<TaskId>,
    ) -> Result<Task, TaskStoreError> {
        validate_blocker_ids(&blockers)?;
        let desc = format!("Update blockers on {}/{}", plan, id);
        self.update_task(ref_name, plan, id, desc, |task| {
            let tasks = self.list_tasks(ref_name, plan)?;
            for blocker in &blockers {
                if !tasks.iter().any(|t| &t.id == blocker) {
                    return Err(TaskStoreError::TaskNotFound {
                        plan: plan.to_string(),
                        id: blocker.clone(),
                    });
                }
            }
            if let Some(cycle) = blocker_cycle(&tasks, &task.id, &blockers) {
                return Err(TaskStoreError::BlockerCycle { cycle });
            }
            task.blocked_by = blockers.clone();
            Ok(())
        })
    }

    /// Set `assigned_to` on a task.
    pub fn assign_task(
        &self,
        ref_name: &str,
        plan: &str,
        id: &TaskId,
        agent: &str,
    ) -> Result<Task, TaskStoreError> {
        let desc = format!("Assign {}/{} to {}", plan, id, agent);
        self.update_task(ref_name, plan, id, desc, |task| {
            task.assigned_to = Some(agent.to_string());
            Ok(())
        })
    }

    /// Clear `assigned_to` on a task.
    pub fn unassign_task(
        &self,
        ref_name: &str,
        plan: &str,
        id: &TaskId,
    ) -> Result<Task, TaskStoreError> {
        self.update_task(
            ref_name,
            plan,
            id,
            format!("Unassign {}/{}", plan, id),
            |task| {
                task.assigned_to = None;
                Ok(())
            },
        )
    }

    // -----------------------------------------------------------------------
    // Query helpers
    // -----------------------------------------------------------------------

    /// Highest-priority `pending` task whose blockers are all `done`.
    /// Ties broken by ascending task id (insertion order).
    pub fn next_task(&self, ref_name: &str, plan: &str) -> Result<Option<Task>, TaskStoreError> {
        self.next_task_for(ref_name, plan, None, true)
    }

    /// Like `next_task`, but filter by assignment.
    ///
    /// - `assigned_to = None` → any pending unblocked task (same as
    ///   `next_task`).
    /// - `assigned_to = Some(agent)`, `include_unassigned = true` →
    ///   tasks assigned to `agent` OR unassigned.
    /// - `assigned_to = Some(agent)`, `include_unassigned = false` →
    ///   only tasks explicitly assigned to `agent`.
    pub fn next_task_for(
        &self,
        ref_name: &str,
        plan: &str,
        assigned_to: Option<&str>,
        include_unassigned: bool,
    ) -> Result<Option<Task>, TaskStoreError> {
        let tasks = self.list_tasks(ref_name, plan)?;
        let mut candidates: Vec<&Task> = tasks
            .iter()
            .filter(|t| t.status == TaskStatus::Pending)
            .filter(|t| t.blocked_by.iter().all(|b| blocker_satisfied(&tasks, b)))
            .filter(|t| match assigned_to {
                None => true,
                Some(agent) => match &t.assigned_to {
                    Some(a) => a == agent,
                    None => include_unassigned,
                },
            })
            .collect();
        candidates.sort_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
        Ok(candidates.first().map(|t| (*t).clone()))
    }

    /// List plans filtered by status. `None` returns all plans.
    pub fn list_plans_by_status(
        &self,
        ref_name: &str,
        status: Option<PlanStatus>,
    ) -> Result<Vec<Plan>, TaskStoreError> {
        let plans = self.list_plans(ref_name)?;
        match status {
            None => Ok(plans),
            Some(s) => Ok(plans.into_iter().filter(|p| p.status == s).collect()),
        }
    }

    /// Compute the rollup status of a parent task from its direct
    /// subtasks. Read-only — does not mutate storage.
    ///
    /// Rules:
    /// - `Done` if every non-abandoned subtask is `Done`.
    /// - `InProgress` if any subtask is `InProgress`.
    /// - `Pending` otherwise.
    ///
    /// If the parent has no subtasks, returns the parent's own status.
    pub fn derived_status(
        &self,
        ref_name: &str,
        plan: &str,
        parent_id: &TaskId,
    ) -> Result<TaskStatus, TaskStoreError> {
        let tasks = self.list_tasks(ref_name, plan)?;
        let parent = tasks.iter().find(|t| &t.id == parent_id).ok_or_else(|| {
            TaskStoreError::TaskNotFound {
                plan: plan.to_string(),
                id: parent_id.clone(),
            }
        })?;

        let subtasks: Vec<&Task> = tasks
            .iter()
            .filter(|t| t.parent_id.as_ref() == Some(parent_id))
            .collect();

        if subtasks.is_empty() {
            return Ok(parent.status);
        }

        if subtasks.iter().any(|t| t.status == TaskStatus::InProgress) {
            return Ok(TaskStatus::InProgress);
        }

        let non_abandoned: Vec<&&Task> = subtasks
            .iter()
            .filter(|t| t.status != TaskStatus::Abandoned)
            .collect();

        if !non_abandoned.is_empty() && non_abandoned.iter().all(|t| t.status == TaskStatus::Done) {
            return Ok(TaskStatus::Done);
        }

        Ok(TaskStatus::Pending)
    }

    /// Walk every `done` task and run the given verifier against each proof.
    /// Non-`done` tasks are skipped.
    pub fn verify_plan(
        &self,
        ref_name: &str,
        plan: &str,
        verifier: &dyn Verifier,
    ) -> Result<VerifyReport, TaskStoreError> {
        let tasks = self.list_tasks(ref_name, plan)?;
        let mut results = Vec::new();
        for task in tasks.iter().filter(|t| t.status == TaskStatus::Done) {
            let proof = task.proof.as_ref().ok_or(TaskStoreError::ProofRequired)?;
            let outcome = verifier.verify(proof);
            results.push(VerifyEntry {
                task_id: task.id.clone(),
                result: outcome,
            });
        }
        Ok(VerifyReport {
            plan: plan.to_string(),
            results,
        })
    }

    // -----------------------------------------------------------------------
    // Internals
    // -----------------------------------------------------------------------

    fn plan_exists(&self, ref_name: &str, name: &str) -> Result<bool, TaskStoreError> {
        match self.get_plan(ref_name, name) {
            Ok(_) => Ok(true),
            Err(TaskStoreError::PlanNotFound(_)) => Ok(false),
            Err(e) => Err(e),
        }
    }

    fn next_task_number(&self, ref_name: &str, plan: &str) -> Result<u32, TaskStoreError> {
        let ids = self.task_ids(ref_name, plan)?;
        let max = ids
            .iter()
            .filter_map(|id| id.number().ok())
            .max()
            .unwrap_or(0);
        Ok(max + 1)
    }

    fn classify_blockers(
        &self,
        ref_name: &str,
        plan: &str,
        blockers: &[TaskId],
    ) -> Result<BlockerCheck, TaskStoreError> {
        if blockers.is_empty() {
            return Ok(BlockerCheck::default());
        }
        let tasks = self.list_tasks(ref_name, plan)?;
        let mut missing = Vec::new();
        let mut pending = Vec::new();
        for b in blockers {
            match tasks.iter().find(|t| &t.id == b) {
                None => missing.push(b.clone()),
                Some(t) if t.status != TaskStatus::Done => pending.push(b.clone()),
                _ => {}
            }
        }
        Ok(BlockerCheck { missing, pending })
    }

    /// Read-modify-write one task without losing a concurrent update.
    ///
    /// Every transition reads the whole task, changes a field or two, and
    /// writes the whole task back. Landing that with a plain `set_json` moved
    /// the ref safely but wrote the value read earlier, so a concurrent update
    /// to the same task was reverted while both calls returned Ok (a
    /// complete racing an assign lost one or the other every time). Snapshot
    /// the head before reading, apply `change` to what was read, and land it
    /// with `set_json_cas` against that head; if anything moved the ref in
    /// between, re-read and re-apply — which also re-validates the transition
    /// against the fresh task.
    fn update_task<F>(
        &self,
        ref_name: &str,
        plan: &str,
        id: &TaskId,
        description: String,
        mut change: F,
    ) -> Result<Task, TaskStoreError>
    where
        F: FnMut(&mut Task) -> Result<(), TaskStoreError>,
    {
        for _ in 0..Self::MAX_CAS_RETRIES {
            let head = self.repo.head(ref_name)?;
            let mut task = self.get_task(ref_name, plan, id)?;
            change(&mut task)?;
            let path = paths::task(&self.prefix, plan, &task.id);
            let value = serde_json::to_value(&task)?;
            match self.repo.set_json_cas(
                ref_name,
                head,
                &path,
                &value,
                self.commit_opts(description.clone()),
            ) {
                Ok(_) => return Ok(task),
                Err(RepoError::WriteConflict) => continue,
                Err(e) => return Err(e.into()),
            }
        }
        Err(TaskStoreError::WriteConflict)
    }

    fn commit_opts(&self, description: impl Into<String>) -> CommitOptions {
        CommitOptions::new(&self.agent_id, IntentCategory::Plan, description)
    }
}

/// A blocker is satisfied iff it names a task in the same plan whose
/// status is `Done`. Abandoned blockers are NOT considered satisfied —
/// an agent who abandons a blocker must explicitly re-open the
/// blockers on the dependent task (via `set_blockers`) before starting
/// it. Missing blockers (the task no longer exists) are also not
/// satisfied and surface as `BlockerNotFound` at `start_task` time.
fn blocker_satisfied(tasks: &[Task], id: &TaskId) -> bool {
    tasks
        .iter()
        .any(|t| &t.id == id && t.status == TaskStatus::Done)
}

/// The cycle that making `blockers` the blockers of `id` would close, as the
/// path from `id` back to itself: `[t-001, t-003, t-001]`, or `[t-001, t-001]`
/// for a task that would block itself. `None` when the plan's blocker graph
/// stays acyclic. The other tasks' blockers come from `tasks`.
fn blocker_cycle(tasks: &[Task], id: &TaskId, blockers: &[TaskId]) -> Option<Vec<TaskId>> {
    let edges: HashMap<&TaskId, &[TaskId]> = tasks
        .iter()
        .map(|t| (&t.id, t.blocked_by.as_slice()))
        .collect();
    let mut visited = HashSet::new();
    let mut path = vec![id.clone()];
    blockers
        .iter()
        .any(|b| reaches(b, id, &edges, &mut visited, &mut path))
        .then_some(path)
}

/// Depth-first along `blocked_by` from `node`: true when it reaches `target`,
/// with `path` then holding the route there.
fn reaches<'a>(
    node: &'a TaskId,
    target: &TaskId,
    edges: &HashMap<&'a TaskId, &'a [TaskId]>,
    visited: &mut HashSet<&'a TaskId>,
    path: &mut Vec<TaskId>,
) -> bool {
    path.push(node.clone());
    if node == target {
        return true;
    }
    if visited.insert(node) {
        for next in edges.get(node).copied().unwrap_or_default() {
            if reaches(next, target, edges, visited, path) {
                return true;
            }
        }
    }
    path.pop();
    false
}

#[derive(Default, Debug)]
struct BlockerCheck {
    /// Blocker ids that are not currently `Done` but DO exist in the plan.
    pending: Vec<TaskId>,
    /// Blocker ids that no longer resolve to any task in the plan.
    missing: Vec<TaskId>,
}

/// True only when a read failed because the *path* is genuinely absent — a
/// key that was never written. This must NOT match `TreeError::ObjectNotFound`,
/// which means an object referenced by the tree is missing from the store
/// (repository corruption / a dangling interior node). Conflating the two made
/// `list_plans`/`list_tasks` silently return an empty collection over a
/// corrupt tree, masking data loss as "no plans". Corruption now propagates.
fn is_path_not_found(e: &agentstategraph::RepoError) -> bool {
    matches!(
        e,
        agentstategraph::RepoError::Tree(agentstategraph::tree::TreeError::PathNotFound(_))
    )
}

/// A plan's metadata from its subtree of the plans tree (`plan` is the value
/// at `<prefix>/<name>`).
fn plan_from_tree(name: &str, plan: &serde_json::Value) -> Result<Plan, TaskStoreError> {
    let meta = plan
        .get(paths::META_KEY)
        .ok_or_else(|| TaskStoreError::PlanNotFound(name.to_string()))?;
    Ok(serde_json::from_value(meta.clone())?)
}

/// The tasks in a plan's subtree, sorted by id.
fn tasks_from_tree(plan: &serde_json::Value) -> Result<Vec<Task>, TaskStoreError> {
    let serde_json::Value::Object(map) = plan else {
        return Ok(Vec::new());
    };
    let mut tasks = map
        .iter()
        .filter(|(key, _)| key.as_str() != paths::META_KEY)
        .map(|(_, value)| serde_json::from_value::<Task>(value.clone()))
        .collect::<Result<Vec<_>, _>>()?;
    tasks.sort_by_key(|t| t.id.clone());
    Ok(tasks)
}

fn map_not_found<F>(e: agentstategraph::RepoError, make: F) -> TaskStoreError
where
    F: FnOnce() -> TaskStoreError,
{
    if is_path_not_found(&e) {
        make()
    } else {
        e.into()
    }
}

#[cfg(test)]
mod path_not_found_tests {
    use super::is_path_not_found;
    use agentstategraph::RepoError;
    use agentstategraph::core::ObjectId;
    use agentstategraph::tree::TreeError;

    #[test]
    fn path_not_found_is_classified_as_empty() {
        let e = RepoError::Tree(TreeError::PathNotFound("/plans/foo".into()));
        assert!(is_path_not_found(&e));
    }

    #[test]
    fn object_not_found_is_not_empty() {
        // A dangling interior object is corruption, not an absent path — it must
        // NOT be swallowed as an empty collection.
        let e = RepoError::Tree(TreeError::ObjectNotFound(ObjectId::from_bytes([7u8; 32])));
        assert!(
            !is_path_not_found(&e),
            "ObjectNotFound must propagate as an error, not read as empty"
        );
    }
}