bea-rs 0.8.1

A file-based task tracker CLI and MCP server for AI agent workflows
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
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{CallToolResult, Implementation, ServerCapabilities, ServerInfo};
use rmcp::{ServerHandler, tool, tool_handler, tool_router};

use bears::error::Error;
use bears::service;
use bears::store;
use bears::task::{self, Priority, Status, Task};

use super::params::*;
use super::{BeaMcp, ok_json, tool_ok};

#[tool_router]
impl BeaMcp {
    #[tool(description = "List tasks that are ready to work on (open with all dependencies done)")]
    async fn list_ready(
        &self,
        Parameters(params): Parameters<ListReadyParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let tasks = store::load_all(&self.base).await?;
                let limit = params.limit.map(|v| v as usize);
                let ready = service::list_ready(
                    &tasks,
                    params.tag.as_deref(),
                    limit,
                    params.epic.as_deref(),
                );
                let eff = service::effective_priorities(&tasks);
                let summaries: Vec<_> = ready.iter().map(|t| t.summary(eff.get(&t.id))).collect();
                ok_json(serde_json::json!(summaries))
            }
            .await,
        )
    }

    #[tool(description = "List tasks with optional filters")]
    async fn list_all_tasks(
        &self,
        Parameters(params): Parameters<ListTasksFilterParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let tasks = store::load_all(&self.base).await?;
                // active_only=true → include_all=false (hide done/cancelled)
                let include_all = !params.active_only.unwrap_or(false);
                let mut filtered = service::list_tasks(
                    &tasks,
                    params.status,
                    params.priority,
                    params.tag.as_deref(),
                    include_all,
                    params.epic.as_deref(),
                );
                if let Some(limit) = params.limit {
                    filtered.truncate(limit as usize);
                }
                let eff = service::effective_priorities(&tasks);
                let summaries: Vec<_> =
                    filtered.iter().map(|t| t.summary(eff.get(&t.id))).collect();
                ok_json(serde_json::json!(summaries))
            }
            .await,
        )
    }

    #[tool(description = "Get full details of a single task. If the id isn't an \
                       active task, falls back to the archive; an archived \
                       result is marked with \"archived\": true.")]
    async fn get_task(
        &self,
        Parameters(params): Parameters<TaskIdParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let tasks = store::load_all(&self.base).await?;
                match service::get_task(&tasks, &params.id) {
                    Ok(t) => {
                        let eff = service::effective_priorities(&tasks);
                        let ep = eff.get(&t.id);
                        ok_json(serde_json::to_value(t.detail(ep))?)
                    }
                    // Not in the active store — fall back to the archive (read-only).
                    Err(Error::TaskNotFound(id)) => {
                        match service::get_archived_task(&self.base, &params.id).await {
                            Ok(t) => {
                                let mut v = serde_json::to_value(t.detail(None))?;
                                if let Some(obj) = v.as_object_mut() {
                                    obj.insert("archived".into(), serde_json::Value::Bool(true));
                                }
                                ok_json(v)
                            }
                            // Neither active nor archived: report the original miss.
                            Err(_) => Err(Error::TaskNotFound(id)),
                        }
                    }
                    Err(e) => Err(e),
                }
            }
            .await,
        )
    }

    #[tool(description = "Create a new task")]
    async fn create_task(
        &self,
        Parameters(params): Parameters<CreateTaskParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let tasks = store::load_all(&self.base).await?;
                let priority = params.priority.unwrap_or(Priority::P2);
                let task_type = params.task_type.unwrap_or_default();

                let t = service::create_task(
                    &self.base,
                    &tasks,
                    params.title,
                    priority,
                    params.tags.unwrap_or_default(),
                    params.depends_on.unwrap_or_default(),
                    params.parent,
                    params.body.unwrap_or_default(),
                    task_type,
                )?;
                ok_json(serde_json::to_value(t.summary(None))?)
            }
            .await,
        )
    }

    #[tool(description = "Update task fields")]
    async fn update_task(
        &self,
        Parameters(params): Parameters<UpdateTaskParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let tasks = store::load_all(&self.base).await?;
                // Map MCP parent: None = unchanged, "" = clear, "id" = set
                let parent_update: Option<Option<String>> = params
                    .parent
                    .map(|p| if p.is_empty() { None } else { Some(p) });
                let t = service::update_task(
                    &self.base,
                    &tasks,
                    &params.id,
                    params.status,
                    params.priority,
                    params.tags,
                    params.assignee,
                    params.body,
                    params.title,
                    parent_update,
                )?;
                ok_json(serde_json::to_value(t.summary(None))?)
            }
            .await,
        )
    }

    #[tool(description = "Start a task (set status to in_progress)")]
    async fn start_task(
        &self,
        Parameters(params): Parameters<TaskIdParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let tasks = store::load_all(&self.base).await?;
                let t = service::set_status(&self.base, &tasks, &params.id, Status::InProgress)?;
                ok_json(serde_json::to_value(t.summary(None))?)
            }
            .await,
        )
    }

    #[tool(description = "Complete a task (set status to done)")]
    async fn complete_task(
        &self,
        Parameters(params): Parameters<TaskIdParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let tasks = store::load_all(&self.base).await?;
                let t = service::set_status(&self.base, &tasks, &params.id, Status::Done)?;
                ok_json(serde_json::to_value(t.summary(None))?)
            }
            .await,
        )
    }

    #[tool(description = "Add a dependency between tasks")]
    async fn add_dependency(
        &self,
        Parameters(params): Parameters<DepParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let tasks = store::load_all(&self.base).await?;
                let t =
                    service::add_dependency(&self.base, &tasks, &params.id, &params.depends_on)?;
                ok_json(serde_json::to_value(t.summary(None))?)
            }
            .await,
        )
    }

    #[tool(description = "Remove a dependency between tasks")]
    async fn remove_dependency(
        &self,
        Parameters(params): Parameters<DepParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let tasks = store::load_all(&self.base).await?;
                let t =
                    service::remove_dependency(&self.base, &tasks, &params.id, &params.depends_on)?;
                ok_json(serde_json::to_value(t.summary(None))?)
            }
            .await,
        )
    }

    #[tool(description = "Search tasks by text query")]
    async fn search_tasks(
        &self,
        Parameters(params): Parameters<SearchParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let tasks = store::load_all(&self.base).await?;
                let include_all = !params.active_only.unwrap_or(false);
                let mut results = service::search_tasks(&tasks, &params.query, include_all);
                if let Some(limit) = params.limit {
                    results.truncate(limit as usize);
                }
                let summaries: Vec<_> = results.iter().map(|t| t.summary(None)).collect();
                ok_json(serde_json::json!(summaries))
            }
            .await,
        )
    }

    #[tool(description = "Cancel a task (set status to cancelled)")]
    async fn cancel_task(
        &self,
        Parameters(params): Parameters<TaskIdParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let tasks = store::load_all(&self.base).await?;
                let t = service::set_status(&self.base, &tasks, &params.id, Status::Cancelled)?;
                ok_json(serde_json::to_value(t.summary(None))?)
            }
            .await,
        )
    }

    #[tool(
        description = "DEPRECATED: Permanently hard-deletes cancelled (and optionally done) tasks. \
        Prefer archive_task (no id → sweep) which moves settled tasks to the archive instead of \
        destroying them, keeping history recoverable via restore_task. \
        prune_tasks remains available for cases where permanent deletion is intentional."
    )]
    async fn prune_tasks(
        &self,
        Parameters(params): Parameters<PruneParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let tasks = store::load_all(&self.base).await?;
                let include_done = params.include_done.unwrap_or(false);
                let deleted = service::prune_tasks(&self.base, &tasks, include_done)?;
                let summaries: Vec<_> = deleted.iter().map(|t| t.summary(None)).collect();
                ok_json(serde_json::json!(summaries))
            }
            .await,
        )
    }

    #[tool(description = "Permanently delete a task by ID")]
    async fn delete_task(
        &self,
        Parameters(params): Parameters<TaskIdParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let tasks = store::load_all(&self.base).await?;
                let t = service::delete_task(&self.base, &tasks, &params.id)?;
                ok_json(serde_json::to_value(t.summary(None))?)
            }
            .await,
        )
    }

    #[tool(description = "Get the dependency graph as a bounded adjacency list. \
        Excludes isolated and done/cancelled nodes by default.")]
    async fn get_graph(
        &self,
        Parameters(params): Parameters<GetGraphParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let tasks = store::load_all(&self.base).await?;
                let graph = service::build_graph(&tasks);
                let include_done = params.include_done.unwrap_or(false);
                let limit = params.limit.map(|v| v as usize);
                let adj = graph.bounded_adjacency_list(
                    &tasks,
                    include_done,
                    params.epic.as_deref(),
                    limit,
                );
                ok_json(serde_json::json!(adj))
            }
            .await,
        )
    }

    #[tool(
        description = "Return the children of an epic in topological execution order (plan view)"
    )]
    async fn plan_epic(
        &self,
        Parameters(params): Parameters<PlanEpicParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let tasks = store::load_all(&self.base).await?;
                let plan = service::plan_epic(&tasks, &params.id)?;
                // Cyclic children cannot be ordered; append them so nothing is lost.
                let all: Vec<&Task> = plan
                    .tasks
                    .iter()
                    .chain(plan.cyclic.iter())
                    .copied()
                    .collect();
                let eff = service::effective_priorities(&tasks);
                let summaries: Vec<_> = all.iter().map(|t| t.summary(eff.get(&t.id))).collect();
                ok_json(serde_json::json!(summaries))
            }
            .await,
        )
    }

    #[tool(description = "Archive a task (and its settled epic children) by ID, \
        or sweep all archivable tasks when no ID is given. \
        Only Done/Cancelled tasks with no active dependents can be archived. \
        Archived tasks are hidden from all active-task tools.")]
    async fn archive_task(
        &self,
        Parameters(params): Parameters<ArchiveTaskParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let tasks = store::load_all(&self.base).await?;
                let archived_ids = match params.id {
                    Some(ref id) => service::archive_task(&self.base, &tasks, id)?,
                    None => service::archive_all(&self.base, &tasks)?,
                };
                ok_json(serde_json::json!(archived_ids))
            }
            .await,
        )
    }

    #[tool(
        description = "Restore an archived task (and its archived dependencies/parent epic) \
        back to the active store."
    )]
    async fn restore_task(
        &self,
        Parameters(params): Parameters<RestoreTaskParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let restored_ids = service::restore_task(&self.base, &params.id).await?;
                ok_json(serde_json::json!(restored_ids))
            }
            .await,
        )
    }

    #[tool(description = "List archived tasks sorted by most recently updated. \
        Use limit to cap the number returned.")]
    async fn list_archived(
        &self,
        Parameters(params): Parameters<ListArchivedParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let limit = params.limit.map(|v| v as usize);
                let archived = service::list_archive(&self.base, limit).await?;
                let summaries: Vec<_> = archived.iter().map(|t| t.summary(None)).collect();
                ok_json(serde_json::json!(summaries))
            }
            .await,
        )
    }

    #[tool(description = "List all epics with progress summary")]
    async fn list_epics(&self) -> Result<CallToolResult, rmcp::ErrorData> {
        tool_ok(
            async {
                let tasks = store::load_all(&self.base).await?;
                let mut epics: Vec<&task::Task> =
                    tasks.values().filter(|t| t.task_type.is_epic()).collect();
                epics.sort_by(|a, b| a.priority.cmp(&b.priority).then(a.created.cmp(&b.created)));
                let summaries: Vec<_> = epics
                    .iter()
                    .map(|t| t.epic_summary(service::epic_progress(&tasks, &t.id)))
                    .collect();
                ok_json(serde_json::json!(summaries))
            }
            .await,
        )
    }
}

#[tool_handler]
impl ServerHandler for BeaMcp {
    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
            .with_server_info(Implementation::new("bears", env!("CARGO_PKG_VERSION")))
            .with_instructions(
                "bears is a file-based task tracker. Use tools to manage tasks and dependencies. \
                Completed or cancelled tasks can be archived with archive_task to keep the active \
                list clean. Use list_archived to browse the archive and restore_task to bring a \
                task back to active."
                    .to_string(),
            )
    }
}

impl BeaMcp {
    pub(super) fn build_tool_router() -> ToolRouter<Self> {
        Self::tool_router()
    }
}

#[cfg(test)]
mod tests {
    use rmcp::handler::server::wrapper::Parameters;
    use rmcp::model::{CallToolResult, ContentBlock};

    use bears::store;
    use bears::task::{Priority, Status, TaskType};

    use super::super::BeaMcp;
    use super::super::params::*;

    use tempfile::TempDir;

    fn setup() -> (TempDir, BeaMcp) {
        let tmp = TempDir::new().unwrap();
        store::init(tmp.path()).unwrap();
        let mcp = BeaMcp::new(tmp.path().to_path_buf());
        (tmp, mcp)
    }

    fn extract_json(result: &CallToolResult) -> serde_json::Value {
        let text = match &result.content[0] {
            ContentBlock::Text(t) => &t.text,
            _ => panic!("expected text content"),
        };
        serde_json::from_str(text).unwrap()
    }

    fn extract_text(result: &CallToolResult) -> &str {
        match &result.content[0] {
            ContentBlock::Text(t) => &t.text,
            _ => panic!("expected text content"),
        }
    }

    #[tokio::test]
    async fn test_tool_create_and_list() {
        let (_tmp, mcp) = setup();
        let result = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Test task".into(),
                priority: Some(Priority::P1),
                tags: Some(vec!["backend".into()]),
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let json = extract_json(&result);
        assert_eq!(json["title"], "Test task");
        let id = json["id"].as_str().unwrap();

        let list = mcp
            .list_all_tasks(Parameters(ListTasksFilterParams {
                status: None,
                priority: None,
                tag: None,
                epic: None,
                limit: None,
                active_only: None,
            }))
            .await
            .unwrap();
        let arr = extract_json(&list);
        let arr = arr.as_array().unwrap();
        assert_eq!(arr.len(), 1);
        assert_eq!(arr[0]["id"], id);
    }

    #[tokio::test]
    async fn test_tool_get_task() {
        let (_tmp, mcp) = setup();
        let result = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Detail task".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: Some("Some body".into()),
                task_type: None,
            }))
            .await
            .unwrap();
        let id = extract_json(&result)["id"].as_str().unwrap().to_string();

        let detail = mcp.get_task(Parameters(TaskIdParams { id })).await.unwrap();
        let json = extract_json(&detail);
        assert_eq!(json["title"], "Detail task");
        assert_eq!(json["body"], "Some body");
    }

    #[tokio::test]
    async fn test_tool_get_task_falls_back_to_archive() {
        let (_tmp, mcp) = setup();
        // Create, complete, and archive a task.
        let created = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Archived detail".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: Some("archived body".into()),
                task_type: None,
            }))
            .await
            .unwrap();
        let id = extract_json(&created)["id"].as_str().unwrap().to_string();
        mcp.complete_task(Parameters(TaskIdParams { id: id.clone() }))
            .await
            .unwrap();
        mcp.archive_task(Parameters(ArchiveTaskParams {
            id: Some(id.clone()),
        }))
        .await
        .unwrap();

        // get_task on the archived id resolves via the archive fallback and is
        // flagged as archived.
        let detail = mcp
            .get_task(Parameters(TaskIdParams { id: id.clone() }))
            .await
            .unwrap();
        let json = extract_json(&detail);
        assert_eq!(json["title"], "Archived detail");
        assert_eq!(json["archived"], true);

        // A genuinely unknown id (neither active nor archived) reports an
        // in-band tool error.
        let missing = mcp
            .get_task(Parameters(TaskIdParams { id: "nope".into() }))
            .await
            .unwrap();
        assert_eq!(missing.is_error, Some(true));
        assert!(extract_text(&missing).contains("not found"));
    }

    #[tokio::test]
    async fn test_tool_start_complete() {
        let (_tmp, mcp) = setup();
        let result = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Flow task".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id = extract_json(&result)["id"].as_str().unwrap().to_string();

        let started = mcp
            .start_task(Parameters(TaskIdParams { id: id.clone() }))
            .await
            .unwrap();
        assert_eq!(extract_json(&started)["status"], "in_progress");

        let completed = mcp
            .complete_task(Parameters(TaskIdParams { id }))
            .await
            .unwrap();
        assert_eq!(extract_json(&completed)["status"], "done");
    }

    #[tokio::test]
    async fn test_tool_ready() {
        let (_tmp, mcp) = setup();
        let t1 = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "First".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id1 = extract_json(&t1)["id"].as_str().unwrap().to_string();

        mcp.create_task(Parameters(CreateTaskParams {
            title: "Second".into(),
            priority: None,
            tags: None,
            depends_on: Some(vec![id1.clone()]),
            parent: None,
            body: None,
            task_type: None,
        }))
        .await
        .unwrap();

        // Only first should be ready
        let ready = mcp
            .list_ready(Parameters(ListReadyParams {
                limit: None,
                tag: None,
                epic: None,
            }))
            .await
            .unwrap();
        let arr = extract_json(&ready);
        let arr = arr.as_array().unwrap();
        assert_eq!(arr.len(), 1);
        assert_eq!(arr[0]["title"], "First");

        // Complete first
        mcp.complete_task(Parameters(TaskIdParams { id: id1 }))
            .await
            .unwrap();

        // Now second should be ready
        let ready = mcp
            .list_ready(Parameters(ListReadyParams {
                limit: None,
                tag: None,
                epic: None,
            }))
            .await
            .unwrap();
        let arr = extract_json(&ready);
        let arr = arr.as_array().unwrap();
        assert_eq!(arr.len(), 1);
        assert_eq!(arr[0]["title"], "Second");
    }

    #[tokio::test]
    async fn test_tool_dependency_cycle() {
        let (_tmp, mcp) = setup();
        let t1 = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "A".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id_a = extract_json(&t1)["id"].as_str().unwrap().to_string();

        let t2 = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "B".into(),
                priority: None,
                tags: None,
                depends_on: Some(vec![id_a.clone()]),
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id_b = extract_json(&t2)["id"].as_str().unwrap().to_string();

        let result = mcp
            .add_dependency(Parameters(DepParams {
                id: id_a,
                depends_on: id_b,
            }))
            .await
            .unwrap();
        assert_eq!(result.is_error, Some(true));
    }

    #[tokio::test]
    async fn test_tool_search() {
        let (_tmp, mcp) = setup();
        mcp.create_task(Parameters(CreateTaskParams {
            title: "Implement OAuth".into(),
            priority: None,
            tags: Some(vec!["auth".into()]),
            depends_on: None,
            parent: None,
            body: None,
            task_type: None,
        }))
        .await
        .unwrap();
        mcp.create_task(Parameters(CreateTaskParams {
            title: "Fix database".into(),
            priority: None,
            tags: None,
            depends_on: None,
            parent: None,
            body: None,
            task_type: None,
        }))
        .await
        .unwrap();

        let results = mcp
            .search_tasks(Parameters(SearchParams {
                query: "OAuth".into(),
                limit: None,
                active_only: None,
            }))
            .await
            .unwrap();
        let arr = extract_json(&results);
        let arr = arr.as_array().unwrap();
        assert_eq!(arr.len(), 1);
        assert_eq!(arr[0]["title"], "Implement OAuth");
    }

    #[tokio::test]
    async fn test_tool_delete_task() {
        let (_tmp, mcp) = setup();
        let result = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "To be deleted".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id = extract_json(&result)["id"].as_str().unwrap().to_string();

        let deleted = mcp
            .delete_task(Parameters(TaskIdParams { id: id.clone() }))
            .await
            .unwrap();
        assert_eq!(extract_json(&deleted)["id"], id);

        // Should no longer be findable
        let not_found = mcp.get_task(Parameters(TaskIdParams { id })).await.unwrap();
        assert_eq!(not_found.is_error, Some(true));
    }

    #[tokio::test]
    async fn test_tool_graph() {
        let (_tmp, mcp) = setup();
        let t1 = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "A".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id_a = extract_json(&t1)["id"].as_str().unwrap().to_string();

        mcp.create_task(Parameters(CreateTaskParams {
            title: "B".into(),
            priority: None,
            tags: None,
            depends_on: Some(vec![id_a]),
            parent: None,
            body: None,
            task_type: None,
        }))
        .await
        .unwrap();

        let graph = mcp
            .get_graph(Parameters(GetGraphParams {
                include_done: None,
                epic: None,
                limit: None,
            }))
            .await
            .unwrap();
        let json = extract_json(&graph);
        assert!(json.is_object());
    }

    #[tokio::test]
    async fn test_tool_get_graph_bounded() {
        let (_tmp, mcp) = setup();

        // Create A -> B dependency (both active)
        let t_a = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "A".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id_a = extract_json(&t_a)["id"].as_str().unwrap().to_string();

        mcp.create_task(Parameters(CreateTaskParams {
            title: "B".into(),
            priority: None,
            tags: None,
            depends_on: Some(vec![id_a.clone()]),
            parent: None,
            body: None,
            task_type: None,
        }))
        .await
        .unwrap();

        // Create a done isolated task C (no deps, no dependents)
        let t_c = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "C (isolated)".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id_c = extract_json(&t_c)["id"].as_str().unwrap().to_string();
        mcp.complete_task(Parameters(TaskIdParams { id: id_c.clone() }))
            .await
            .unwrap();

        // Create an open isolated task D (no edges)
        let t_d = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "D (isolated open)".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id_d = extract_json(&t_d)["id"].as_str().unwrap().to_string();

        // Default get_graph: excludes done (C) and isolated (D)
        let graph = mcp
            .get_graph(Parameters(GetGraphParams {
                include_done: None,
                epic: None,
                limit: None,
            }))
            .await
            .unwrap();
        let json = extract_json(&graph);
        let obj = json.as_object().unwrap();
        // A and B should be in the graph (they have an edge between them)
        assert!(obj.contains_key(id_a.as_str()), "A should be in graph");
        // C is done → excluded
        assert!(
            !obj.contains_key(id_c.as_str()),
            "done task C should be excluded"
        );
        // D is isolated (no edges) → excluded
        assert!(
            !obj.contains_key(id_d.as_str()),
            "isolated task D should be excluded"
        );

        // include_done=true: C is now eligible, but C is still isolated → still excluded
        let graph_all = mcp
            .get_graph(Parameters(GetGraphParams {
                include_done: Some(true),
                epic: None,
                limit: None,
            }))
            .await
            .unwrap();
        let obj_all = extract_json(&graph_all);
        let obj_all = obj_all.as_object().unwrap();
        // C is done but still isolated → excluded
        assert!(
            !obj_all.contains_key(id_c.as_str()),
            "isolated done task C should still be excluded"
        );
    }

    #[tokio::test]
    async fn test_tool_update_title() {
        let (_tmp, mcp) = setup();
        let result = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Original Title".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id = extract_json(&result)["id"].as_str().unwrap().to_string();

        // Rename the task via update_task
        let updated = mcp
            .update_task(Parameters(UpdateTaskParams {
                id: id.clone(),
                title: Some("Renamed Title".into()),
                status: None,
                priority: None,
                tags: None,
                assignee: None,
                body: None,
                parent: None,
            }))
            .await
            .unwrap();
        let json = extract_json(&updated);
        assert_eq!(json["title"], "Renamed Title");
        assert_eq!(json["id"], id);

        // Confirm the change persists when fetched
        let detail = mcp.get_task(Parameters(TaskIdParams { id })).await.unwrap();
        assert_eq!(extract_json(&detail)["title"], "Renamed Title");
    }

    #[tokio::test]
    async fn test_tool_list_limit_and_active_only() {
        let (_tmp, mcp) = setup();

        // Create 3 tasks; complete one
        for title in &["Alpha", "Beta", "Gamma"] {
            mcp.create_task(Parameters(CreateTaskParams {
                title: (*title).into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        }

        // Complete "Alpha"
        let all = mcp
            .list_all_tasks(Parameters(ListTasksFilterParams {
                status: None,
                priority: None,
                tag: None,
                epic: None,
                limit: None,
                active_only: None,
            }))
            .await
            .unwrap();
        let arr = extract_json(&all);
        let alpha_id = arr
            .as_array()
            .unwrap()
            .iter()
            .find(|x| x["title"] == "Alpha")
            .unwrap()["id"]
            .as_str()
            .unwrap()
            .to_string();
        mcp.complete_task(Parameters(TaskIdParams {
            id: alpha_id.clone(),
        }))
        .await
        .unwrap();

        // active_only=true should exclude the done task
        let active = mcp
            .list_all_tasks(Parameters(ListTasksFilterParams {
                status: None,
                priority: None,
                tag: None,
                epic: None,
                limit: None,
                active_only: Some(true),
            }))
            .await
            .unwrap();
        let active_arr = extract_json(&active);
        let active_arr = active_arr.as_array().unwrap();
        assert_eq!(active_arr.len(), 2, "done task excluded with active_only");
        assert!(
            active_arr.iter().all(|x| x["id"] != alpha_id),
            "completed task should not appear"
        );

        // active_only=false (default) shows all 3
        let all2 = mcp
            .list_all_tasks(Parameters(ListTasksFilterParams {
                status: None,
                priority: None,
                tag: None,
                epic: None,
                limit: None,
                active_only: Some(false),
            }))
            .await
            .unwrap();
        assert_eq!(extract_json(&all2).as_array().unwrap().len(), 3);

        // limit=1 returns only one
        let limited = mcp
            .list_all_tasks(Parameters(ListTasksFilterParams {
                status: None,
                priority: None,
                tag: None,
                epic: None,
                limit: Some(1),
                active_only: None,
            }))
            .await
            .unwrap();
        assert_eq!(extract_json(&limited).as_array().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn test_tool_search_limit_and_active_only() {
        let (_tmp, mcp) = setup();

        // Create 3 tasks all matching query "task"
        for title in &["task one", "task two", "task three"] {
            mcp.create_task(Parameters(CreateTaskParams {
                title: (*title).into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        }

        // Get id of "task one" and complete it
        let all = mcp
            .search_tasks(Parameters(SearchParams {
                query: "task one".into(),
                limit: None,
                active_only: None,
            }))
            .await
            .unwrap();
        let one_id = extract_json(&all).as_array().unwrap()[0]["id"]
            .as_str()
            .unwrap()
            .to_string();
        mcp.complete_task(Parameters(TaskIdParams { id: one_id.clone() }))
            .await
            .unwrap();

        // active_only=true excludes done
        let active = mcp
            .search_tasks(Parameters(SearchParams {
                query: "task".into(),
                limit: None,
                active_only: Some(true),
            }))
            .await
            .unwrap();
        let active_arr = extract_json(&active);
        let active_arr = active_arr.as_array().unwrap();
        assert_eq!(active_arr.len(), 2, "done task excluded with active_only");

        // limit=1 caps results
        let limited = mcp
            .search_tasks(Parameters(SearchParams {
                query: "task".into(),
                limit: Some(1),
                active_only: None,
            }))
            .await
            .unwrap();
        assert_eq!(extract_json(&limited).as_array().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn test_tool_plan_epic() {
        let (_tmp, mcp) = setup();

        // Create an epic
        let epic = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "My Epic".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: Some(TaskType::Epic),
            }))
            .await
            .unwrap();
        let epic_id = extract_json(&epic)["id"].as_str().unwrap().to_string();

        // Create a linear chain: c1 <- c2 <- c3
        let c1 = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Step 1".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: Some(epic_id.clone()),
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id_c1 = extract_json(&c1)["id"].as_str().unwrap().to_string();

        let c2 = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Step 2".into(),
                priority: None,
                tags: None,
                depends_on: Some(vec![id_c1.clone()]),
                parent: Some(epic_id.clone()),
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id_c2 = extract_json(&c2)["id"].as_str().unwrap().to_string();

        // Create an independent sibling
        mcp.create_task(Parameters(CreateTaskParams {
            title: "Independent Step".into(),
            priority: None,
            tags: None,
            depends_on: None,
            parent: Some(epic_id.clone()),
            body: None,
            task_type: None,
        }))
        .await
        .unwrap();

        let result = mcp
            .plan_epic(Parameters(PlanEpicParams {
                id: epic_id.clone(),
            }))
            .await
            .unwrap();
        assert!(!result.is_error.unwrap_or(false));
        let json = extract_json(&result);
        let arr = json.as_array().unwrap();
        // All 3 children returned
        assert_eq!(arr.len(), 3);
        // c1 must appear before c2 (dependency order)
        let pos_c1 = arr
            .iter()
            .position(|x| x["id"] == id_c1)
            .expect("c1 in plan");
        let pos_c2 = arr
            .iter()
            .position(|x| x["id"] == id_c2)
            .expect("c2 in plan");
        assert!(pos_c1 < pos_c2, "c1 must precede c2 in execution order");

        // Calling plan_epic on a non-epic task returns an error
        let non_epic_result = mcp
            .plan_epic(Parameters(PlanEpicParams { id: id_c1 }))
            .await
            .unwrap();
        assert_eq!(non_epic_result.is_error, Some(true));
    }

    #[tokio::test]
    async fn test_tool_reparent_set_and_clear() {
        let (_tmp, mcp) = setup();

        // Create an epic
        let epic = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "My Epic".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: Some(TaskType::Epic),
            }))
            .await
            .unwrap();
        let epic_id = extract_json(&epic)["id"].as_str().unwrap().to_string();

        // Create a task without a parent
        let task = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Child Task".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let task_id = extract_json(&task)["id"].as_str().unwrap().to_string();

        // Set parent to the epic
        let updated = mcp
            .update_task(Parameters(UpdateTaskParams {
                id: task_id.clone(),
                title: None,
                status: None,
                priority: None,
                tags: None,
                assignee: None,
                body: None,
                parent: Some(epic_id.clone()),
            }))
            .await
            .unwrap();
        let json = extract_json(&updated);
        assert_eq!(json["id"], task_id);

        // Confirm the parent is set via get_task
        let detail = mcp
            .get_task(Parameters(TaskIdParams {
                id: task_id.clone(),
            }))
            .await
            .unwrap();
        assert_eq!(extract_json(&detail)["parent"], epic_id);

        // Clear parent with empty string
        let cleared = mcp
            .update_task(Parameters(UpdateTaskParams {
                id: task_id.clone(),
                title: None,
                status: None,
                priority: None,
                tags: None,
                assignee: None,
                body: None,
                parent: Some("".into()),
            }))
            .await
            .unwrap();
        assert!(!cleared.is_error.unwrap_or(false));

        // Confirm parent is cleared
        let detail2 = mcp
            .get_task(Parameters(TaskIdParams {
                id: task_id.clone(),
            }))
            .await
            .unwrap();
        assert!(
            extract_json(&detail2)["parent"].is_null(),
            "parent should be null after clearing"
        );
    }

    #[tokio::test]
    async fn test_tool_reparent_invalid_parent() {
        let (_tmp, mcp) = setup();
        let task = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Task".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let task_id = extract_json(&task)["id"].as_str().unwrap().to_string();

        // Attempt to set a non-existent parent
        let result = mcp
            .update_task(Parameters(UpdateTaskParams {
                id: task_id,
                title: None,
                status: None,
                priority: None,
                tags: None,
                assignee: None,
                body: None,
                parent: Some("nonexistent".into()),
            }))
            .await
            .unwrap();
        assert_eq!(result.is_error, Some(true));
    }

    // ─── Archive tool tests ───────────────────────────────────────────────────

    #[tokio::test]
    async fn test_tool_archive_hides_from_list_and_ready() {
        let (_tmp, mcp) = setup();

        // Create two tasks: t1 (no deps), t2 depends on t1
        let t1 = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Base task".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id1 = extract_json(&t1)["id"].as_str().unwrap().to_string();

        mcp.create_task(Parameters(CreateTaskParams {
            title: "Dependent task".into(),
            priority: None,
            tags: None,
            depends_on: Some(vec![id1.clone()]),
            parent: None,
            body: None,
            task_type: None,
        }))
        .await
        .unwrap();

        // Complete t1 so it's archivable (no active tasks depend on a done task... wait,
        // t2 depends on t1 and t2 is open — t1 is NOT archivable yet)
        mcp.complete_task(Parameters(TaskIdParams { id: id1.clone() }))
            .await
            .unwrap();

        // t1 is done but t2 (open) depends on it — archive should fail
        let fail = mcp
            .archive_task(Parameters(ArchiveTaskParams {
                id: Some(id1.clone()),
            }))
            .await
            .unwrap();
        assert_eq!(fail.is_error, Some(true));

        // Complete t2 as well — now t1 has no active dependents
        let all = mcp
            .list_all_tasks(Parameters(ListTasksFilterParams {
                status: None,
                priority: None,
                tag: None,
                epic: None,
                limit: None,
                active_only: None,
            }))
            .await
            .unwrap();
        let arr = extract_json(&all);
        let id2 = arr
            .as_array()
            .unwrap()
            .iter()
            .find(|x| x["title"] == "Dependent task")
            .unwrap()["id"]
            .as_str()
            .unwrap()
            .to_string();

        mcp.complete_task(Parameters(TaskIdParams { id: id2.clone() }))
            .await
            .unwrap();

        // Now archive t1 — t2 is done so t1 has no active dependents
        let archived = mcp
            .archive_task(Parameters(ArchiveTaskParams {
                id: Some(id1.clone()),
            }))
            .await
            .unwrap();
        assert!(!archived.is_error.unwrap_or(false));
        let archived_ids = extract_json(&archived);
        assert!(archived_ids.as_array().unwrap().iter().any(|v| v == &id1));

        // t1 should no longer appear in list_all_tasks
        let all2 = mcp
            .list_all_tasks(Parameters(ListTasksFilterParams {
                status: None,
                priority: None,
                tag: None,
                epic: None,
                limit: None,
                active_only: None,
            }))
            .await
            .unwrap();
        let arr2 = extract_json(&all2);
        assert!(
            arr2.as_array().unwrap().iter().all(|x| x["id"] != id1),
            "archived task must not appear in list_all_tasks"
        );

        // t1 should appear in list_archived
        let listed = mcp
            .list_archived(Parameters(ListArchivedParams { limit: None }))
            .await
            .unwrap();
        let arr3 = extract_json(&listed);
        assert!(
            arr3.as_array().unwrap().iter().any(|x| x["id"] == id1),
            "archived task must appear in list_archived"
        );
    }

    #[tokio::test]
    async fn test_tool_archive_sweep_no_id() {
        let (_tmp, mcp) = setup();

        // Create two independent tasks, both done
        let t1 = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Done 1".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id1 = extract_json(&t1)["id"].as_str().unwrap().to_string();

        let t2 = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Done 2".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id2 = extract_json(&t2)["id"].as_str().unwrap().to_string();

        mcp.complete_task(Parameters(TaskIdParams { id: id1.clone() }))
            .await
            .unwrap();
        mcp.complete_task(Parameters(TaskIdParams { id: id2.clone() }))
            .await
            .unwrap();

        // Sweep: no id → archive all archivable tasks
        let result = mcp
            .archive_task(Parameters(ArchiveTaskParams { id: None }))
            .await
            .unwrap();
        assert!(!result.is_error.unwrap_or(false));
        let ids = extract_json(&result);
        let ids_arr = ids.as_array().unwrap();
        assert!(ids_arr.len() >= 2, "both done tasks should be archived");
        assert!(ids_arr.iter().any(|v| v == &id1));
        assert!(ids_arr.iter().any(|v| v == &id2));

        // Active list should be empty
        let all = mcp
            .list_all_tasks(Parameters(ListTasksFilterParams {
                status: None,
                priority: None,
                tag: None,
                epic: None,
                limit: None,
                active_only: None,
            }))
            .await
            .unwrap();
        assert_eq!(extract_json(&all).as_array().unwrap().len(), 0);
    }

    #[tokio::test]
    async fn test_tool_restore_task_brings_back_to_active() {
        let (_tmp, mcp) = setup();

        // Create a task, complete it, archive it
        let t = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Will be archived".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id = extract_json(&t)["id"].as_str().unwrap().to_string();

        mcp.complete_task(Parameters(TaskIdParams { id: id.clone() }))
            .await
            .unwrap();
        mcp.archive_task(Parameters(ArchiveTaskParams {
            id: Some(id.clone()),
        }))
        .await
        .unwrap();

        // Verify it's archived and not active
        let archived_before = mcp
            .list_archived(Parameters(ListArchivedParams { limit: None }))
            .await
            .unwrap();
        let arr = extract_json(&archived_before);
        assert!(arr.as_array().unwrap().iter().any(|x| x["id"] == id));

        let active_before = mcp
            .list_all_tasks(Parameters(ListTasksFilterParams {
                status: None,
                priority: None,
                tag: None,
                epic: None,
                limit: None,
                active_only: None,
            }))
            .await
            .unwrap();
        assert!(
            extract_json(&active_before)
                .as_array()
                .unwrap()
                .iter()
                .all(|x| x["id"] != id)
        );

        // Restore
        let restored = mcp
            .restore_task(Parameters(RestoreTaskParams { id: id.clone() }))
            .await
            .unwrap();
        assert!(!restored.is_error.unwrap_or(false));
        let restored_ids = extract_json(&restored);
        assert!(restored_ids.as_array().unwrap().iter().any(|v| v == &id));

        // Now it should be active again and list_ready should see it (status=done, won't be ready,
        // but it IS in the active list)
        let active_after = mcp
            .list_all_tasks(Parameters(ListTasksFilterParams {
                status: None,
                priority: None,
                tag: None,
                epic: None,
                limit: None,
                active_only: None,
            }))
            .await
            .unwrap();
        assert!(
            extract_json(&active_after)
                .as_array()
                .unwrap()
                .iter()
                .any(|x| x["id"] == id),
            "restored task must appear in active list"
        );

        // And gone from archive
        let archived_after = mcp
            .list_archived(Parameters(ListArchivedParams { limit: None }))
            .await
            .unwrap();
        assert!(
            extract_json(&archived_after)
                .as_array()
                .unwrap()
                .iter()
                .all(|x| x["id"] != id)
        );
    }

    #[tokio::test]
    async fn test_tool_restore_then_ready() {
        // Archive a done task that had no deps, restore it (status=done → won't be ready),
        // then open it to verify it shows in list_ready.
        let (_tmp, mcp) = setup();

        let t = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Restore me".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id = extract_json(&t)["id"].as_str().unwrap().to_string();

        mcp.complete_task(Parameters(TaskIdParams { id: id.clone() }))
            .await
            .unwrap();
        mcp.archive_task(Parameters(ArchiveTaskParams {
            id: Some(id.clone()),
        }))
        .await
        .unwrap();

        // Restore the task
        mcp.restore_task(Parameters(RestoreTaskParams { id: id.clone() }))
            .await
            .unwrap();

        // Re-open the task so it becomes ready
        mcp.update_task(Parameters(UpdateTaskParams {
            id: id.clone(),
            title: None,
            status: Some(Status::Open),
            priority: None,
            tags: None,
            assignee: None,
            body: None,
            parent: None,
        }))
        .await
        .unwrap();

        // Now it should appear in list_ready
        let ready = mcp
            .list_ready(Parameters(ListReadyParams {
                limit: None,
                tag: None,
                epic: None,
            }))
            .await
            .unwrap();
        let arr = extract_json(&ready);
        assert!(
            arr.as_array().unwrap().iter().any(|x| x["id"] == id),
            "restored and reopened task must appear in list_ready"
        );
    }

    #[tokio::test]
    async fn test_tool_list_archived_with_limit() {
        let (_tmp, mcp) = setup();

        for title in &["A", "B", "C"] {
            let t = mcp
                .create_task(Parameters(CreateTaskParams {
                    title: (*title).into(),
                    priority: None,
                    tags: None,
                    depends_on: None,
                    parent: None,
                    body: None,
                    task_type: None,
                }))
                .await
                .unwrap();
            let id = extract_json(&t)["id"].as_str().unwrap().to_string();
            mcp.complete_task(Parameters(TaskIdParams { id: id.clone() }))
                .await
                .unwrap();
            mcp.archive_task(Parameters(ArchiveTaskParams { id: Some(id) }))
                .await
                .unwrap();
        }

        let all = mcp
            .list_archived(Parameters(ListArchivedParams { limit: None }))
            .await
            .unwrap();
        assert_eq!(extract_json(&all).as_array().unwrap().len(), 3);

        let limited = mcp
            .list_archived(Parameters(ListArchivedParams { limit: Some(2) }))
            .await
            .unwrap();
        assert_eq!(extract_json(&limited).as_array().unwrap().len(), 2);
    }

    #[tokio::test]
    async fn test_tool_restore_nonexistent_archived_errors() {
        let (_tmp, mcp) = setup();

        let result = mcp
            .restore_task(Parameters(RestoreTaskParams {
                id: "nonexistent".into(),
            }))
            .await
            .unwrap();
        assert_eq!(result.is_error, Some(true));
    }

    // ─── xja: end-to-end archive visibility and integrity (MCP layer) ─────────

    /// Archived task is hidden from search_tasks.
    #[tokio::test]
    async fn test_tool_archived_hidden_from_search() {
        let (_tmp, mcp) = setup();

        let t = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Searchable archived task".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id = extract_json(&t)["id"].as_str().unwrap().to_string();

        mcp.complete_task(Parameters(TaskIdParams { id: id.clone() }))
            .await
            .unwrap();
        mcp.archive_task(Parameters(ArchiveTaskParams {
            id: Some(id.clone()),
        }))
        .await
        .unwrap();

        // search_tasks (default: includes done) must not return archived task
        let results = mcp
            .search_tasks(Parameters(SearchParams {
                query: "Searchable archived task".into(),
                limit: None,
                active_only: None,
            }))
            .await
            .unwrap();
        let arr = extract_json(&results);
        assert!(
            arr.as_array().unwrap().iter().all(|x| x["id"] != id),
            "archived task must not appear in search_tasks"
        );
    }

    /// Archived task is hidden from get_graph (even with include_done=true).
    #[tokio::test]
    async fn test_tool_archived_hidden_from_graph() {
        let (_tmp, mcp) = setup();

        // Create A → B dep chain; both done and archived via sweep
        let t_a = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Graph base".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id_a = extract_json(&t_a)["id"].as_str().unwrap().to_string();

        let t_b = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Graph dependent".into(),
                priority: None,
                tags: None,
                depends_on: Some(vec![id_a.clone()]),
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let id_b = extract_json(&t_b)["id"].as_str().unwrap().to_string();

        mcp.complete_task(Parameters(TaskIdParams { id: id_a.clone() }))
            .await
            .unwrap();
        mcp.complete_task(Parameters(TaskIdParams { id: id_b.clone() }))
            .await
            .unwrap();
        // Sweep archive
        mcp.archive_task(Parameters(ArchiveTaskParams { id: None }))
            .await
            .unwrap();

        // get_graph with include_done=true must not return archived nodes
        let graph = mcp
            .get_graph(Parameters(GetGraphParams {
                include_done: Some(true),
                epic: None,
                limit: None,
            }))
            .await
            .unwrap();
        let obj = extract_json(&graph);
        let obj = obj.as_object().unwrap();
        assert!(
            !obj.contains_key(id_a.as_str()),
            "archived node A must not appear in graph"
        );
        assert!(
            !obj.contains_key(id_b.as_str()),
            "archived node B must not appear in graph"
        );
    }

    /// Archived epic is hidden from list_epics.
    #[tokio::test]
    async fn test_tool_archived_epic_hidden_from_list_epics() {
        let (_tmp, mcp) = setup();

        let epic = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Hidden epic".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: Some(TaskType::Epic),
            }))
            .await
            .unwrap();
        let epic_id = extract_json(&epic)["id"].as_str().unwrap().to_string();

        let child = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Only child".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: Some(epic_id.clone()),
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let child_id = extract_json(&child)["id"].as_str().unwrap().to_string();

        // Complete child (epic auto-closes) then archive the epic
        mcp.complete_task(Parameters(TaskIdParams {
            id: child_id.clone(),
        }))
        .await
        .unwrap();
        mcp.archive_task(Parameters(ArchiveTaskParams {
            id: Some(epic_id.clone()),
        }))
        .await
        .unwrap();

        let epics = mcp.list_epics().await.unwrap();
        let arr = extract_json(&epics);
        assert!(
            arr.as_array().unwrap().iter().all(|x| x["id"] != epic_id),
            "archived epic must not appear in list_epics"
        );
    }

    /// dep add onto an archived task ID is rejected (treated as unknown).
    #[tokio::test]
    async fn test_tool_dep_add_onto_archived_id_is_rejected() {
        let (_tmp, mcp) = setup();

        let archived = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "To archive".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let archived_id = extract_json(&archived)["id"].as_str().unwrap().to_string();

        mcp.complete_task(Parameters(TaskIdParams {
            id: archived_id.clone(),
        }))
        .await
        .unwrap();
        mcp.archive_task(Parameters(ArchiveTaskParams {
            id: Some(archived_id.clone()),
        }))
        .await
        .unwrap();

        let active = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Active task".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let active_id = extract_json(&active)["id"].as_str().unwrap().to_string();

        let result = mcp
            .add_dependency(Parameters(DepParams {
                id: active_id,
                depends_on: archived_id,
            }))
            .await
            .unwrap();
        assert_eq!(
            result.is_error,
            Some(true),
            "dep add onto archived id must return an error"
        );
    }

    /// prune_tasks hard-deletes from active store only — the archive is untouched.
    #[tokio::test]
    async fn test_tool_prune_never_touches_archive() {
        let (_tmp, mcp) = setup();

        let t_arch = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Archived task".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let arch_id = extract_json(&t_arch)["id"].as_str().unwrap().to_string();
        mcp.complete_task(Parameters(TaskIdParams {
            id: arch_id.clone(),
        }))
        .await
        .unwrap();
        mcp.archive_task(Parameters(ArchiveTaskParams {
            id: Some(arch_id.clone()),
        }))
        .await
        .unwrap();

        // Create a cancelled task in the active store for prune to consume
        let t_cancel = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "Cancelled active".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let cancel_id = extract_json(&t_cancel)["id"].as_str().unwrap().to_string();
        mcp.cancel_task(Parameters(TaskIdParams {
            id: cancel_id.clone(),
        }))
        .await
        .unwrap();

        let pruned = mcp
            .prune_tasks(Parameters(PruneParams {
                include_done: Some(true),
            }))
            .await
            .unwrap();
        assert!(!pruned.is_error.unwrap_or(false));

        // Archived task must still be in list_archived
        let archived = mcp
            .list_archived(Parameters(ListArchivedParams { limit: None }))
            .await
            .unwrap();
        assert!(
            extract_json(&archived)
                .as_array()
                .unwrap()
                .iter()
                .any(|x| x["id"] == arch_id),
            "archived task must not be removed by prune"
        );
    }

    /// New task IDs are never reused from archived IDs.
    #[tokio::test]
    async fn test_tool_new_task_ids_do_not_reuse_archived() {
        let (_tmp, mcp) = setup();

        let t = mcp
            .create_task(Parameters(CreateTaskParams {
                title: "ID Guard".into(),
                priority: None,
                tags: None,
                depends_on: None,
                parent: None,
                body: None,
                task_type: None,
            }))
            .await
            .unwrap();
        let archived_id = extract_json(&t)["id"].as_str().unwrap().to_string();

        mcp.complete_task(Parameters(TaskIdParams {
            id: archived_id.clone(),
        }))
        .await
        .unwrap();
        mcp.archive_task(Parameters(ArchiveTaskParams {
            id: Some(archived_id.clone()),
        }))
        .await
        .unwrap();

        let mut new_ids = Vec::new();
        for i in 0..10 {
            let nt = mcp
                .create_task(Parameters(CreateTaskParams {
                    title: format!("New {i}"),
                    priority: None,
                    tags: None,
                    depends_on: None,
                    parent: None,
                    body: None,
                    task_type: None,
                }))
                .await
                .unwrap();
            new_ids.push(extract_json(&nt)["id"].as_str().unwrap().to_string());
        }

        assert!(
            !new_ids.contains(&archived_id),
            "archived ID {archived_id} must not be reused; new IDs: {new_ids:?}"
        );
    }
}