mahbot 0.11.1

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! The admin's own view into the managed workspaces: list them, add one (which activates
//! it), inspect one, delete one, freeze/unfreeze their pipelines, switch maintenance on or
//! off, restart discovery, write their rules and their diagnostics commands, make one the
//! active project, read a board and a single ticket, and leave a clarification note on a
//! ticket.
//!
//! The detail of that surface is not here: every action and every field is documented in the
//! `reference` action ([`crate::settings::reference`], the same text `mahbot config reference`
//! prints), so the standing description stays small and every field's description stays short.
//!
//! It manages no board. Adding a managed workspace activates it; the desktop itself moves
//! the active project when the active one is deleted, and onto a project at start-up
//! whenever the stored one no longer exists.
use anyhow::anyhow;
use async_trait::async_trait;
use serde_json::json;
use std::fmt::Write as _;

use crate::pipeline::board::{TicketPhase, store as board_store};
use crate::tools::ToolAnswer;
use crate::tools::ticket::{GET_TICKET_COMMENT_MAX, GET_TICKET_DESC_MAX, GET_TICKET_LAST_N_FULL};
use crate::workspace::WorkspaceStore;
use crate::{Role, Tool, Workspace, WorkspaceStatus};

/// The tool's own byte budget, needed because the framework's ~5 KB tool-output truncation is
/// off for it (see [`WorkspaceTool::preserve_full_output`]): the `board` listing and the
/// shortened `ticket` view bound themselves, and a byte cap is required alongside
/// `BOARD_LINE_LIMIT` because a title, a description and a comment are all unbounded.
/// `ticket` with `full: true` is deliberately exempt.
const OUTPUT_BYTE_LIMIT: usize = 24_000;
const BOARD_LINE_LIMIT: usize = 100;

/// What an action that covers the whole managed set answers when there is none — one
/// wording, so `list` and a fleet-wide pause say the same thing.
const NO_WORKSPACE: &str = "No managed workspaces exist.";

/// The `workspace` tool: the admin's project view and the settings of each project —
/// `reference`, `list`, `show`, `add`, `delete`, `pause`, `resume`, `maintenance`,
/// `rediscover`, `rediscover_diagnostics`, `set_diagnostics`, `set_rules`, `use`, `board`,
/// `ticket`, `comment`.
pub(crate) struct WorkspaceTool;

/// This tool's schema, built once: [`Tool::parameters_schema`] hands out a copy, and the
/// unknown-field guard reads the same list without rebuilding it on every call.
fn schema() -> &'static serde_json::Value {
    static SCHEMA: std::sync::LazyLock<serde_json::Value> = std::sync::LazyLock::new(build_schema);
    &SCHEMA
}

fn build_schema() -> serde_json::Value {
    super::tool_params_schema(
        &json!({
            "action": {
                "type": "string",
                "enum": [
                    "reference",
                    "list",
                    "show",
                    "add",
                    "delete",
                    "pause",
                    "resume",
                    "maintenance",
                    "rediscover",
                    "rediscover_diagnostics",
                    "set_diagnostics",
                    "set_rules",
                    "use",
                    "board",
                    "ticket",
                    "comment"
                ],
                "description": "The operation; its `reference` action lists every one."
            },
            "workspace": {
                "type": "string",
                "description": "The managed workspace, spelled as `list` spells it."
            },
            "name": {
                "type": "string",
                "description": "(add) Short unique name."
            },
            "path": {
                "type": "string",
                "description": "(add) The project directory."
            },
            "phase": {
                "type": "string",
                "description": "(board) One ticket phase."
            },
            "ticket_id": {
                "type": "string",
                "description": "(ticket/comment) Full id `<workspace>-<number>`."
            },
            "full": {
                "type": "boolean",
                "description": "(ticket) Whole and unclipped. Default false."
            },
            "content": {
                "type": "string",
                "description": "(comment) The note to leave."
            },
            "rules": {
                "type": "string",
                "description": "(set_rules) Project rules; empty clears."
            },
            "maintenance": {
                "type": "boolean",
                "description": "(maintenance) Background maintainer on or off."
            },
            "format": {
                "type": "string",
                "description": "(set_diagnostics) Format command."
            },
            "format_check": {
                "type": "string",
                "description": "(set_diagnostics) Format-check command."
            },
            "lint": {
                "type": "string",
                "description": "(set_diagnostics) Lint command."
            },
            "lint_fix": {
                "type": "string",
                "description": "(set_diagnostics) Lint-fix command."
            },
            "type_check": {
                "type": "string",
                "description": "(set_diagnostics) Type-check command."
            },
            "build": {
                "type": "string",
                "description": "(set_diagnostics) Build command."
            },
            "unit_test": {
                "type": "string",
                "description": "(set_diagnostics) Unit-test command."
            }
        }),
        &["action"],
    )
}

#[async_trait]
impl Tool for WorkspaceTool {
    fn name(&self) -> &'static str {
        "workspace"
    }

    fn parameters_schema(&self) -> serde_json::Value {
        schema().clone()
    }

    fn preserve_full_output(&self) -> bool {
        // A `ticket` answer can carry hundreds of KB of comments, so the fixed ~5 KB
        // truncation is wrong for the whole tool; the read paths bound themselves.
        true
    }

    async fn execute(&self, _ws: &Workspace, args: serde_json::Value) -> anyhow::Result<String> {
        Ok(self.answer(args).await?.text)
    }

    async fn execute_answer(
        &self,
        _ws: &Workspace,
        args: serde_json::Value,
    ) -> anyhow::Result<ToolAnswer> {
        self.answer(args).await
    }
}

impl WorkspaceTool {
    /// The one action dispatch both faces of the tool go through: `execute` renders it to its
    /// text, and [`Tool::execute_answer`] hands it over with the partiality flag a command-line
    /// caller reads. There is no second code path to drift from this one.
    async fn answer(&self, args: serde_json::Value) -> anyhow::Result<ToolAnswer> {
        // Before anything is read: a field the schema does not declare is a usage error naming
        // the reference, never silently ignored — a misspelled `workspace` would otherwise act
        // on the whole fleet.
        super::refuse_unknown_fields(schema(), &args, super::REFERENCE_ACTION_HINT)?;
        match super::get_str(&args, "action")? {
            "reference" => Ok(ToolAnswer::done(crate::settings::reference())),
            "list" => Ok(ToolAnswer::done(
                list_workspaces(super::get_opt_str_strict(&args, "workspace")?).await?,
            )),
            "show" => Ok(ToolAnswer::done(
                show_workspace(super::get_str(&args, "workspace")?).await?,
            )),
            "add" => add_workspace(&args).await,
            "delete" => Ok(ToolAnswer::done(
                delete_workspace(super::get_str(&args, "workspace")?).await?,
            )),
            "pause" => pause_or_resume(write_address(&args, "pause")?, true).await,
            "resume" => pause_or_resume(write_address(&args, "resume")?, false).await,
            "maintenance" => Ok(ToolAnswer::done(set_maintenance(&args).await?)),
            "rediscover" => Ok(ToolAnswer::done(
                rediscover(super::get_str(&args, "workspace")?).await?,
            )),
            "rediscover_diagnostics" => Ok(ToolAnswer::done(
                rediscover_diagnostics(super::get_str(&args, "workspace")?).await?,
            )),
            "set_diagnostics" => Ok(ToolAnswer::done(set_diagnostics(&args).await?)),
            "set_rules" => Ok(ToolAnswer::done(set_rules(&args).await?)),
            "use" => Ok(ToolAnswer::done(
                use_workspace(super::get_str(&args, "workspace")?).await?,
            )),
            "board" => Ok(ToolAnswer::done(
                list_board(
                    super::get_opt_str_strict(&args, "workspace")?,
                    super::get_opt_str_strict(&args, "phase")?,
                )
                .await?,
            )),
            "ticket" => Ok(ToolAnswer::done(
                show_ticket(
                    super::get_str(&args, "ticket_id")?,
                    super::get_bool(&args, "full", false)?,
                )
                .await?,
            )),
            "comment" => Ok(ToolAnswer::done(
                add_note(
                    super::get_str(&args, "ticket_id")?,
                    super::get_str(&args, "content")?,
                )
                .await?,
            )),
            other => Err(anyhow!(
                "unknown action '{other}' — call the `reference` action for every action and field"
            )),
        }
    }
}

/// The workspace a `pause` / `resume` was pointed at: the `workspace` argument, or `None`
/// for every managed workspace when none is named.
///
/// The one action pair that can act on a single workspace or on all of them must never widen
/// because the address was spelled some other way — a folder path, a ticket id, or `add`'s
/// `name` — so with no `workspace` argument such a call may name nothing else at all. An
/// extra declared field is a usage error phrased around that rule, never around the key that
/// carried it; a key no schema declares is refused earlier, for every action
/// ([`super::refuse_unknown_fields`]). The read actions take the same address but ignore a
/// stray declared field; only a write that would cover the fleet has to say so.
///
/// A JSON `null` counts as absent, as everywhere in the product (providers fill omitted
/// arguments with nulls).
fn write_address<'a>(args: &'a serde_json::Value, action: &str) -> anyhow::Result<Option<&'a str>> {
    if let Some(address) = super::get_opt_str_strict(args, "workspace")? {
        return Ok(Some(address));
    }
    if args.as_object().is_some_and(|obj| {
        obj.iter()
            .any(|(key, value)| key.as_str() != "action" && !value.is_null())
    }) {
        return Err(anyhow!(
            "usage: with no \"workspace\" this `{action}` covers every managed workspace, so \
             the call may name nothing else — hint: pass \"workspace\" to act on one workspace, or \
             drop the extra field to really cover every managed workspace"
        ));
    }
    Ok(None)
}

/// Resolve `name` to a managed workspace — never a personal space, including a legacy
/// `personal:*` row. Matching is exact, and a miss names the live set because the admin names
/// workspaces from a session-start context block that may predate an add or a delete.
async fn managed_workspace(name: &str) -> anyhow::Result<Workspace> {
    let name = name.trim();
    let workspaces = crate::users::managed_workspaces().await?;
    if let Some(ws) = workspaces.iter().find(|ws| ws.name == name) {
        return Ok(ws.clone());
    }
    let managed = if workspaces.is_empty() {
        "none".to_string()
    } else {
        workspaces
            .iter()
            .map(|ws| ws.name.as_str())
            .collect::<Vec<_>>()
            .join(", ")
    };
    Err(if crate::users::is_personal_workspace(name) {
        anyhow!(
            "'{name}' is a personal space, not a managed workspace — personal spaces have \
             no pipeline and no board; managed workspaces: {managed}"
        )
    } else {
        anyhow!(
            "No managed workspace exists under the name '{name}' — managed workspaces: {managed}"
        )
    })
}

/// Resolve a full `<workspace>-<number>` ticket id, refusing every other spelling with the
/// expected form, and an id whose workspace prefix is not a managed workspace.
async fn managed_ticket_id(raw: &str) -> anyhow::Result<String> {
    // Only the full spelling addresses a ticket here: the manager's own ticket tools resolve a
    // bare number against the workspace they are bound to, and this tool is bound to none.
    let Ok((Some(prefix), full)) = crate::tools::ticket::parse_ticket_id(raw) else {
        return Err(anyhow!(
            "Ticket id '{}' is not a full '<workspace>-<number>' id — `ticket` and `comment` \
             are addressed by a ticket's full id, which already carries its workspace.",
            raw.trim()
        ));
    };
    // An id naming a workspace that is not managed is refused as an unknown workspace, with
    // the managed set named.
    managed_workspace(prefix).await?;
    Ok(full.to_string())
}

/// The managed workspaces, one line each, with the admin's active one marked.
///
/// The active workspace is the stored selection and counts only when it is one of the managed
/// names: a personal value, or a name no longer managed, means nothing is active — while the
/// resolver's `None` is a failed read, reported as such. The desktop repairs such a selection
/// at start-up and after a deletion, so the two surfaces agree in the steady state.
async fn list_workspaces(only: Option<&str>) -> anyhow::Result<String> {
    let workspaces = crate::users::managed_workspaces().await?;
    // A named workspace is answered about itself: with none managed at all, that is the not-found
    // refusal naming the name, not a report on the empty fleet.
    if workspaces.is_empty() && only.is_none() {
        return Ok(NO_WORKSPACE.to_string());
    }
    let resolved =
        crate::users::resolve_selected_workspace_name(crate::users::ADMIN_USER_NAME).await;
    let active = resolved
        .as_deref()
        .filter(|name| workspaces.iter().any(|ws| &ws.name == name));
    let listed = match only {
        Some(name) => vec![managed_workspace(name).await?],
        None => workspaces,
    };
    let mut listing = String::from("Managed workspaces:\n");
    for ws in &listed {
        let paused = if ws.paused { ", paused" } else { "" };
        let maintenance = if ws.maintenance_enabled {
            ", maintenance on"
        } else {
            ""
        };
        let active_marker = if active == Some(ws.name.as_str()) {
            " [active]"
        } else {
            ""
        };
        let _ = writeln!(
            listing,
            "- {} ({}{paused}{maintenance}): {}{active_marker}",
            ws.name, ws.status, ws.path
        );
    }
    if resolved.is_none() {
        let _ = writeln!(listing, "The active workspace could not be read.");
    } else if active.is_none() {
        let _ = writeln!(listing, "No workspace is active.");
    }
    Ok(listing.trim_end().to_string())
}

/// Add a managed workspace and make it the admin's active one — adding and activating are one
/// rule on every path (the desktop's own add form does the same).
///
/// PARTIAL exactly when the add succeeded but the activation write did not.
async fn add_workspace(args: &serde_json::Value) -> anyhow::Result<ToolAnswer> {
    let name = super::get_str(args, "name")?;
    let path = super::get_str(args, "path")?;
    // The stored path, not the caller's spelling: the store canonicalises it, and an answer that
    // echoed `./proj` back would read as a different folder from the one `list` shows.
    let added = crate::workspace::store().add(name, path).await?;
    let path = added.path;
    // Adding activates: the row exists by now, so a failed selection write is reported as the
    // partial outcome it is rather than as an add that did not happen.
    match crate::users::store()
        .set_selected_workspace(crate::users::ADMIN_USER_NAME, Some(name))
        .await
    {
        Ok(()) => Ok(ToolAnswer::done(format!(
            "Added managed workspace '{name}' at {path} and made it your active workspace. \
             The workspace is being picked up — if the model provider is configured its first \
             discovery pass will start shortly."
        ))),
        Err(e) => Ok(ToolAnswer::partial(format!(
            "Added managed workspace '{name}' at {path}, but making it your active workspace \
             failed: {e} — make it active again with the `use` action."
        ))),
    }
}

/// One workspace in full: what `list` shows, plus the rules and the diagnostics commands, so
/// the admin can see what an agent there is told and what verification will run.
///
/// The rules are the admin's own text, printed verbatim under an indented block (the store caps
/// them at [`MAX_WORKSPACE_NOTES_CHARS`](crate::workspace::MAX_WORKSPACE_NOTES_CHARS)), and the
/// commands come out label by label, an absent one spelled "not discovered".
async fn show_workspace(name: &str) -> anyhow::Result<String> {
    let ws = managed_workspace(name).await?;
    // The read's two negatives are different facts: for the admin a successful read always yields
    // `Some` (the personal workspace at worst), so `None` is a failed read and is reported as
    // unknown — never as "not active".
    let active = crate::users::resolve_selected_workspace_name(crate::users::ADMIN_USER_NAME).await;
    let commands = crate::workspace::store().get_diagnostics(&ws.name).await?;
    let mut out = format!("Workspace '{}':\n", ws.name);
    let _ = writeln!(out, "- path: {}", ws.path);
    let _ = writeln!(out, "- status: {}", ws.status);
    let _ = writeln!(
        out,
        "- pipeline: {}",
        if ws.paused { "paused" } else { "running" }
    );
    let _ = writeln!(
        out,
        "- maintenance: {}",
        if ws.maintenance_enabled { "on" } else { "off" }
    );
    let _ = writeln!(
        out,
        "- active project: {}",
        match active.as_deref() {
            Some(active) if active == ws.name => "yes",
            Some(_) => "no",
            None => "unknown (the selection could not be read)",
        }
    );
    if ws.notes.trim().is_empty() {
        let _ = writeln!(out, "- rules: none");
    } else {
        let _ = writeln!(out, "- rules:");
        for line in ws.notes.lines() {
            let _ = writeln!(out, "  {line}");
        }
    }
    match commands.as_ref().filter(|commands| !commands.is_empty()) {
        Some(commands) => {
            let _ = writeln!(out, "- diagnostics:");
            write_commands(&mut out, commands, "  ");
        }
        None => {
            let _ = writeln!(out, "- diagnostics: not discovered");
        }
    }
    Ok(out.trim_end().to_string())
}

/// Delete a managed workspace: its row, its jobs and its research runs go; the project on disk
/// is untouched, which the answer names so the admin knows the folder can be added back.
///
/// The active project afterwards is the store's own answer — the deletion resolves the admin's
/// selection inside its transaction — so the reply reports where the product stands rather than
/// a derivation of it.
async fn delete_workspace(name: &str) -> anyhow::Result<String> {
    let ws = managed_workspace(name).await?;
    let active = match crate::workspace::store().delete(&ws.name).await? {
        Some(next) => format!("Your active project is now '{next}'."),
        None => "You are back on your personal workspace.".to_string(),
    };
    Ok(format!(
        "Deleted managed workspace '{name}'. Its jobs and its research runs are gone with it. \
         {folder_note} The tickets filed against it stay in the board but are no longer listed. \
         {active}",
        name = ws.name,
        folder_note = folder_note(&ws.path)
    ))
}

/// What a deleted workspace left on disk, as far as the folder itself can prove: a folder removed
/// by hand is not reported as still there, and one that is no repository has none to name.
fn folder_note(path: &str) -> String {
    let folder = std::path::Path::new(path);
    if !folder.exists() {
        format!("The project folder at {path} is gone.")
    } else if crate::git::commands::is_git_repo(folder) {
        format!("The project folder at {path} (git repository included) stays.")
    } else {
        format!("The project folder at {path} stays.")
    }
}

/// Turn the background maintainer on or off for one workspace.
///
/// Both effects are the store's own write: enabling clears the debounce so the maintainer runs
/// on the next poll, and disabling cancels a maintainer agent already running there — so the
/// answer reports the state, never a second implementation of either.
async fn set_maintenance(args: &serde_json::Value) -> anyhow::Result<String> {
    // The argument is judged before a store is read, so a bad call touches nothing.
    let Some(on) = super::get_opt_bool(args, "maintenance")? else {
        return Err(anyhow!(
            "usage: missing required argument \"maintenance\" (expected a boolean) — hint: pass \
             true to run the background maintainer or false to stop it"
        ));
    };
    let ws = managed_workspace(super::get_str(args, "workspace")?).await?;
    crate::workspace::store()
        .set_maintenance_enabled(&ws.name, on)
        .await?;
    Ok(if on {
        format!(
            "Maintenance is now on for workspace '{}'. The debounce is cleared, so the maintainer \
             runs on the next poll.",
            ws.name
        )
    } else {
        format!(
            "Maintenance is now off for workspace '{}'. Any maintainer agent running there was \
             cancelled.",
            ws.name
        )
    })
}

/// Re-analyse a workspace: the store sets it back to `analyzing`, clears the per-role contexts
/// and spawns a fresh discovery. The answer must say the pipeline is paused until that finishes
/// — the pause is the store's, and the admin would otherwise read it as their own.
async fn rediscover(name: &str) -> anyhow::Result<String> {
    let ws = managed_workspace(name).await?;
    crate::workspace::store().rediscover(&ws.name).await?;
    Ok(format!(
        "Discovery restarted for workspace '{}': its per-role contexts were cleared. The \
         pipeline is paused until discovery finishes.",
        ws.name
    ))
}

/// Re-detect only the project's commands: the store leaves the status, the pause and the
/// per-role contexts alone, which is the whole difference from [`rediscover`].
async fn rediscover_diagnostics(name: &str) -> anyhow::Result<String> {
    let ws = managed_workspace(name).await?;
    crate::workspace::store()
        .rediscover_diagnostics(&ws.name)
        .await?;
    Ok(format!(
        "Diagnostics discovery restarted for workspace '{}': its stored commands were cleared and \
         are being re-detected — its status, its pause and its per-role contexts are untouched.",
        ws.name
    ))
}

/// Apply one given command field over the stored one: absent keeps it, an empty string clears
/// it, a value sets it.
fn apply_command(slot: &mut Option<String>, given: Option<&str>) {
    if let Some(value) = given {
        *slot = crate::util::none_if_empty(value);
    }
}

/// One line per diagnostics command, an absent one spelled "not discovered", indented under
/// whatever header the caller printed.
fn write_commands(out: &mut String, commands: &crate::DiagnosticsCommands, indent: &str) {
    for (label, command) in commands.commands() {
        let _ = writeln!(
            out,
            "{indent}- {label}: {}",
            command.unwrap_or("not discovered")
        );
    }
}

/// Write the project's diagnostics commands by hand.
///
/// The stored blob is read first and the given fields applied over it, so a partial call can
/// never blank the commands it did not name. A call naming no command field at all is refused
/// before the store: it would re-write the identical blob and bump `diagnostics_generation`,
/// cancelling an in-flight discovery for nothing. The store bumps that generation on a real write,
/// which is what invalidates a discovery already in flight; the answer says so, because a
/// hand-written command would otherwise seem to vanish when the stale discovery landed.
async fn set_diagnostics(args: &serde_json::Value) -> anyhow::Result<String> {
    let format = super::get_opt_str_strict(args, "format")?;
    let format_check = super::get_opt_str_strict(args, "format_check")?;
    let lint = super::get_opt_str_strict(args, "lint")?;
    let lint_fix = super::get_opt_str_strict(args, "lint_fix")?;
    let type_check = super::get_opt_str_strict(args, "type_check")?;
    let build = super::get_opt_str_strict(args, "build")?;
    let unit_test = super::get_opt_str_strict(args, "unit_test")?;
    anyhow::ensure!(
        [
            format,
            format_check,
            lint,
            lint_fix,
            type_check,
            build,
            unit_test
        ]
        .iter()
        .any(Option::is_some),
        "usage: name at least one command field — format, format_check, lint, lint_fix, \
         type_check, build, unit_test (an empty string clears one)"
    );

    let ws = managed_workspace(super::get_str(args, "workspace")?).await?;
    let mut commands = crate::workspace::store()
        .get_diagnostics(&ws.name)
        .await?
        .unwrap_or_default();
    apply_command(&mut commands.format, format);
    apply_command(&mut commands.format_check, format_check);
    apply_command(&mut commands.lint, lint);
    apply_command(&mut commands.lint_fix, lint_fix);
    apply_command(&mut commands.type_check, type_check);
    apply_command(&mut commands.build, build);
    apply_command(&mut commands.unit_test, unit_test);
    crate::workspace::store()
        .set_diagnostics(&ws.name, &commands)
        .await?;
    let mut out = format!("Diagnostics for workspace '{}':\n", ws.name);
    write_commands(&mut out, &commands, "");
    let _ = write!(
        out,
        "\nWriting invalidated any diagnostics discovery already in flight, so its stale result \
         cannot overwrite these."
    );
    Ok(out)
}

/// Write the project rules.
///
/// The store caps them at [`MAX_WORKSPACE_NOTES_CHARS`](crate::workspace::MAX_WORKSPACE_NOTES_CHARS)
/// characters, so a longer input is reported as truncated rather than silently shortened.
async fn set_rules(args: &serde_json::Value) -> anyhow::Result<String> {
    let rules = super::get_str(args, "rules")?;
    let ws = managed_workspace(super::get_str(args, "workspace")?).await?;
    crate::workspace::store().set_notes(&ws.name, rules).await?;
    // The stored length is the store's own truncation, read back through the same function it
    // writes with, so the answer and the row cannot disagree.
    let stored = crate::workspace::truncate_workspace_notes(rules);
    let mut out = if stored.is_empty() {
        format!("The rules of workspace '{}' are now empty.", ws.name)
    } else {
        format!(
            "The rules of workspace '{}' are now {} characters long.",
            ws.name,
            stored.chars().count()
        )
    };
    if rules.chars().count() > stored.chars().count() {
        let _ = write!(
            out,
            " They were truncated to {} characters.",
            crate::workspace::MAX_WORKSPACE_NOTES_CHARS
        );
    }
    Ok(out)
}

/// Make one managed workspace the admin's active project — the same stored selection the
/// desktop's own switcher writes, so it takes effect without a restart: the dashboard reads the
/// selection back on a users change.
async fn use_workspace(name: &str) -> anyhow::Result<String> {
    let ws = managed_workspace(name).await?;
    crate::users::store()
        .set_selected_workspace(crate::users::ADMIN_USER_NAME, Some(&ws.name))
        .await?;
    Ok(format!(
        "'{}' is now your active project at {}. It takes effect without a restart — the \
         dashboard reads the stored selection back on a users change.",
        ws.name, ws.path
    ))
}

/// What a pause/resume request does to one workspace — the rule both forms follow, so the
/// named and the fleet-wide answer can never disagree about which rows are written.
enum PipelineChange {
    /// Not `ready`: only a `ready` row is dispatchable (the poll gates every claim and phase
    /// dispatch on the status), so a non-ready row's `paused` flag is the discovery's own
    /// analysis pause rather than a freeze of running work, and it is never written.
    NotReady,
    /// Already in the requested state: reported as such, never written again.
    Already,
    Write,
}

fn pipeline_change(ws: &Workspace, paused: bool) -> PipelineChange {
    if ws.status != WorkspaceStatus::Ready {
        PipelineChange::NotReady
    } else if ws.paused == paused {
        PipelineChange::Already
    } else {
        PipelineChange::Write
    }
}

/// Pause or resume the named workspace's pipeline, or every managed workspace at once when no
/// name was given.
async fn pause_or_resume(name: Option<&str>, paused: bool) -> anyhow::Result<ToolAnswer> {
    match name {
        Some(name) => Ok(ToolAnswer::done(
            set_one_pipeline_paused(name, paused).await?,
        )),
        None => set_all_pipelines_paused(paused).await,
    }
}

async fn set_one_pipeline_paused(name: &str, paused: bool) -> anyhow::Result<String> {
    let ws = managed_workspace(name).await?;
    match pipeline_change(&ws, paused) {
        PipelineChange::NotReady => Err(anyhow!(
            "Workspace '{}' is {} — only a ready workspace has a pipeline to pause or resume.",
            ws.name,
            ws.status
        )),
        PipelineChange::Already => Ok(if paused {
            format!("The pipeline of workspace '{}' is already paused.", ws.name)
        } else {
            format!(
                "The pipeline of workspace '{}' is not paused — nothing to resume.",
                ws.name
            )
        }),
        PipelineChange::Write => {
            crate::workspace::store()
                .set_paused(&ws.name, paused)
                .await?;
            let verb = if paused { "paused" } else { "resumed" };
            Ok(format!("Pipeline {verb} for workspace '{}'.", ws.name))
        }
    }
}

/// Pause or resume every workspace of `workspaces` where the write is honest — see
/// [`pipeline_change`] — one line per workspace, or [`NO_WORKSPACE`] for an empty set.
///
/// Takes the store the writes go to and the set they cover, so the fleet-wide form is not
/// hardwired to the process-global store: a fleet-wide write can then never reach a row a test
/// created. Never [`WorkspaceStore::pause_all`](crate::workspace::WorkspaceStore::pause_all):
/// that would also pause not-ready rows and the discovery's own analysis pause.
///
/// PARTIAL exactly when the requested state was not reached for a workspace: a write that
/// failed, or a workspace skipped as not ready. A workspace already in the requested state
/// leaves the operation whole. The not-ready skip counts in BOTH directions on purpose,
/// `resume` included: the named form refuses a not-ready workspace the same way, and one rule
/// for both forms keeps them from disagreeing about the same workspace.
async fn set_pipelines_paused(
    store: &WorkspaceStore,
    workspaces: &[Workspace],
    paused: bool,
) -> anyhow::Result<ToolAnswer> {
    if workspaces.is_empty() {
        return Ok(ToolAnswer::done(NO_WORKSPACE));
    }
    let header = if paused {
        "Paused every managed workspace where possible:"
    } else {
        "Resumed every managed workspace where possible:"
    };
    let mut out = format!("{header}\n");
    let mut incomplete = false;
    for ws in workspaces {
        let line = match pipeline_change(ws, paused) {
            // The caller asked for every managed workspace; this one was left untouched.
            PipelineChange::NotReady => {
                incomplete = true;
                format!("- {}: skipped — not ready ({})", ws.name, ws.status)
            }
            PipelineChange::Already if paused => format!("- {}: already paused", ws.name),
            PipelineChange::Already => format!("- {}: not paused", ws.name),
            PipelineChange::Write => match store.set_paused(&ws.name, paused).await {
                Ok(()) if paused => format!("- {}: paused", ws.name),
                Ok(()) => format!("- {}: resumed", ws.name),
                // Reported like every other outcome: the rows written before a failure are real, so
                // the report must cover each workspace.
                Err(e) => {
                    incomplete = true;
                    format!("- {}: failed — {e}", ws.name)
                }
            },
        };
        let _ = writeln!(out, "{line}");
    }
    let report = out.trim_end().to_string();
    Ok(if incomplete {
        ToolAnswer::partial(report)
    } else {
        ToolAnswer::done(report)
    })
}

/// Every managed workspace at once: the global store and the set it must cover.
async fn set_all_pipelines_paused(paused: bool) -> anyhow::Result<ToolAnswer> {
    let workspaces = crate::users::managed_workspaces().await?;
    set_pipelines_paused(crate::workspace::store(), &workspaces, paused).await
}

/// List the live tickets of the managed workspaces, optionally narrowed to one workspace
/// and/or one phase.
async fn list_board(only: Option<&str>, phase: Option<&str>) -> anyhow::Result<String> {
    let workspaces = crate::users::managed_workspaces().await?;
    let phase_filter = match phase {
        Some(s) if s.eq_ignore_ascii_case("archived") => {
            anyhow::bail!(
                "Archived tickets are never listed — archiving is a one-way visibility switch that hides a ticket from every listing, and a single archived ticket stays readable with `ticket` by its id."
            );
        }
        // `TicketPhase::from_str`'s error already lists the valid phases.
        Some(s) => Some(s.parse::<TicketPhase>()?),
        None => None,
    };
    let only = match only {
        Some(name) => Some(managed_workspace(name).await?.name),
        None => None,
    };
    let mut tickets = board_store().list_all_tickets(None, phase_filter).await?;
    // A ticket of a workspace that no longer exists is never listed.
    tickets.retain(|t| {
        workspaces.iter().any(|ws| ws.name == t.workspace_name)
            && only.as_ref().is_none_or(|name| name == &t.workspace_name)
    });
    if tickets.is_empty() {
        return Ok("No tickets found.".to_string());
    }
    let total = tickets.len();
    let mut lines = Vec::new();
    let mut bytes = 0;
    for t in &tickets {
        let mut line = t.short_display();
        if !lines.is_empty()
            && (lines.len() == BOARD_LINE_LIMIT || bytes + line.len() > OUTPUT_BYTE_LIMIT)
        {
            break;
        }
        // The first line is always shown — the notice must never read "the first 0 of N
        // tickets" — so a line larger than the whole budget is cut.
        line = crate::util::cut_bytes(&line, OUTPUT_BYTE_LIMIT);
        bytes += line.len() + 1;
        lines.push(line);
    }
    let shown = lines.len();
    let mut out = String::from("Tickets:\n");
    for line in &lines {
        let _ = writeln!(out, "{line}");
    }
    if shown < total {
        let _ = write!(
            out,
            "\n(partial listing: showing the first {shown} of {total} tickets — \
             narrow it with `phase`, name a single `workspace`, or read one ticket with `ticket`.)"
        );
    }
    Ok(out)
}

/// Read one ticket by its full id. The default is the shortened form for every ticket,
/// whoever filed it.
async fn show_ticket(ticket_id: &str, full: bool) -> anyhow::Result<String> {
    let id = managed_ticket_id(ticket_id).await?;
    let Some(ticket) = board_store().get_ticket(&id).await? else {
        return Err(anyhow!("Ticket {id} not found."));
    };
    if full {
        return Ok(ticket.detailed_display());
    }
    let shortened = ticket.detailed_display_limited(
        GET_TICKET_DESC_MAX,
        GET_TICKET_COMMENT_MAX,
        GET_TICKET_LAST_N_FULL,
    );
    // The newest comments come back in full, so a ticket carrying a huge one is still bounded
    // here — `full: true` is the unbounded read.
    if shortened.len() <= OUTPUT_BYTE_LIMIT {
        return Ok(shortened);
    }
    Ok(format!(
        "{}…\n(shortened view cut short — pass `full: true` for the ticket whole and unclipped.)",
        crate::util::truncate_bytes(&shortened, OUTPUT_BYTE_LIMIT)
    ))
}

/// Leave a clarification note on a ticket. Refused when the ticket does not exist, so a note
/// is never stored for a missing ticket.
async fn add_note(ticket_id: &str, content: &str) -> anyhow::Result<String> {
    anyhow::ensure!(
        !content.trim().is_empty(),
        "usage: \"content\" is empty — hint: pass the note's text to leave on the ticket"
    );
    let id = managed_ticket_id(ticket_id).await?;
    if board_store().get_ticket_phase(&id).await?.is_none() {
        return Err(anyhow!("Ticket {id} not found — no note was left."));
    }
    board_store()
        .add_comment(&id, Role::Assistant.as_str(), content)
        .await?;
    Ok(format!("Note added to ticket {id} as 'assistant'."))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn tool_args(action: &str, name: Option<&str>) -> serde_json::Value {
        match name {
            Some(name) => json!({ "action": action, "workspace": name }),
            None => json!({ "action": action }),
        }
    }

    #[tokio::test]
    async fn pause_and_resume_a_ready_workspace() {
        let _guard = crate::util::test::STORE_LOCK.lock().await;
        crate::util::test::init_test_stores().await;
        let ws = crate::workspace::test_ws("/tmp/ws_ready");
        let tool = WorkspaceTool;
        crate::util::test::create_test_workspace("/tmp/ws_ready", "ws_ready").await;
        crate::workspace::store()
            .set_status("ws_ready", &WorkspaceStatus::Ready)
            .await
            .expect("mark ready");

        let reply = tool
            .execute(&ws, tool_args("pause", Some("ws_ready")))
            .await
            .expect("pause");
        assert!(
            reply.contains("ws_ready") && reply.contains("paused"),
            "got: {reply}"
        );
        assert!(
            crate::workspace::get_by_name("ws_ready")
                .await
                .expect("read")
                .expect("exists")
                .paused
        );

        let listing = tool
            .execute(&ws, tool_args("list", None))
            .await
            .expect("list");
        assert!(
            listing.contains("- ws_ready (ready, paused):"),
            "got: {listing}"
        );

        // Re-pausing reports the state it is already in, never a second freeze.
        let reply = tool
            .execute(&ws, tool_args("pause", Some("ws_ready")))
            .await
            .expect("re-pause");
        assert!(reply.contains("already paused"), "got: {reply}");

        let reply = tool
            .execute(&ws, tool_args("resume", Some("ws_ready")))
            .await
            .expect("resume");
        assert!(reply.contains("resumed"), "got: {reply}");
        assert!(
            !crate::workspace::get_by_name("ws_ready")
                .await
                .expect("read")
                .expect("exists")
                .paused
        );
        assert!(
            !tool
                .execute(&ws, tool_args("list", None))
                .await
                .expect("list")
                .contains("- ws_ready (ready, paused)"),
            "a resumed workspace must not carry the pause marker"
        );
    }

    /// Every managed workspace at once: the ready one is written, the not-ready one is skipped
    /// and reported as skipped. Driven against the test's own store, so the fleet-wide write
    /// can only reach rows this test created.
    #[tokio::test]
    async fn pause_every_managed_workspace_skips_not_ready() {
        let (store, _dir) = crate::open_test_store!(WorkspaceStore, "workspace");
        let root = crate::util::test::test_root();
        let ready = root.join("ws_fleet");
        let pending = root.join("ws_fleet_pending");
        for dir in [&ready, &pending] {
            std::fs::create_dir_all(dir).expect("create workspace dir");
        }
        let ready = ready.to_str().expect("utf-8 path");
        store.add("ws_fleet", ready).await.expect("add ws_fleet");
        store
            .set_status("ws_fleet", &WorkspaceStatus::Ready)
            .await
            .expect("mark ready");
        // A fresh row is created paused (the pickup step lifts it), so the fleet pause below
        // starts from a running pipeline.
        store.set_paused("ws_fleet", false).await.expect("unpause");
        // Another not-ready workspace must be skipped rather than written — left unpaused, so
        // a write would show.
        store
            .add("ws_fleet_pending", pending.to_str().expect("utf-8 path"))
            .await
            .expect("add ws_fleet_pending");
        store
            .set_paused("ws_fleet_pending", false)
            .await
            .expect("unpause ws_fleet_pending");
        let workspaces = store.list().await.expect("list");

        let reply = set_pipelines_paused(&store, &workspaces, true)
            .await
            .expect("pause all");
        assert!(
            reply.text.contains("- ws_fleet: paused"),
            "got: {}",
            reply.text
        );
        assert!(
            reply
                .text
                .contains("- ws_fleet_pending: skipped — not ready (pending)"),
            "got: {}",
            reply.text
        );
        assert!(
            reply.partial,
            "a workspace the call left untouched makes the fleet call partial: {}",
            reply.text
        );
        assert!(
            store
                .get_by_name("ws_fleet")
                .await
                .expect("read")
                .expect("exists")
                .paused
        );
        assert!(
            !store
                .get_by_name("ws_fleet_pending")
                .await
                .expect("read")
                .expect("exists")
                .paused,
            "a not-ready workspace must not be paused"
        );

        // A second fleet call, resuming: the ready workspace is written again and the
        // not-ready one is still skipped.
        let workspaces = store.list().await.expect("list");
        let reply = set_pipelines_paused(&store, &workspaces, false)
            .await
            .expect("resume all");
        assert!(
            reply.text.contains("- ws_fleet: resumed"),
            "got: {}",
            reply.text
        );
        assert!(
            reply.partial,
            "the not-ready workspace is left untouched by the resume too: {}",
            reply.text
        );

        // Nothing managed: the same plain wording `list` uses.
        let reply = set_pipelines_paused(&store, &[], true)
            .await
            .expect("empty set");
        assert_eq!(reply.text, NO_WORKSPACE);
    }

    /// The unnamed form of `pause` / `resume` is the fleet-wide write, so it may only be
    /// reached by a call that names nothing else: any other *declared* field — whether it names
    /// a place (`name` and `path` belong to `add`, a ticket id to the ticket actions) or the
    /// ticket id the product's argument repair makes of a mistaken `id` — is a usage error. A key
    /// no schema declares is refused earlier, for every action. The read actions take the same
    /// address and ignore a declared field they do not use.
    #[tokio::test]
    async fn a_misspelled_address_never_escalates_to_the_fleet() {
        let _guard = crate::util::test::STORE_LOCK.lock().await;
        crate::util::test::init_test_stores().await;
        let tool = WorkspaceTool;
        crate::util::test::create_test_workspace("/tmp/ws_address", "ws_address").await;
        crate::workspace::store()
            .set_status("ws_address", &WorkspaceStatus::Ready)
            .await
            .expect("mark ready");
        let ws = crate::workspace::test_ws("/tmp/ws_address");

        for call in [
            json!({ "action": "pause", "name": "ws_address" }),
            json!({ "action": "resume", "path": "/tmp/ws_address" }),
            json!({ "action": "resume", "ticket_id": "ws_address-1" }),
            crate::tools::normalize_tool_call(
                "workspace",
                json!({ "action": "pause", "id": "ws_address" }),
            )
            .1,
        ] {
            let err = tool
                .execute(&ws, call.clone())
                .await
                .unwrap_err()
                .to_string();
            assert!(err.contains("usage:"), "for {call}: {err}");
        }

        // A key no schema declares never reaches the address rule at all: the one unknown-field
        // check every action goes through refuses it first, naming the reference.
        for call in [
            json!({ "action": "pause", "workspace_name": "ws_address" }),
            json!({ "action": "list", "workspace": "ws_address", "folder": "/tmp/ws_address" }),
        ] {
            let err = tool
                .execute(&ws, call.clone())
                .await
                .unwrap_err()
                .to_string();
            assert!(
                err.contains("unknown field") && err.contains("reference"),
                "for {call}: {err}"
            );
        }

        // A wrong-typed address is a usage error too, and it names the field the caller wrote.
        for value in [
            json!(3),
            json!(["ws_address"]),
            json!({ "name": "ws_address" }),
        ] {
            let err = tool
                .execute(&ws, json!({ "action": "resume", "workspace": value }))
                .await
                .unwrap_err()
                .to_string();
            assert!(
                err.contains("usage:") && err.contains("workspace"),
                "got: {err}"
            );
        }
        assert!(
            !crate::workspace::get_by_name("ws_address")
                .await
                .expect("read")
                .expect("exists")
                .paused,
            "a refused address must not pause anything"
        );

        // A stray *declared* field on a read action is ignored rather than refused: the answer is
        // the listing the call gives without it, neither widened nor dropped. (Narrowed to this
        // one workspace, so a test running beside this one cannot change what is listed.)
        for args in [
            json!({ "action": "list", "workspace": "ws_address" }),
            json!({ "action": "list", "workspace": "ws_address", "phase": "done" }),
        ] {
            let listing = tool.execute(&ws, args.clone()).await.expect("list");
            assert!(
                listing.starts_with("Managed workspaces:\n- ws_address ("),
                "for {args}: {listing}"
            );
        }

        // The named form still reaches exactly the workspace it names.
        let reply = tool
            .execute(&ws, json!({ "action": "pause", "workspace": "ws_address" }))
            .await
            .expect("pause");
        assert!(
            reply.contains("Pipeline paused for workspace 'ws_address'"),
            "got: {reply}"
        );
    }

    /// A bare number is never a valid `ticket` / `comment` address.
    #[tokio::test]
    async fn ticket_actions_refuse_a_bare_number() {
        crate::util::test::init_test_stores().await;
        let ws = crate::workspace::test_ws("/tmp/ws_bare");
        let tool = WorkspaceTool;

        let err = tool
            .execute(&ws, json!({ "action": "ticket", "ticket_id": "42" }))
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("<workspace>-<number>"), "got: {err}");

        let err = tool
            .execute(
                &ws,
                json!({ "action": "comment", "ticket_id": "42", "content": "hi" }),
            )
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("<workspace>-<number>"), "got: {err}");
    }

    /// `ticket` refuses an id whose workspace is not managed and an id with no such ticket.
    #[tokio::test]
    async fn ticket_refuses_a_not_managed_workspace_and_missing_ticket() {
        crate::util::test::init_test_stores().await;
        let ws = crate::workspace::test_ws("/tmp/ws_ticket");
        let tool = WorkspaceTool;

        let err = tool
            .execute(
                &ws,
                json!({ "action": "ticket", "ticket_id": "ws_ghost-1" }),
            )
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("No managed workspace exists"), "got: {err}");

        crate::util::test::create_test_workspace("/tmp/ws_ticket", "ws_ticket").await;
        let err = tool
            .execute(
                &ws,
                json!({ "action": "ticket", "ticket_id": "ws_ticket-9999" }),
            )
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("not found"), "got: {err}");
    }

    /// `comment` on a ticket that does not exist leaves no note.
    #[tokio::test]
    async fn comment_refuses_a_missing_ticket() {
        crate::util::test::init_test_stores().await;
        let tool = WorkspaceTool;
        crate::util::test::create_test_workspace("/tmp/ws_note", "ws_note").await;
        let ws = crate::workspace::test_ws("/tmp/ws_note");

        let err = tool
            .execute(
                &ws,
                json!({ "action": "comment", "ticket_id": "ws_note-9999", "content": "   " }),
            )
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("usage:"), "got: {err}");

        let err = tool
            .execute(
                &ws,
                json!({ "action": "comment", "ticket_id": "ws_note-9999", "content": "hi" }),
            )
            .await
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("not found") && err.contains("no note"),
            "got: {err}"
        );
        assert!(
            board_store()
                .get_comments("ws_note-9999")
                .await
                .expect("read")
                .is_empty(),
            "a missing ticket must gain no note"
        );
    }

    /// `board` refuses the archived phase, lists finished tickets of managed workspaces and
    /// never a ticket of one that is not managed.
    #[tokio::test]
    async fn board_refuses_archived_and_skips_workspaces_that_are_not_managed() {
        crate::util::test::init_test_stores().await;
        let tool = WorkspaceTool;
        let ws = crate::util::test::create_test_workspace("/tmp/ws_board", "ws_board").await;
        let done_id = crate::util::test::make_ticket(
            board_store(),
            &ws,
            "workspace board done",
            TicketPhase::Done,
        )
        .await;
        // A ticket of a workspace that is not managed.
        let ghost = crate::workspace::test_ws_named("/tmp/ws_ghost", "ws_ghost");
        let ghost_id =
            crate::util::test::make_ticket(board_store(), &ghost, "ghost done", TicketPhase::Done)
                .await;

        let err = tool
            .execute(&ws, json!({ "action": "board", "phase": "archived" }))
            .await
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("Archived tickets are never listed"),
            "got: {err}"
        );

        let listing = tool
            .execute(&ws, json!({ "action": "board", "phase": "done" }))
            .await
            .expect("board");
        assert!(
            listing.contains(&done_id),
            "a done ticket of a managed workspace must be listed: {listing}"
        );
        assert!(
            !listing.contains(&ghost_id),
            "a ticket of a workspace that is not managed must never be listed: {listing}"
        );
        // The default listing keeps finished tickets — deliberately unlike the manager's own
        // listing, which hides them.
        let listing = tool
            .execute(&ws, json!({ "action": "board" }))
            .await
            .expect("board");
        assert!(
            listing.contains(&done_id),
            "a done ticket must be listed without a phase filter: {listing}"
        );
    }

    /// `list` marks the admin's selected workspace and says so when none is.
    #[tokio::test]
    #[serial_test::serial(gui_admin_workspace)] // writes the shared seeded admin row
    async fn list_marks_the_active_workspace_or_says_none() {
        crate::util::test::init_test_stores().await;
        let tool = WorkspaceTool;
        let ws = crate::workspace::test_ws("/tmp/ws_active");
        crate::users::test_util::with_test_workspaces(
            &[("/tmp/ws_active", "ws_active")],
            crate::users::test_util::with_admin_workspace_restored(async {
                crate::users::store()
                    .set_selected_workspace(crate::users::ADMIN_USER_NAME, Some("ws_active"))
                    .await
                    .expect("select");
                let listing = tool
                    .execute(&ws, tool_args("list", None))
                    .await
                    .expect("list");
                assert!(listing.contains("- ws_active ("), "got: {listing}");
                assert!(listing.contains("[active]"), "got: {listing}");
                assert!(
                    !listing.contains("No workspace is active."),
                    "got: {listing}"
                );

                // A personal selection is not a managed workspace, so nothing is active.
                crate::users::store()
                    .set_selected_workspace(crate::users::ADMIN_USER_NAME, Some("personal:admin"))
                    .await
                    .expect("select personal");
                let listing = tool
                    .execute(&ws, tool_args("list", None))
                    .await
                    .expect("list");
                assert!(
                    listing.contains("No workspace is active."),
                    "got: {listing}"
                );
                assert!(!listing.contains("[active]"), "got: {listing}");
            }),
        )
        .await;
    }

    /// A named listing is answered about that workspace: it narrows to the one named, and a name
    /// that is not managed is the not-found refusal naming it rather than a report on the fleet.
    #[tokio::test]
    async fn a_named_listing_answers_about_that_workspace() {
        let _guard = crate::util::test::STORE_LOCK.lock().await;
        crate::util::test::init_test_stores().await;
        crate::users::test_util::with_test_workspaces(
            &[("/tmp/ws_named", "ws_named"), ("/tmp/ws_other", "ws_other")],
            async {
                let listing = list_workspaces(Some("ws_named"))
                    .await
                    .expect("a named listing");
                assert!(listing.contains("- ws_named ("), "got: {listing}");
                assert!(
                    !listing.contains("- ws_other ("),
                    "a named listing narrows to the one named: {listing}"
                );

                let missing = list_workspaces(Some("ws_absent"))
                    .await
                    .expect_err("an unmanaged name")
                    .to_string();
                assert!(missing.contains("ws_absent"), "got: {missing}");
                assert!(
                    !missing.contains("No managed workspaces exist."),
                    "a named listing answers about the name, not the fleet: {missing}"
                );
            },
        )
        .await;
    }

    /// `reference` hands over the settings reference verbatim.
    #[tokio::test]
    async fn reference_is_the_settings_reference_verbatim() {
        let ws = crate::workspace::test_ws("/tmp/ws_reference");
        let reply = WorkspaceTool
            .execute(&ws, json!({ "action": "reference" }))
            .await
            .expect("reference");
        assert_eq!(reply, crate::settings::reference());
    }

    /// `show` is the one read that carries a workspace's own settings: its address and state,
    /// the rules an agent there is told, and the commands verification will run.
    #[tokio::test]
    async fn show_reports_a_workspaces_settings() {
        let _guard = crate::util::test::STORE_LOCK.lock().await;
        crate::util::test::init_test_stores().await;
        let tool = WorkspaceTool;
        let ws = crate::workspace::test_ws("/tmp/ws_show");
        crate::util::test::create_test_workspace("/tmp/ws_show", "ws_show").await;
        crate::workspace::store()
            .set_maintenance_enabled("ws_show", true)
            .await
            .expect("maintenance on");
        crate::workspace::store()
            .set_notes("ws_show", "be nice to the fixtures")
            .await
            .expect("rules");
        crate::workspace::store()
            .set_diagnostics(
                "ws_show",
                &crate::DiagnosticsCommands {
                    format: Some("cargo fmt".to_string()),
                    ..Default::default()
                },
            )
            .await
            .expect("diagnostics");

        let reply = tool
            .execute(&ws, tool_args("show", Some("ws_show")))
            .await
            .expect("show");
        assert!(reply.starts_with("Workspace 'ws_show':"), "got: {reply}");
        for expected in [
            "- path: /tmp/ws_show",
            "- status: pending",
            "- pipeline: running",
            "- maintenance: on",
            "- active project: no",
            "- rules:\n  be nice to the fixtures",
            "  - format: cargo fmt",
            "  - build: not discovered",
        ] {
            assert!(reply.contains(expected), "missing {expected:?} in: {reply}");
        }

        // No rules and no commands yet: both are spelled out rather than left blank.
        crate::util::test::create_test_workspace("/tmp/ws_show_bare", "ws_show_bare").await;
        let reply = tool
            .execute(&ws, tool_args("show", Some("ws_show_bare")))
            .await
            .expect("show bare");
        assert!(reply.contains("- rules: none"), "got: {reply}");
        assert!(
            reply.contains("- diagnostics: not discovered"),
            "got: {reply}"
        );
        assert!(reply.contains("- maintenance: off"), "got: {reply}");
    }

    /// The store's 4000-character cap is reported, never applied silently.
    #[tokio::test]
    async fn set_rules_reports_the_stores_truncation() {
        let _guard = crate::util::test::STORE_LOCK.lock().await;
        crate::util::test::init_test_stores().await;
        let tool = WorkspaceTool;
        let ws = crate::workspace::test_ws("/tmp/ws_rules");
        crate::util::test::create_test_workspace("/tmp/ws_rules", "ws_rules").await;
        let cap = crate::workspace::MAX_WORKSPACE_NOTES_CHARS;

        let short = tool
            .execute(
                &ws,
                json!({ "action": "set_rules", "workspace": "ws_rules", "rules": "be nice" }),
            )
            .await
            .expect("set rules");
        assert!(
            short.contains("now 7 characters long") && !short.contains("truncated"),
            "got: {short}"
        );

        let long = "r".repeat(cap + 10);
        let reply = tool
            .execute(
                &ws,
                json!({ "action": "set_rules", "workspace": "ws_rules", "rules": long }),
            )
            .await
            .expect("set long rules");
        assert!(
            reply.contains(&format!("now {cap} characters long"))
                && reply.contains(&format!("truncated to {cap} characters")),
            "got: {reply}"
        );
        let stored = crate::workspace::get_by_name("ws_rules")
            .await
            .expect("read")
            .expect("exists");
        assert_eq!(stored.notes.chars().count(), cap);
    }

    /// An absent command keeps what the row holds and an empty string clears it, so a partial
    /// `set_diagnostics` can never blank the commands it did not name.
    #[tokio::test]
    async fn set_diagnostics_keeps_an_omitted_field_and_clears_an_empty_one() {
        let _guard = crate::util::test::STORE_LOCK.lock().await;
        crate::util::test::init_test_stores().await;
        let tool = WorkspaceTool;
        let ws = crate::workspace::test_ws("/tmp/ws_cmds");
        crate::util::test::create_test_workspace("/tmp/ws_cmds", "ws_cmds").await;

        let reply = tool
            .execute(
                &ws,
                json!({
                    "action": "set_diagnostics",
                    "workspace": "ws_cmds",
                    "format": "cargo fmt",
                    "unit_test": "cargo test",
                }),
            )
            .await
            .expect("set diagnostics");
        assert!(
            reply.contains("- format: cargo fmt")
                && reply.contains("- unit-test: cargo test")
                && reply.contains("- build: not discovered"),
            "got: {reply}"
        );
        assert!(reply.contains("invalidated"), "got: {reply}");

        // `format` cleared by the empty string, `unit_test` kept by its absence.
        let reply = tool
            .execute(
                &ws,
                json!({ "action": "set_diagnostics", "workspace": "ws_cmds", "format": "" }),
            )
            .await
            .expect("clear format");
        assert!(reply.contains("- format: not discovered"), "got: {reply}");
        let stored = crate::workspace::store()
            .get_diagnostics("ws_cmds")
            .await
            .expect("read")
            .expect("diagnostics");
        assert_eq!(stored.format, None);
        assert_eq!(stored.unit_test.as_deref(), Some("cargo test"));
    }

    /// `maintenance` judges its switch before it reads a workspace, and reports the state the
    /// store itself wrote.
    #[tokio::test]
    async fn maintenance_needs_its_switch_before_a_workspace() {
        let _guard = crate::util::test::STORE_LOCK.lock().await;
        crate::util::test::init_test_stores().await;
        let ws = crate::workspace::test_ws("/tmp/ws_maint");
        crate::util::test::create_test_workspace("/tmp/ws_maint", "ws_maint").await;

        let err = WorkspaceTool
            .execute(
                &ws,
                json!({ "action": "maintenance", "workspace": "ws_maint_ghost" }),
            )
            .await
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("missing required argument \"maintenance\""),
            "a bad call must not reach the workspace lookup: {err}"
        );

        let reply = WorkspaceTool
            .execute(
                &ws,
                json!({ "action": "maintenance", "workspace": "ws_maint", "maintenance": true }),
            )
            .await
            .expect("maintenance on");
        assert!(
            reply.contains("Maintenance is now on for workspace 'ws_maint'")
                && reply.contains("next poll"),
            "got: {reply}"
        );
        assert!(
            crate::workspace::get_by_name("ws_maint")
                .await
                .expect("read")
                .expect("exists")
                .maintenance_enabled
        );
    }

    /// A `set_diagnostics` naming no command field is refused before the store: re-writing the
    /// identical blob would bump the generation and cancel an in-flight discovery for nothing.
    /// The refusal comes before the workspace lookup, so nothing is read at all.
    #[tokio::test]
    async fn set_diagnostics_refuses_a_call_that_names_no_command() {
        let _guard = crate::util::test::STORE_LOCK.lock().await;
        crate::util::test::init_test_stores().await;
        let ws = crate::workspace::test_ws("/tmp/ws_cmds_none");
        crate::util::test::create_test_workspace("/tmp/ws_cmds_none", "ws_cmds_none").await;

        for address in ["ws_cmds_none", "ws_cmds_ghost"] {
            let err = WorkspaceTool
                .execute(
                    &ws,
                    json!({ "action": "set_diagnostics", "workspace": address }),
                )
                .await
                .unwrap_err()
                .to_string();
            assert!(
                err.contains("at least one command field") && err.contains("unit_test"),
                "got: {err}"
            );
        }
        assert!(
            crate::workspace::store()
                .get_diagnostics("ws_cmds_none")
                .await
                .expect("read")
                .is_none(),
            "a refused call must not write anything"
        );
    }

    /// What a deleted workspace left on disk is read from the folder itself: a folder removed by
    /// hand is not reported as still there, and only a repository names one.
    #[test]
    fn the_delete_answer_names_a_folder_only_as_it_really_is() {
        let folder = tempfile::TempDir::new().expect("temp dir");
        let path = folder.path().to_str().expect("utf-8 path");
        assert_eq!(
            folder_note(path),
            format!("The project folder at {path} stays.")
        );
        std::fs::create_dir(folder.path().join(".git")).expect("make a repository");
        assert_eq!(
            folder_note(path),
            format!("The project folder at {path} (git repository included) stays.")
        );
        std::fs::remove_dir_all(folder.path()).expect("remove the folder by hand");
        assert_eq!(
            folder_note(path),
            format!("The project folder at {path} is gone.")
        );
    }

    /// `delete` removes the row and names what it left behind, so the admin knows the folder can
    /// be added back and the tickets are still there.
    #[tokio::test]
    #[serial_test::serial(gui_admin_workspace)] // writes the shared seeded admin row
    async fn delete_names_what_remains_on_disk() {
        let _guard = crate::util::test::STORE_LOCK.lock().await;
        crate::util::test::init_test_stores().await;
        crate::users::test_util::with_admin_workspace_restored(async {
            let tool = WorkspaceTool;
            let ws = crate::workspace::test_ws("/tmp/ws_del_gone");
            let gone =
                crate::util::test::create_test_workspace("/tmp/ws_del_gone", "ws_del_gone").await;
            crate::util::test::create_test_workspace("/tmp/ws_del_keep", "ws_del_keep").await;
            let ticket = crate::util::test::make_ticket(
                board_store(),
                &gone,
                "delete leaves me",
                TicketPhase::Queued,
            )
            .await;
            crate::users::store()
                .set_selected_workspace(crate::users::ADMIN_USER_NAME, Some("ws_del_gone"))
                .await
                .expect("select");

            let reply = tool
                .execute(&ws, tool_args("delete", Some("ws_del_gone")))
                .await
                .expect("delete");
            assert!(
                reply.contains("Deleted managed workspace 'ws_del_gone'"),
                "got: {reply}"
            );
            assert!(reply.contains("/tmp/ws_del_gone"), "got: {reply}");
            // The answer names a repository only when the folder really has one — a deleted
            // project that is no repository has none to keep.
            assert_eq!(
                reply.contains("git repository"),
                crate::git::commands::is_git_repo(std::path::Path::new("/tmp/ws_del_gone")),
                "the repository half must match what is on disk: {reply}"
            );
            assert!(reply.contains("tickets"), "got: {reply}");
            assert!(
                reply.contains("Your active project is now '"),
                "another managed workspace survives, so the selection must move to it: {reply}"
            );
            assert!(
                crate::workspace::get_by_name("ws_del_gone")
                    .await
                    .expect("read")
                    .is_none(),
                "the row is gone"
            );
            assert!(
                board_store()
                    .get_ticket(&ticket)
                    .await
                    .expect("read")
                    .is_some(),
                "deleting a workspace must not delete its tickets"
            );
            assert_ne!(
                crate::users::resolve_selected_workspace_name(crate::users::ADMIN_USER_NAME)
                    .await
                    .as_deref(),
                Some("ws_del_gone"),
                "the active project must not stay on the deleted workspace"
            );

            // A second delete is refused with the live set named.
            let err = tool
                .execute(&ws, tool_args("delete", Some("ws_del_gone")))
                .await
                .unwrap_err()
                .to_string();
            assert!(err.contains("No managed workspace exists"), "got: {err}");
        })
        .await;
    }

    /// `use` writes the admin's stored selection — the same row the desktop's switcher writes —
    /// so it takes effect without a restart.
    #[tokio::test]
    #[serial_test::serial(gui_admin_workspace)] // writes the shared seeded admin row
    async fn use_makes_a_workspace_the_active_project() {
        let _guard = crate::util::test::STORE_LOCK.lock().await;
        crate::util::test::init_test_stores().await;
        crate::users::test_util::with_test_workspaces(
            &[("/tmp/ws_use", "ws_use")],
            crate::users::test_util::with_admin_workspace_restored(async {
                let ws = crate::workspace::test_ws("/tmp/ws_use");
                let reply = WorkspaceTool
                    .execute(&ws, tool_args("use", Some("ws_use")))
                    .await
                    .expect("use");
                assert!(
                    reply.contains("'ws_use' is now your active project")
                        && reply.contains("without a restart"),
                    "got: {reply}"
                );
                assert_eq!(
                    crate::users::resolve_selected_workspace_name(crate::users::ADMIN_USER_NAME)
                        .await
                        .as_deref(),
                    Some("ws_use")
                );

                // A name that is not managed is refused, and the selection is left alone.
                let err = WorkspaceTool
                    .execute(&ws, tool_args("use", Some("ws_ghost")))
                    .await
                    .unwrap_err()
                    .to_string();
                assert!(err.contains("No managed workspace exists"), "got: {err}");
                assert_eq!(
                    crate::users::resolve_selected_workspace_name(crate::users::ADMIN_USER_NAME)
                        .await
                        .as_deref(),
                    Some("ws_use")
                );
            }),
        )
        .await;
    }

    /// The two re-analysis actions report what they started and what they touched: a full
    /// rediscovery pauses the pipeline, while a diagnostics one leaves the status, the pause and the
    /// per-role contexts alone and clears the stored commands.
    #[tokio::test]
    #[serial_test::serial(gui_admin_workspace)]
    async fn the_reanalysis_actions_report_what_they_started() {
        let _guard = crate::util::test::STORE_LOCK.lock().await;
        crate::util::test::init_test_stores().await;
        crate::users::test_util::with_test_workspaces(
            &[("/tmp/ws_reanalyse", "ws_reanalyse")],
            async {
                let ws = crate::workspace::test_ws("/tmp/ws_reanalyse");
                let commands = crate::DiagnosticsCommands {
                    format: Some("cargo fmt".to_string()),
                    ..crate::DiagnosticsCommands::default()
                };
                crate::workspace::store()
                    .set_diagnostics("ws_reanalyse", &commands)
                    .await
                    .expect("seed the commands");

                let reply = WorkspaceTool
                    .execute(
                        &ws,
                        tool_args("rediscover_diagnostics", Some("ws_reanalyse")),
                    )
                    .await
                    .expect("rediscover_diagnostics");
                assert!(
                    reply.contains("stored commands were cleared")
                        && reply
                            .contains("status, its pause and its per-role contexts are untouched"),
                    "got: {reply}"
                );
                assert!(
                    crate::workspace::store()
                        .get_diagnostics("ws_reanalyse")
                        .await
                        .expect("read")
                        .is_none(),
                    "the stored commands are cleared while they are re-detected"
                );

                let reply = WorkspaceTool
                    .execute(&ws, tool_args("rediscover", Some("ws_reanalyse")))
                    .await
                    .expect("rediscover");
                assert!(
                    reply.contains("per-role contexts were cleared")
                        && reply.contains("pipeline is paused until discovery finishes"),
                    "got: {reply}"
                );
                let row = crate::workspace::store()
                    .get_by_name("ws_reanalyse")
                    .await
                    .expect("read")
                    .expect("the workspace is still there");
                assert!(row.paused, "a full rediscovery pauses the pipeline");
            },
        )
        .await;
    }

    /// An action and a field this tool does not know both teach where the whole surface is: the
    /// `reference` action, which is one text shared with `mahbot config reference`.
    #[tokio::test]
    async fn an_unknown_action_and_field_name_the_reference() {
        let ws = crate::workspace::test_ws("/tmp/ws_unknown");
        let err = WorkspaceTool
            .execute(&ws, json!({ "action": "explode" }))
            .await
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("unknown action 'explode'") && err.contains("`reference` action"),
            "got: {err}"
        );

        let err = WorkspaceTool
            .execute(
                &ws,
                json!({ "action": "list", "folder": "/tmp/ws_unknown" }),
            )
            .await
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("unknown field 'folder'") && err.contains("reference"),
            "got: {err}"
        );
    }
}