solomd-mcp-test 0.4.2

Model Context Protocol server for SoloMD vaults — exposes a Markdown notes folder to Claude Code, Codex CLI, Cursor, Cline, Continue, Zed, and any other MCP client
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
//! MCP tool definitions + handlers.
//!
//! All eight v2.2 tools live here. The two write tools are gated by
//! `allow_write` — when false they return an error explaining how to enable
//! them, and they are still listed so clients see consistent capabilities
//! (this matches what most MCP servers do for safety toggles). If you'd
//! rather *omit* them entirely, build with `--allow-write` off and the
//! checks here will refuse the call.

use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;

use rmcp::{
    handler::server::{router::tool::ToolRouter, wrapper::Parameters},
    model::{CallToolResult, Content, Implementation, ServerCapabilities, ServerInfo},
    schemars::{self, JsonSchema},
    tool, tool_handler, tool_router, ErrorData as McpError, ServerHandler,
};
use serde::{Deserialize, Serialize};
use tokio::process::Command as AsyncCommand;
use tracing::debug;

use crate::safety;
use crate::trace_reader;
use crate::workspace::{self, BacklinkRef, HeadingRef, NoteMeta, TagCount};

// ---------------------------------------------------------------------------
// Server state
// ---------------------------------------------------------------------------

#[derive(Clone)]
pub struct SoloMdServer {
    inner: Arc<ServerState>,
    tool_router: ToolRouter<Self>,
}

struct ServerState {
    /// Ordered list of `(alias, canonical_path)` workspaces. The first entry
    /// is the *default* — tool calls without an explicit `workspace`
    /// argument resolve to it (back-compat with single-workspace clients).
    workspaces: Vec<(String, PathBuf)>,
    allow_write: bool,
}

impl SoloMdServer {
    /// `workspaces` is required to be non-empty (the CLI parser enforces
    /// this); the first entry becomes the default workspace.
    pub fn new(workspaces: Vec<(String, PathBuf)>, allow_write: bool) -> Self {
        assert!(
            !workspaces.is_empty(),
            "SoloMdServer requires at least one workspace"
        );
        Self {
            inner: Arc::new(ServerState {
                workspaces,
                allow_write,
            }),
            tool_router: Self::tool_router(),
        }
    }

    /// Default workspace (first registered).
    fn default_workspace(&self) -> &Path {
        &self.inner.workspaces[0].1
    }

    /// Comma-separated list of registered aliases — used in error messages.
    fn known_aliases(&self) -> String {
        self.inner
            .workspaces
            .iter()
            .map(|(a, _)| a.as_str())
            .collect::<Vec<_>>()
            .join(", ")
    }

    /// Resolve a tool argument's `workspace` field to a concrete workspace
    /// path. Resolution order:
    ///
    /// 1. `None` → default workspace (back-compat).
    /// 2. `Some(s)` matches a registered alias → that alias's path.
    /// 3. `Some(s)` is an absolute path that canonicalises to a registered
    ///    workspace path → that workspace.
    /// 4. Otherwise → `Err`.
    pub fn resolve_workspace(&self, opt: Option<&str>) -> Result<&Path, String> {
        let s = match opt {
            None => return Ok(self.default_workspace()),
            Some(s) if s.is_empty() => return Ok(self.default_workspace()),
            Some(s) => s,
        };

        // Alias match (exact, case-sensitive — aliases are user-controlled
        // tokens, not file paths).
        for (alias, path) in &self.inner.workspaces {
            if alias == s {
                return Ok(path.as_path());
            }
        }

        // Absolute path match — canonicalise both sides so symlinks /
        // trailing slashes don't trip us up.
        let candidate = PathBuf::from(s);
        if candidate.is_absolute() {
            if let Ok(canon) = candidate.canonicalize() {
                for (_, path) in &self.inner.workspaces {
                    if path == &canon {
                        return Ok(path.as_path());
                    }
                }
            }
        }

        Err(format!(
            "unknown workspace: {s}. Available aliases: {}",
            self.known_aliases()
        ))
    }
}

// ---------------------------------------------------------------------------
// Tool parameter structs
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ListNotesArgs {
    /// Optional sub-folder under the workspace root.
    #[serde(default)]
    pub folder: Option<String>,
    /// Maximum number of notes to return. Defaults to 100.
    #[serde(default)]
    pub limit: Option<u32>,
    /// Workspace selector — alias or absolute path. Default = first workspace.
    #[serde(default)]
    pub workspace: Option<String>,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ReadNoteArgs {
    /// Path to the note. May be absolute (inside the workspace) or relative.
    pub path: String,
    /// Workspace selector — alias or absolute path. Default = first workspace.
    #[serde(default)]
    pub workspace: Option<String>,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct SearchArgs {
    /// Query string. Treated as a literal substring unless `mode == "regex"`.
    pub query: String,
    /// `"literal"` (default) or `"regex"`.
    #[serde(default)]
    pub mode: Option<String>,
    /// Cap on number of matches. Default 200.
    #[serde(default)]
    pub limit: Option<u32>,
    /// Workspace selector — alias or absolute path. Default = first workspace.
    #[serde(default)]
    pub workspace: Option<String>,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct GetBacklinksArgs {
    /// Note name (file stem) to search for as a wikilink target.
    pub note_name: String,
    /// Workspace selector — alias or absolute path. Default = first workspace.
    #[serde(default)]
    pub workspace: Option<String>,
}

/// Truly-empty args (no inputs, no workspace selector).
///
/// Currently unused — every tool now accepts an optional `workspace`. Kept
/// in case a future tool genuinely takes nothing.
#[allow(dead_code)]
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct EmptyArgs {}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ListTagsArgs {
    /// Workspace selector — alias or absolute path. Default = first workspace.
    #[serde(default)]
    pub workspace: Option<String>,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ListTasksArgs {
    /// Workspace selector — alias or absolute path. Default = first workspace.
    #[serde(default)]
    pub workspace: Option<String>,
    /// `false` for open tasks only, `true` for completed only. Omit for both.
    #[serde(default)]
    pub done: Option<bool>,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct SyncStatusArgs {
    /// Workspace selector — alias or absolute path. Default = first workspace.
    #[serde(default)]
    pub workspace: Option<String>,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct GetOutlineArgs {
    /// Path to the note.
    pub path: String,
    /// Workspace selector — alias or absolute path. Default = first workspace.
    #[serde(default)]
    pub workspace: Option<String>,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct WriteNoteArgs {
    /// Path to the note. Created if it does not exist (parent must exist).
    pub path: String,
    /// New file content (UTF-8).
    pub content: String,
    /// If false (default), refuse to overwrite an existing file.
    #[serde(default)]
    pub allow_overwrite: Option<bool>,
    /// Workspace selector — alias or absolute path. Default = first workspace.
    #[serde(default)]
    pub workspace: Option<String>,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct AppendArgs {
    /// Path to an existing note.
    pub path: String,
    /// Text to append. A newline is added between existing content and the
    /// new text if the file does not already end with one.
    pub content: String,
    /// Workspace selector — alias or absolute path. Default = first workspace.
    #[serde(default)]
    pub workspace: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct SearchHit {
    pub path: String,
    pub line: u32,
    pub column: u32,
    pub snippet: Vec<String>,
}

#[derive(Debug, Serialize)]
pub struct WriteResult {
    pub ok: bool,
    pub bytes_written: usize,
    pub path: String,
}

// ---------------------------------------------------------------------------
// v3.1 SoloMD-only tool args (autogit / sync / share)
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct AutogitLogArgs {
    /// Path to the note (absolute or workspace-relative).
    pub path: String,
    /// Max commits to return (default 50, max 500).
    #[serde(default)]
    pub limit: Option<u32>,
    /// Workspace selector — alias or absolute path. Default = first workspace.
    #[serde(default)]
    pub workspace: Option<String>,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct AutogitDiffArgs {
    /// Path to the note.
    pub path: String,
    /// SHA (or short SHA) to diff. Defaults to comparing HEAD against
    /// the previous commit.
    #[serde(default)]
    pub sha: Option<String>,
    /// Base SHA (defaults to the parent of `sha`). Use this to compare
    /// arbitrary two commits.
    #[serde(default)]
    pub base: Option<String>,
    /// Workspace selector — alias or absolute path. Default = first workspace.
    #[serde(default)]
    pub workspace: Option<String>,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct AutogitRollbackArgs {
    /// Path to the note.
    pub path: String,
    /// SHA whose version of the file should overwrite the current
    /// working-tree copy.
    pub sha: String,
    /// Workspace selector — alias or absolute path. Default = first workspace.
    #[serde(default)]
    pub workspace: Option<String>,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ShareUrlArgs {
    /// Path to the note.
    pub path: String,
    /// Workspace selector — alias or absolute path. Default = first workspace.
    #[serde(default)]
    pub workspace: Option<String>,
}

/// v4.1 — args for `export_note`. Drives `app/scripts/solomd-export.mjs`,
/// the same headless export tool the `solomd export` CLI uses, so MCP
/// clients can produce .docx / .html / .txt artifacts in a CI / agent
/// loop without a running SoloMD GUI. Engine parity with the in-app GUI
/// export — same markdown-it config, same `docx` library.
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ExportNoteArgs {
    /// Path to the source `.md` (relative to the workspace, or absolute
    /// inside it).
    pub path: String,
    /// Output format. One of: `html`, `md`, `txt`, `docx`. Defaults to
    /// `html`.
    #[serde(default)]
    pub format: Option<String>,
    /// Where to write the result. Defaults to a sibling file next to
    /// `path` with the format-appropriate extension. Pass an absolute
    /// path or a workspace-relative path to override.
    #[serde(default)]
    pub output_path: Option<String>,
    /// Workspace selector — alias or absolute path. Default = first workspace.
    #[serde(default)]
    pub workspace: Option<String>,
    /// v4.11 — promote plain-text numbered section lines (`6.2 标题`,
    /// `6.2.1 标题`) to real headings during export, mirroring the GUI's
    /// opt-in «编号章节自动转标题» setting and the CLI's
    /// `--number-headings` flag. Defaults to false.
    #[serde(default)]
    pub number_headings: Option<bool>,
}

/// v4.0 Pillar 3 — args for `read_agent_trace`.
///
/// `workspace` is optional for back-compat with v3.x single-workspace
/// clients; if absent we fall back to the (currently single) workspace
/// the server was started with. P4's federation work will turn that into
/// a real "first registered workspace" lookup; for v4.0 it's a 1:1.
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ReadAgentTraceArgs {
    /// Run id under `<workspace>/.solomd/agent-runs/<run_id>/`.
    pub run_id: String,
    /// Optional workspace override. Defaults to the server's workspace.
    #[serde(default)]
    pub workspace: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct AutogitCommitMeta {
    pub sha: String,
    pub short_sha: String,
    pub author: String,
    pub time: i64,
    pub summary: String,
}

// ---------------------------------------------------------------------------
// Tool router
// ---------------------------------------------------------------------------

#[tool_router(router = tool_router)]
impl SoloMdServer {
    /// List notes in the workspace (metadata only — content is *not* loaded).
    #[tool(
        name = "list_notes",
        description = "List Markdown notes in a SoloMD workspace. Returns metadata only (path, name, title, mtime, size, summary). Use read_note to fetch full content. Pass `workspace` (alias or absolute path) to target a non-default workspace; omit it to use the first registered workspace."
    )]
    pub async fn list_notes(
        &self,
        args: Parameters<ListNotesArgs>,
    ) -> Result<CallToolResult, McpError> {
        let workspace = self
            .resolve_workspace(args.0.workspace.as_deref())
            .map_err(|e| McpError::invalid_params(e, None))?;
        let limit = args.0.limit.unwrap_or(100).min(1000) as usize;
        let folder = match args.0.folder.as_deref() {
            Some(f) => safety::resolve_subfolder(workspace, f)
                .map_err(|e| McpError::invalid_params(e, None))?,
            None => workspace.to_path_buf(),
        };

        let mut metas: Vec<NoteMeta> = Vec::new();
        for path in workspace::walk_markdown_files(&folder) {
            match workspace::scan_meta(&path) {
                Ok(m) => metas.push(m),
                Err(e) => debug!("scan_meta failed for {}: {}", path.display(), e),
            }
            if metas.len() >= limit {
                break;
            }
        }
        metas.sort_by(|a, b| b.mtime.cmp(&a.mtime));
        let json = serde_json::json!({ "notes": metas, "count": metas.len() });
        Ok(CallToolResult::success(vec![Content::json(json).map_err(
            |e| McpError::internal_error(e.to_string(), None),
        )?]))
    }

    /// Read the full content + parsed metadata of a single note.
    #[tool(
        name = "read_note",
        description = "Read a single Markdown note. Returns full content plus parsed front matter, headings, tags, and outbound wikilinks. Pass `workspace` (alias or absolute path) to target a non-default workspace; omit it to use the first registered workspace."
    )]
    pub async fn read_note(
        &self,
        args: Parameters<ReadNoteArgs>,
    ) -> Result<CallToolResult, McpError> {
        let workspace = self
            .resolve_workspace(args.0.workspace.as_deref())
            .map_err(|e| McpError::invalid_params(e, None))?;
        let path = safety::resolve_in(workspace, &args.0.path, true)
            .map_err(|e| McpError::invalid_params(e, None))?;
        let note = workspace::read_full(&path).map_err(|e| McpError::internal_error(e, None))?;
        Ok(CallToolResult::success(vec![Content::json(note).map_err(
            |e| McpError::internal_error(e.to_string(), None),
        )?]))
    }

    /// Search across notes. Prefers `rg` if on PATH, otherwise falls back to
    /// a Rust regex walk.
    #[tool(
        name = "search",
        description = "Search notes for a query. Returns up to `limit` matches with 3-line context. mode defaults to \"literal\"; pass \"regex\" for a regular-expression search. Pass `workspace` (alias or absolute path) to target a non-default workspace; omit it to use the first registered workspace."
    )]
    pub async fn search(&self, args: Parameters<SearchArgs>) -> Result<CallToolResult, McpError> {
        let workspace = self
            .resolve_workspace(args.0.workspace.as_deref())
            .map_err(|e| McpError::invalid_params(e, None))?;
        let mode = args.0.mode.as_deref().unwrap_or("literal");
        let limit = args.0.limit.unwrap_or(200).min(1000) as usize;
        let regex = matches!(mode, "regex");
        let hits = if has_rg().await {
            search_with_rg(workspace, &args.0.query, regex, limit).await
        } else {
            search_native(workspace, &args.0.query, regex, limit)
        }
        .map_err(|e| McpError::internal_error(e, None))?;
        Ok(CallToolResult::success(vec![Content::json(
            serde_json::json!({ "hits": hits, "count": hits.len() }),
        )
        .map_err(|e| McpError::internal_error(e.to_string(), None))?]))
    }

    /// Find every place that wikilinks `[[note_name]]`.
    #[tool(
        name = "get_backlinks",
        description = "Return wikilink-style backlinks (`[[note_name]]`) to the given note. Match is case-insensitive on the file stem. Pass `workspace` (alias or absolute path) to target a non-default workspace; omit it to use the first registered workspace."
    )]
    pub async fn get_backlinks(
        &self,
        args: Parameters<GetBacklinksArgs>,
    ) -> Result<CallToolResult, McpError> {
        let workspace = self
            .resolve_workspace(args.0.workspace.as_deref())
            .map_err(|e| McpError::invalid_params(e, None))?;
        let needle = args.0.note_name.trim().to_lowercase();
        if needle.is_empty() {
            return Err(McpError::invalid_params(
                "note_name must not be empty",
                None,
            ));
        }
        let mut out: Vec<BacklinkRef> = Vec::new();
        for path in workspace::walk_markdown_files(workspace) {
            let note = match workspace::read_full(&path) {
                Ok(n) => n,
                Err(_) => continue,
            };
            for link in &note.wikilinks {
                if link.target.to_lowercase() == needle {
                    let from_name = path
                        .file_name()
                        .and_then(|s| s.to_str())
                        .unwrap_or("")
                        .to_string();
                    out.push(BacklinkRef {
                        from_path: path.to_string_lossy().to_string(),
                        from_name,
                        line: link.line,
                        context: workspace::read_context(&path, link.line),
                    });
                }
            }
        }
        out.sort_by(|a, b| a.from_name.cmp(&b.from_name));
        Ok(CallToolResult::success(vec![Content::json(
            serde_json::json!({ "backlinks": out, "count": out.len() }),
        )
        .map_err(|e| McpError::internal_error(e.to_string(), None))?]))
    }

    /// Aggregated tag counts across the vault.
    #[tool(
        name = "list_tags",
        description = "List every tag found in a workspace (body `#tag` and front-matter `tags:`), sorted by count desc. Pass `workspace` (alias or absolute path) to target a non-default workspace; omit it to use the first registered workspace."
    )]
    pub async fn list_tags(
        &self,
        args: Parameters<ListTagsArgs>,
    ) -> Result<CallToolResult, McpError> {
        let workspace = self
            .resolve_workspace(args.0.workspace.as_deref())
            .map_err(|e| McpError::invalid_params(e, None))?;
        use std::collections::HashMap;
        let mut by_tag: HashMap<String, (u32, Vec<String>)> = HashMap::new();
        for path in workspace::walk_markdown_files(workspace) {
            let note = match workspace::read_full(&path) {
                Ok(n) => n,
                Err(_) => continue,
            };
            let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
            for tag in &note.tags {
                if seen.insert(tag) {
                    let e = by_tag.entry(tag.clone()).or_insert_with(|| (0, vec![]));
                    e.0 += 1;
                    e.1.push(note.path.clone());
                }
            }
        }
        let mut out: Vec<TagCount> = by_tag
            .into_iter()
            .map(|(tag, (count, files))| TagCount { tag, count, files })
            .collect();
        out.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.tag.cmp(&b.tag)));
        Ok(CallToolResult::success(vec![Content::json(
            serde_json::json!({ "tags": out, "count": out.len() }),
        )
        .map_err(|e| McpError::internal_error(e.to_string(), None))?]))
    }

    /// Every checkbox in the workspace.
    ///
    /// The line numbers are counted over the file as it sits on disk, front
    /// matter included — a caller that wants to toggle a box has to seek to
    /// the same line the editor would, and counting from the body instead
    /// would silently shift every task in a note that has front matter.
    #[tool(
        name = "list_tasks",
        description = "Return every Markdown checkbox (`- [ ]` / `- [x]`) in the workspace, with its file, 1-based line number, done state, and text. Checkboxes inside fenced code blocks and front matter are skipped. Pass `done` to filter to open or completed tasks only, and `workspace` (alias or absolute path) to target a non-default workspace."
    )]
    pub async fn list_tasks(
        &self,
        args: Parameters<ListTasksArgs>,
    ) -> Result<CallToolResult, McpError> {
        let workspace = self
            .resolve_workspace(args.0.workspace.as_deref())
            .map_err(|e| McpError::invalid_params(e, None))?;
        let want_done = args.0.done;
        let mut out: Vec<serde_json::Value> = Vec::new();
        for path in workspace::walk_markdown_files(workspace) {
            let note = match workspace::read_full(&path) {
                Ok(n) => n,
                Err(_) => continue,
            };
            for task in workspace::extract_tasks(&note.content) {
                if want_done.is_some_and(|w| w != task.done) {
                    continue;
                }
                out.push(serde_json::json!({
                    "file": note.path,
                    "line": task.line,
                    "done": task.done,
                    "text": task.text,
                }));
            }
        }
        Ok(CallToolResult::success(vec![Content::json(
            serde_json::json!({ "tasks": out, "count": out.len() }),
        )
        .map_err(|e| McpError::internal_error(e.to_string(), None))?]))
    }

    /// Heading outline for a note.
    #[tool(
        name = "get_outline",
        description = "Return the heading outline of a note, with level (1-6), text, and 1-based line number. Pass `workspace` (alias or absolute path) to target a non-default workspace; omit it to use the first registered workspace."
    )]
    pub async fn get_outline(
        &self,
        args: Parameters<GetOutlineArgs>,
    ) -> Result<CallToolResult, McpError> {
        let workspace = self
            .resolve_workspace(args.0.workspace.as_deref())
            .map_err(|e| McpError::invalid_params(e, None))?;
        let path = safety::resolve_in(workspace, &args.0.path, true)
            .map_err(|e| McpError::invalid_params(e, None))?;
        let raw = std::fs::read_to_string(&path)
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;
        let (_fm, body) = workspace::split_front_matter(&raw);
        let headings: Vec<HeadingRef> = workspace::extract_headings(body);
        Ok(CallToolResult::success(vec![Content::json(
            serde_json::json!({ "outline": headings }),
        )
        .map_err(|e| McpError::internal_error(e.to_string(), None))?]))
    }

    /// Write (or overwrite) a note. Gated by `--allow-write`.
    #[tool(
        name = "write_note",
        description = "Write a Markdown note to disk. Requires the server to be started with --allow-write. Refuses to overwrite an existing file unless `allow_overwrite` is true. Pass `workspace` (alias or absolute path) to target a non-default workspace; omit it to use the first registered workspace."
    )]
    pub async fn write_note(
        &self,
        args: Parameters<WriteNoteArgs>,
    ) -> Result<CallToolResult, McpError> {
        if !self.inner.allow_write {
            return Err(McpError::invalid_request(
                "write_note is disabled. Restart solomd-mcp with --allow-write to enable it.",
                None,
            ));
        }
        let workspace = self
            .resolve_workspace(args.0.workspace.as_deref())
            .map_err(|e| McpError::invalid_params(e, None))?;
        let path = safety::resolve_in(workspace, &args.0.path, false)
            .map_err(|e| McpError::invalid_params(e, None))?;
        let allow_overwrite = args.0.allow_overwrite.unwrap_or(false);
        if path.exists() && !allow_overwrite {
            return Err(McpError::invalid_request(
                format!(
                    "{} already exists. Pass allow_overwrite=true to replace it.",
                    path.display()
                ),
                None,
            ));
        }
        let bytes = args.0.content.len();
        std::fs::write(&path, args.0.content)
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;
        let result = WriteResult {
            ok: true,
            bytes_written: bytes,
            path: path.to_string_lossy().to_string(),
        };
        Ok(CallToolResult::success(vec![Content::json(result)
            .map_err(|e| {
                McpError::internal_error(e.to_string(), None)
            })?]))
    }

    // ---- v3.1 SoloMD-only tools (autogit / sync / share) -----------------

    /// List per-note commit history from SoloMD's AutoGit repo.
    #[tool(
        name = "autogit_log",
        description = "List the commit history for a single note from SoloMD's AutoGit repo (saves are auto-committed). Returns sha + short_sha + author + time (unix seconds) + summary, newest first. Pass `workspace` (alias or absolute path) to target a non-default workspace; omit it to use the first registered workspace."
    )]
    pub async fn autogit_log(
        &self,
        args: Parameters<AutogitLogArgs>,
    ) -> Result<CallToolResult, McpError> {
        let workspace = self
            .resolve_workspace(args.0.workspace.as_deref())
            .map_err(|e| McpError::invalid_params(e, None))?
            .to_path_buf();
        let path = safety::resolve_in(&workspace, &args.0.path, true)
            .map_err(|e| McpError::invalid_params(e, None))?;
        let limit = args.0.limit.unwrap_or(50).min(500) as usize;
        let commits =
            tokio::task::spawn_blocking(move || autogit_log_inner(&workspace, &path, limit))
                .await
                .map_err(|e| McpError::internal_error(format!("join: {e}"), None))?
                .map_err(|e| McpError::internal_error(e, None))?;
        let json = serde_json::json!({ "commits": commits, "count": commits.len() });
        Ok(CallToolResult::success(vec![Content::json(json).map_err(
            |e| McpError::internal_error(e.to_string(), None),
        )?]))
    }

    /// Show the textual diff for one note between two AutoGit commits.
    #[tool(
        name = "autogit_diff",
        description = "Show a unified diff for one note between two AutoGit commits. Defaults: sha=HEAD, base=parent of sha. Returns the diff as a string plus the resolved sha/base. Pass `workspace` (alias or absolute path) to target a non-default workspace; omit it to use the first registered workspace."
    )]
    pub async fn autogit_diff(
        &self,
        args: Parameters<AutogitDiffArgs>,
    ) -> Result<CallToolResult, McpError> {
        let workspace = self
            .resolve_workspace(args.0.workspace.as_deref())
            .map_err(|e| McpError::invalid_params(e, None))?
            .to_path_buf();
        let path = safety::resolve_in(&workspace, &args.0.path, true)
            .map_err(|e| McpError::invalid_params(e, None))?;
        let sha = args.0.sha.clone();
        let base = args.0.base.clone();
        let result = tokio::task::spawn_blocking(move || {
            autogit_diff_inner(&workspace, &path, sha.as_deref(), base.as_deref())
        })
        .await
        .map_err(|e| McpError::internal_error(format!("join: {e}"), None))?
        .map_err(|e| McpError::internal_error(e, None))?;
        Ok(CallToolResult::success(vec![Content::json(result)
            .map_err(|e| {
                McpError::internal_error(e.to_string(), None)
            })?]))
    }

    /// Restore a note's content from a specific AutoGit commit. Gated by
    /// `--allow-write`. Writes through the AutoGit repo so the rollback
    /// itself becomes a new commit on top.
    #[tool(
        name = "autogit_rollback",
        description = "Restore a note's content from a specific AutoGit commit by overwriting the working tree. Requires --allow-write. The rollback is itself a new save (and thus a new AutoGit commit), so the prior history is preserved. Pass `workspace` (alias or absolute path) to target a non-default workspace; omit it to use the first registered workspace."
    )]
    pub async fn autogit_rollback(
        &self,
        args: Parameters<AutogitRollbackArgs>,
    ) -> Result<CallToolResult, McpError> {
        if !self.inner.allow_write {
            return Err(McpError::invalid_request(
                "autogit_rollback is disabled. Restart solomd-mcp with --allow-write to enable it.",
                None,
            ));
        }
        let workspace = self
            .resolve_workspace(args.0.workspace.as_deref())
            .map_err(|e| McpError::invalid_params(e, None))?
            .to_path_buf();
        let path = safety::resolve_in(&workspace, &args.0.path, true)
            .map_err(|e| McpError::invalid_params(e, None))?;
        let sha = args.0.sha.clone();
        let path_str = path.to_string_lossy().to_string();
        let bytes =
            tokio::task::spawn_blocking(move || autogit_rollback_inner(&workspace, &path, &sha))
                .await
                .map_err(|e| McpError::internal_error(format!("join: {e}"), None))?
                .map_err(|e| McpError::internal_error(e, None))?;
        let result = WriteResult {
            ok: true,
            bytes_written: bytes,
            path: path_str,
        };
        Ok(CallToolResult::success(vec![Content::json(result)
            .map_err(|e| {
                McpError::internal_error(e.to_string(), None)
            })?]))
    }

    /// Read SoloMD's GitHub-sync state for the workspace.
    #[tool(
        name = "sync_status",
        description = "Return SoloMD's GitHub-sync configuration for a workspace: linked remote, current branch, encryption flag, last push/pull timestamps. Reads .solomd/sync.json — does not require credentials. Pass `workspace` (alias or absolute path) to target a non-default workspace; omit it to use the first registered workspace."
    )]
    pub async fn sync_status(
        &self,
        args: Parameters<SyncStatusArgs>,
    ) -> Result<CallToolResult, McpError> {
        let workspace = self
            .resolve_workspace(args.0.workspace.as_deref())
            .map_err(|e| McpError::invalid_params(e, None))?
            .to_path_buf();
        let json = tokio::task::spawn_blocking(move || sync_status_inner(&workspace))
            .await
            .map_err(|e| McpError::internal_error(format!("join: {e}"), None))?
            .map_err(|e| McpError::internal_error(e, None))?;
        Ok(CallToolResult::success(vec![Content::json(json).map_err(
            |e| McpError::internal_error(e.to_string(), None),
        )?]))
    }

    /// Compute the public share URL for a note (only valid if the
    /// workspace is linked to a public GitHub repo).
    #[tool(
        name = "share_url",
        description = "Return the public solomd.app/share/ URL for a note. Only resolves to a real page if the workspace's linked repo is public; for private repos the URL exists but raw.githubusercontent.com will 404. Use sync_status first to check `private`. Pass `workspace` (alias or absolute path) to target a non-default workspace; omit it to use the first registered workspace."
    )]
    pub async fn share_url(
        &self,
        args: Parameters<ShareUrlArgs>,
    ) -> Result<CallToolResult, McpError> {
        let workspace = self
            .resolve_workspace(args.0.workspace.as_deref())
            .map_err(|e| McpError::invalid_params(e, None))?
            .to_path_buf();
        let path = safety::resolve_in(&workspace, &args.0.path, true)
            .map_err(|e| McpError::invalid_params(e, None))?;
        let json = tokio::task::spawn_blocking(move || share_url_inner(&workspace, &path))
            .await
            .map_err(|e| McpError::internal_error(format!("join: {e}"), None))?
            .map_err(|e| McpError::internal_error(e, None))?;
        Ok(CallToolResult::success(vec![Content::json(json).map_err(
            |e| McpError::internal_error(e.to_string(), None),
        )?]))
    }

    /// Append to an existing note. Gated by `--allow-write`.
    #[tool(
        name = "append_to_note",
        description = "Append text to an existing note. Requires --allow-write. A newline is inserted between existing content and new text if needed. Pass `workspace` (alias or absolute path) to target a non-default workspace; omit it to use the first registered workspace."
    )]
    pub async fn append_to_note(
        &self,
        args: Parameters<AppendArgs>,
    ) -> Result<CallToolResult, McpError> {
        if !self.inner.allow_write {
            return Err(McpError::invalid_request(
                "append_to_note is disabled. Restart solomd-mcp with --allow-write to enable it.",
                None,
            ));
        }
        let workspace = self
            .resolve_workspace(args.0.workspace.as_deref())
            .map_err(|e| McpError::invalid_params(e, None))?;
        let path = safety::resolve_in(workspace, &args.0.path, true)
            .map_err(|e| McpError::invalid_params(e, None))?;
        let mut existing = std::fs::read_to_string(&path)
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;
        if !existing.ends_with('\n') && !existing.is_empty() {
            existing.push('\n');
        }
        existing.push_str(&args.0.content);
        let bytes = existing.len();
        std::fs::write(&path, existing)
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;
        let result = WriteResult {
            ok: true,
            bytes_written: bytes,
            path: path.to_string_lossy().to_string(),
        };
        Ok(CallToolResult::success(vec![Content::json(result)
            .map_err(|e| {
                McpError::internal_error(e.to_string(), None)
            })?]))
    }

    /// v4.0 Pillar 3 — return the agent trace for a single run.
    ///
    /// Reads `<workspace>/.solomd/agent-runs/<run_id>/trace.jsonl` and
    /// returns its lines as a JSON array, plus a count. Tolerates malformed
    /// v4.1 — Headless export. Shells out to
    /// `app/scripts/solomd-export.mjs` (Node) so we share the engine the
    /// `solomd export` CLI uses + the in-app GUI's markdown-it config.
    ///
    /// Read-only by default: the `output_path` is allowed to live OUTSIDE
    /// the workspace (e.g. `/tmp/foo.docx`) without requiring
    /// `--allow-write`. We treat exports as derived artifacts, not as
    /// modifications of the vault. Writing to a path INSIDE the
    /// workspace IS gated by `allow_write` for safety.
    #[tool(
        name = "export_note",
        description = "Export a Markdown note to html / md / txt / docx. Engine-parity with the SoloMD GUI export. Args: `path` (workspace-relative), `format` (default html), optional `output_path` (default: sibling file next to `path` with format-appropriate extension), optional `number_headings` (promote plain-text numbered sections like 6.2 / 6.2.1 to headings, default false). Returns the absolute output path. Requires Node.js + `pnpm install` in the SoloMD repo's app/ directory."
    )]
    pub async fn export_note(
        &self,
        args: Parameters<ExportNoteArgs>,
    ) -> Result<CallToolResult, McpError> {
        let workspace = self
            .resolve_workspace(args.0.workspace.as_deref())
            .map_err(|e| McpError::invalid_params(e, None))?
            .to_path_buf();
        let input_path = safety::resolve_in(&workspace, &args.0.path, true)
            .map_err(|e| McpError::invalid_params(e, None))?;

        let fmt = args.0.format.as_deref().unwrap_or("html").to_lowercase();
        if !matches!(fmt.as_str(), "html" | "md" | "txt" | "docx") {
            return Err(McpError::invalid_params(
                format!("unknown format: {fmt} (try html|md|txt|docx)"),
                None,
            ));
        }

        // Resolve output path. If user gave one, take it as-is — but if
        // it falls inside the workspace, we treat it as a write op and
        // require allow_write.
        let output_path = match args.0.output_path.as_deref() {
            Some(p) => {
                let pb = PathBuf::from(p);
                if pb.is_absolute() {
                    pb
                } else {
                    workspace.join(p)
                }
            }
            None => {
                let stem = input_path.file_stem().unwrap_or_default();
                let mut sibling = input_path.clone();
                sibling.set_file_name(format!("{}.{}", stem.to_string_lossy(), fmt));
                sibling
            }
        };
        let output_canonical_parent = output_path
            .parent()
            .and_then(|p| p.canonicalize().ok())
            .unwrap_or_else(|| output_path.clone());
        let inside_workspace = output_canonical_parent.starts_with(&workspace);
        if inside_workspace && !self.inner.allow_write {
            return Err(McpError::invalid_params(
                "output_path lives inside the workspace; writes require --allow-write".to_string(),
                None,
            ));
        }

        let script = find_export_script()
            .map_err(|e| McpError::internal_error(format!("export script not found: {e}"), None))?;
        let script_dir = script
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .to_path_buf();

        let mut cmd = AsyncCommand::new("node");
        cmd.arg(&script)
            .arg(&input_path)
            .arg("--format")
            .arg(&fmt)
            .arg("--output")
            .arg(&output_path);
        if args.0.number_headings.unwrap_or(false) {
            cmd.arg("--number-headings");
        }
        let out = cmd
            .current_dir(&script_dir)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .await
            .map_err(|e| McpError::internal_error(format!("spawn node: {e}"), None))?;
        if !out.status.success() {
            let stderr = String::from_utf8_lossy(&out.stderr);
            return Err(McpError::internal_error(
                format!("export failed: {stderr}"),
                None,
            ));
        }

        Ok(CallToolResult::success(vec![Content::json(
            serde_json::json!({
                "output_path": output_path.to_string_lossy(),
                "format": fmt,
            }),
        )
        .map_err(|e| McpError::internal_error(e.to_string(), None))?]))
    }

    /// lines (skipped, not errored) so partial / crashed runs are still
    /// inspectable. The reader is a slim duplicate of the canonical
    /// `app/src-tauri/src/trace.rs` parser — we don't path-dep into the
    /// app crate to keep `solomd-mcp` self-contained.
    #[tool(
        name = "read_agent_trace",
        description = "Return the agent run trace as an array of step objects. Lines from `<workspace>/.solomd/agent-runs/<run_id>/trace.jsonl`. Each step has ts (unix ms), seq (1-based), kind, plus kind-specific fields (provider/model/tool/result/...). See SoloMD v4 contracts C2 for the schema."
    )]
    pub async fn read_agent_trace(
        &self,
        args: Parameters<ReadAgentTraceArgs>,
    ) -> Result<CallToolResult, McpError> {
        let workspace = self
            .resolve_workspace(args.0.workspace.as_deref())
            .map_err(|e| McpError::invalid_params(e, None))?
            .to_path_buf();
        let run_id = args.0.run_id.trim().to_string();
        if !trace_reader::is_safe_run_id(&run_id) {
            return Err(McpError::invalid_params(
                format!("invalid run_id: {run_id:?}"),
                None,
            ));
        }
        let dir = workspace.join(".solomd").join("agent-runs").join(&run_id);
        let steps = tokio::task::spawn_blocking(move || trace_reader::read_trace(&dir))
            .await
            .map_err(|e| McpError::internal_error(format!("join: {e}"), None))?
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;
        let count = steps.len();
        Ok(CallToolResult::success(vec![Content::json(
            serde_json::json!({ "steps": steps, "count": count }),
        )
        .map_err(|e| McpError::internal_error(e.to_string(), None))?]))
    }
}

// ---------------------------------------------------------------------------
// ServerHandler
// ---------------------------------------------------------------------------

#[tool_handler(router = self.tool_router)]
impl ServerHandler for SoloMdServer {
    fn get_info(&self) -> ServerInfo {
        let implementation =
            Implementation::new("solomd-mcp", env!("CARGO_PKG_VERSION")).with_title("SoloMD Vault");
        let aliases: Vec<&str> = self
            .inner
            .workspaces
            .iter()
            .map(|(a, _)| a.as_str())
            .collect();
        let workspace_blurb = if aliases.len() == 1 {
            format!("Single workspace registered: {}.", aliases[0])
        } else {
            format!(
                "Multiple workspaces registered: [{}]. The first ({}) is the default; pass `workspace: \"<alias>\"` (or an absolute path) to target a different one.",
                aliases.join(", "),
                aliases[0]
            )
        };
        ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
            .with_server_info(implementation)
            .with_instructions(format!(
                "Read and (optionally) write SoloMD Markdown notes vaults. \
                 Tools are read-only by default; restart with --allow-write to expose \
                 write_note + append_to_note + autogit_rollback. {workspace_blurb}"
            ))
    }
}

// ---------------------------------------------------------------------------
// Search backends
// ---------------------------------------------------------------------------

async fn has_rg() -> bool {
    AsyncCommand::new("rg")
        .arg("--version")
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .await
        .map(|s| s.success())
        .unwrap_or(false)
}

async fn search_with_rg(
    root: &std::path::Path,
    query: &str,
    regex: bool,
    limit: usize,
) -> Result<Vec<SearchHit>, String> {
    let mut cmd = AsyncCommand::new("rg");
    cmd.arg("--json")
        .arg("--with-filename")
        .arg("--line-number")
        .arg("--column")
        .arg("--no-heading")
        .arg("--max-count")
        .arg(limit.to_string())
        .arg("--type-add")
        .arg("md:*.md")
        .arg("--type-add")
        .arg("md:*.markdown")
        .arg("--type-add")
        .arg("md:*.mdown")
        .arg("--type")
        .arg("md");
    if !regex {
        cmd.arg("--fixed-strings");
    }
    cmd.arg("--").arg(query).arg(root);
    let output = cmd
        .output()
        .await
        .map_err(|e| format!("rg failed to start: {e}"))?;
    if !output.status.success() && !output.status.code().map(|c| c == 1).unwrap_or(false) {
        // exit 1 == no matches; otherwise it's an error.
        return Err(format!(
            "rg exited with {:?}: {}",
            output.status.code(),
            String::from_utf8_lossy(&output.stderr)
        ));
    }
    let mut hits: Vec<SearchHit> = Vec::new();
    for line in output.stdout.split(|b| *b == b'\n') {
        if line.is_empty() {
            continue;
        }
        let v: serde_json::Value = match serde_json::from_slice(line) {
            Ok(v) => v,
            Err(_) => continue,
        };
        if v.get("type").and_then(|t| t.as_str()) != Some("match") {
            continue;
        }
        let data = match v.get("data") {
            Some(d) => d,
            None => continue,
        };
        let path = data
            .pointer("/path/text")
            .and_then(|s| s.as_str())
            .unwrap_or("")
            .to_string();
        let line_no = data
            .get("line_number")
            .and_then(|n| n.as_u64())
            .unwrap_or(0) as u32;
        let column = data
            .pointer("/submatches/0/start")
            .and_then(|n| n.as_u64())
            .unwrap_or(0) as u32
            + 1;
        let snippet = workspace::read_context(std::path::Path::new(&path), line_no);
        hits.push(SearchHit {
            path,
            line: line_no,
            column,
            snippet,
        });
        if hits.len() >= limit {
            break;
        }
    }
    Ok(hits)
}

fn search_native(
    root: &std::path::Path,
    query: &str,
    regex: bool,
    limit: usize,
) -> Result<Vec<SearchHit>, String> {
    let pattern = if regex {
        Some(regex_lite::Regex::new(query).map_err(|e| format!("invalid regex: {e}"))?)
    } else {
        None
    };
    let needle_lower = query.to_lowercase();
    let mut hits: Vec<SearchHit> = Vec::new();
    'outer: for path in workspace::walk_markdown_files(root) {
        let raw = match std::fs::read_to_string(&path) {
            Ok(r) => r,
            Err(_) => continue,
        };
        for (line_idx, line) in raw.lines().enumerate() {
            let col = if let Some(re) = &pattern {
                re.find(line).map(|m| m.start() + 1)
            } else {
                line.to_lowercase().find(&needle_lower).map(|c| c + 1)
            };
            if let Some(column) = col {
                hits.push(SearchHit {
                    path: path.to_string_lossy().to_string(),
                    line: (line_idx as u32) + 1,
                    column: column as u32,
                    snippet: workspace::read_context(&path, (line_idx as u32) + 1),
                });
                if hits.len() >= limit {
                    break 'outer;
                }
            }
        }
    }
    Ok(hits)
}

// ---------------------------------------------------------------------------
// v3.1 inner helpers — git2 / sync.json / share URL
// ---------------------------------------------------------------------------

fn autogit_log_inner(
    workspace: &std::path::Path,
    note_path: &std::path::Path,
    limit: usize,
) -> Result<Vec<AutogitCommitMeta>, String> {
    let repo =
        git2::Repository::open(workspace).map_err(|e| format!("not an AutoGit workspace: {e}"))?;
    let rel = note_path
        .strip_prefix(workspace)
        .map_err(|_| "note is outside the workspace".to_string())?;
    let mut walker = repo.revwalk().map_err(|e| e.to_string())?;
    walker.push_head().map_err(|e| e.to_string())?;

    let mut out: Vec<AutogitCommitMeta> = Vec::new();
    for oid in walker.flatten() {
        let commit = match repo.find_commit(oid) {
            Ok(c) => c,
            Err(_) => continue,
        };
        if !commit_touches(&repo, &commit, rel).unwrap_or(false) {
            continue;
        }
        let summary = commit.summary().unwrap_or("").to_string();
        let name = commit.author().name().unwrap_or("").to_string();
        out.push(AutogitCommitMeta {
            sha: commit.id().to_string(),
            short_sha: commit.id().to_string().chars().take(7).collect(),
            author: name,
            time: commit.time().seconds(),
            summary,
        });
    }
    // Sort newest-first by author time. Doing it in Rust dodges git2's
    // sorting modes — Sort::TIME is ascending, REVERSE is non-obvious,
    // and the resulting filter+visit order is fragile across history
    // shapes. A plain sort_by here is unambiguous.
    out.sort_by(|a, b| b.time.cmp(&a.time));
    out.truncate(limit);
    Ok(out)
}

fn commit_touches(
    repo: &git2::Repository,
    commit: &git2::Commit,
    rel: &std::path::Path,
) -> Result<bool, git2::Error> {
    let tree = commit.tree()?;
    let parent_tree = if commit.parent_count() > 0 {
        Some(commit.parent(0)?.tree()?)
    } else {
        None
    };
    let diff = repo.diff_tree_to_tree(parent_tree.as_ref(), Some(&tree), None)?;
    let mut hit = false;
    diff.foreach(
        &mut |delta, _| {
            if delta
                .new_file()
                .path()
                .or_else(|| delta.old_file().path())
                .map(|p| p == rel)
                .unwrap_or(false)
            {
                hit = true;
            }
            true
        },
        None,
        None,
        None,
    )?;
    Ok(hit)
}

fn autogit_diff_inner(
    workspace: &std::path::Path,
    note_path: &std::path::Path,
    sha: Option<&str>,
    base: Option<&str>,
) -> Result<serde_json::Value, String> {
    let repo =
        git2::Repository::open(workspace).map_err(|e| format!("not an AutoGit workspace: {e}"))?;
    let rel = note_path
        .strip_prefix(workspace)
        .map_err(|_| "note is outside the workspace".to_string())?;

    let new_oid = match sha {
        Some(s) => repo
            .revparse_single(s)
            .map_err(|e| format!("resolve {s}: {e}"))?
            .id(),
        None => {
            // Default: the most recent commit that actually touched this
            // path. Plain HEAD-vs-parent is misleading when HEAD only
            // changed *other* files — the diff would be empty even though
            // there's plenty of history for the requested path.
            let mut walker = repo.revwalk().map_err(|e| e.to_string())?;
            walker.push_head().map_err(|e| e.to_string())?;
            // Collect every commit that touches the path, then pick the
            // newest by author time. (Don't rely on revwalk sort modes.)
            let mut candidates: Vec<(git2::Oid, i64)> = Vec::new();
            for oid in walker.flatten() {
                if let Ok(c) = repo.find_commit(oid) {
                    if commit_touches(&repo, &c, rel).unwrap_or(false) {
                        candidates.push((oid, c.time().seconds()));
                    }
                }
            }
            candidates.sort_by(|a, b| b.1.cmp(&a.1));
            candidates
                .into_iter()
                .next()
                .map(|(oid, _)| oid)
                .ok_or_else(|| format!("no commit in this repo has touched '{}'", rel.display()))?
        }
    };
    let new_commit = repo.find_commit(new_oid).map_err(|e| e.to_string())?;
    let new_tree = new_commit.tree().map_err(|e| e.to_string())?;

    let base_commit = match base {
        Some(s) => Some(
            repo.revparse_single(s)
                .map_err(|e| format!("resolve {s}: {e}"))?
                .peel_to_commit()
                .map_err(|e| e.to_string())?,
        ),
        None => {
            if new_commit.parent_count() > 0 {
                Some(new_commit.parent(0).map_err(|e| e.to_string())?)
            } else {
                None
            }
        }
    };
    let base_tree = match &base_commit {
        Some(c) => Some(c.tree().map_err(|e| e.to_string())?),
        None => None,
    };

    let mut diff_opts = git2::DiffOptions::new();
    diff_opts.pathspec(rel.to_string_lossy().as_ref());
    let diff = repo
        .diff_tree_to_tree(base_tree.as_ref(), Some(&new_tree), Some(&mut diff_opts))
        .map_err(|e| e.to_string())?;

    let mut out = String::new();
    diff.print(git2::DiffFormat::Patch, |_d, _h, line| {
        let origin = line.origin();
        if origin == '+' || origin == '-' || origin == ' ' {
            out.push(origin);
        }
        out.push_str(std::str::from_utf8(line.content()).unwrap_or(""));
        true
    })
    .map_err(|e| e.to_string())?;

    Ok(serde_json::json!({
        "sha": new_oid.to_string(),
        "base": base_commit.as_ref().map(|c| c.id().to_string()),
        "diff": out,
        "path": rel.to_string_lossy(),
    }))
}

fn autogit_rollback_inner(
    workspace: &std::path::Path,
    note_path: &std::path::Path,
    sha: &str,
) -> Result<usize, String> {
    let repo =
        git2::Repository::open(workspace).map_err(|e| format!("not an AutoGit workspace: {e}"))?;
    let rel = note_path
        .strip_prefix(workspace)
        .map_err(|_| "note is outside the workspace".to_string())?;
    let object = repo
        .revparse_single(sha)
        .map_err(|e| format!("resolve {sha}: {e}"))?;
    let commit = object
        .peel_to_commit()
        .map_err(|e| format!("not a commit: {e}"))?;
    let tree = commit.tree().map_err(|e| e.to_string())?;
    let entry = tree
        .get_path(rel)
        .map_err(|_| format!("file '{}' not in commit {}", rel.display(), sha))?;
    let blob = repo
        .find_blob(entry.id())
        .map_err(|e| format!("blob: {e}"))?;
    let bytes = blob.content().to_vec();
    let n = bytes.len();
    std::fs::write(note_path, bytes).map_err(|e| format!("write: {e}"))?;
    Ok(n)
}

fn sync_status_inner(workspace: &std::path::Path) -> Result<serde_json::Value, String> {
    let cfg_path = workspace.join(".solomd").join("sync.json");
    if !cfg_path.exists() {
        return Ok(serde_json::json!({
            "linked": false,
            "remote_url": null,
            "encrypted": false,
        }));
    }
    let raw = std::fs::read_to_string(&cfg_path).map_err(|e| e.to_string())?;
    // Refuse to invent state if the config is corrupted — same fail-closed
    // posture as the desktop app's github_push_inner / github_pull_inner.
    let mut value: serde_json::Value =
        serde_json::from_str(&raw).map_err(|e| format!("sync.json corrupted: {e}"))?;
    if let Some(obj) = value.as_object_mut() {
        obj.insert("linked".into(), serde_json::Value::Bool(true));
    }
    Ok(value)
}

fn share_url_inner(
    workspace: &std::path::Path,
    note_path: &std::path::Path,
) -> Result<serde_json::Value, String> {
    let cfg_path = workspace.join(".solomd").join("sync.json");
    if !cfg_path.exists() {
        return Err("workspace is not linked to a GitHub repo".into());
    }
    let raw = std::fs::read_to_string(&cfg_path).map_err(|e| e.to_string())?;
    let cfg: serde_json::Value =
        serde_json::from_str(&raw).map_err(|e| format!("sync.json corrupted: {e}"))?;
    let remote = cfg
        .get("remote_url")
        .and_then(|v| v.as_str())
        .ok_or_else(|| "remote_url missing in sync.json".to_string())?;
    // Accept both https://github.com/<owner>/<repo>.git and the bare form.
    let owner_repo =
        parse_owner_repo(remote).ok_or_else(|| format!("not a GitHub remote: {remote}"))?;
    let branch = cfg
        .get("branch")
        .and_then(|v| v.as_str())
        .unwrap_or("main")
        .to_string();
    let rel = note_path
        .strip_prefix(workspace)
        .map_err(|_| "note is outside the workspace".to_string())?;
    let rel_str = rel.to_string_lossy().replace('\\', "/");
    let url = format!(
        "https://solomd.app/share/?repo={}&path={}&branch={}",
        urlencode(&owner_repo),
        urlencode(&rel_str),
        urlencode(&branch),
    );
    Ok(serde_json::json!({
        "url": url,
        "repo": owner_repo,
        "branch": branch,
        "path": rel_str,
        "warning": "Public share only renders if the linked repo is public. Use sync_status if unsure.",
    }))
}

fn parse_owner_repo(remote: &str) -> Option<String> {
    let trimmed = remote.trim().trim_end_matches('/').trim_end_matches(".git");
    let after = trimmed
        .split("github.com")
        .nth(1)?
        .trim_start_matches([':', '/']);
    let parts: Vec<&str> = after.split('/').filter(|s| !s.is_empty()).collect();
    if parts.len() >= 2 {
        Some(format!("{}/{}", parts[0], parts[1]))
    } else {
        None
    }
}

fn urlencode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for byte in s.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
                out.push(byte as char);
            }
            _ => out.push_str(&format!("%{:02X}", byte)),
        }
    }
    out
}

// ---------------------------------------------------------------------------
// v3.1 unit tests for SoloMD-only inner helpers.
//
// These don't go through the MCP protocol layer — they call the inner
// functions directly so we can pin down behavior (fail-closed on bad
// sync.json, smart default for autogit_diff, branch-with-slash for share
// URL, etc.) without spinning up the JSON-RPC server.
// ---------------------------------------------------------------------------

/// Locate `app/scripts/solomd-export.mjs`, the Node tool that backs the
/// `export_note` MCP tool and the `solomd export` CLI subcommand.
///
/// Search order:
///   1. `$SOLOMD_EXPORT_SCRIPT` env var (explicit override).
///   2. `<exe-dir>/../app/scripts/solomd-export.mjs` (running from the
///      SoloMD repo's release build, e.g. `mcp-server/target/release/`).
///   3. `<exe-dir>/../../app/scripts/solomd-export.mjs` (running from a
///      monorepo dev build).
///   4. `<cwd>/app/scripts/solomd-export.mjs` (running from repo root).
///   5. `~/.solomd/solomd-export.mjs` (manually installed).
fn find_export_script() -> Result<PathBuf, String> {
    if let Ok(p) = std::env::var("SOLOMD_EXPORT_SCRIPT") {
        let pb = PathBuf::from(p);
        if pb.is_file() {
            return Ok(pb);
        }
    }
    let exe = std::env::current_exe().ok();
    let mut candidates: Vec<PathBuf> = Vec::new();
    if let Some(exe) = exe {
        if let Some(parent) = exe.parent() {
            candidates.push(parent.join("../app/scripts/solomd-export.mjs"));
            candidates.push(parent.join("../../app/scripts/solomd-export.mjs"));
        }
    }
    if let Ok(cwd) = std::env::current_dir() {
        candidates.push(cwd.join("app/scripts/solomd-export.mjs"));
        candidates.push(cwd.join("../app/scripts/solomd-export.mjs"));
    }
    if let Some(home) = std::env::var_os("HOME") {
        candidates.push(PathBuf::from(home).join(".solomd/solomd-export.mjs"));
    }
    for c in &candidates {
        if c.is_file() {
            return c.canonicalize().map_err(|e| e.to_string());
        }
    }
    Err(format!(
        "tried {} candidate paths; set SOLOMD_EXPORT_SCRIPT to point at app/scripts/solomd-export.mjs",
        candidates.len()
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::path::PathBuf;
    use std::process::Command;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn fresh_repo(label: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let dir = std::env::temp_dir().join(format!("solomd-mcp-{label}-{nanos}"));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        // git init + identity (avoid test depending on user's git config)
        Command::new("git")
            .args(["init", "-q", "-b", "main"])
            .current_dir(&dir)
            .status()
            .unwrap();
        Command::new("git")
            .args(["config", "user.email", "test@local"])
            .current_dir(&dir)
            .status()
            .unwrap();
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(&dir)
            .status()
            .unwrap();
        dir
    }

    fn commit(repo: &std::path::Path, path: &str, body: &str, msg: &str) {
        let full = repo.join(path);
        if let Some(parent) = full.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(&full, body).unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(repo)
            .status()
            .unwrap();
        Command::new("git")
            .args(["commit", "-q", "-m", msg])
            .current_dir(repo)
            .status()
            .unwrap();
    }

    #[test]
    fn autogit_log_returns_only_commits_touching_path_newest_first() {
        let repo = fresh_repo("log");
        commit(&repo, "notes/foo.md", "v1\n", "initial: foo");
        // Sleep 1s so author times differ deterministically.
        std::thread::sleep(std::time::Duration::from_secs(1));
        commit(
            &repo,
            "notes/bar.md",
            "bar\n",
            "add: bar (does not touch foo)",
        );
        std::thread::sleep(std::time::Duration::from_secs(1));
        commit(&repo, "notes/foo.md", "v2\n", "edit: foo round 2");

        let foo = repo.join("notes/foo.md");
        let log = autogit_log_inner(&repo, &foo, 50).unwrap();
        assert_eq!(log.len(), 2, "should skip the bar-only commit");
        assert_eq!(log[0].summary, "edit: foo round 2", "newest first");
        assert_eq!(log[1].summary, "initial: foo");
        assert!(log[0].time >= log[1].time);
    }

    #[test]
    fn autogit_diff_default_picks_most_recent_commit_touching_path() {
        let repo = fresh_repo("diff");
        commit(&repo, "notes/foo.md", "v1\n", "initial: foo");
        std::thread::sleep(std::time::Duration::from_secs(1));
        commit(&repo, "notes/foo.md", "v2\n", "edit: foo round 2");
        std::thread::sleep(std::time::Duration::from_secs(1));
        // HEAD doesn't touch foo — naive HEAD-vs-parent would diff empty.
        commit(&repo, "notes/bar.md", "bar\n", "add: bar (HEAD)");

        let foo = repo.join("notes/foo.md");
        let result = autogit_diff_inner(&repo, &foo, None, None).unwrap();
        let diff = result.get("diff").unwrap().as_str().unwrap();
        assert!(
            diff.contains("-v1"),
            "expected the foo edit diff, got: {diff}"
        );
        assert!(
            diff.contains("+v2"),
            "expected the foo edit diff, got: {diff}"
        );
    }

    #[test]
    fn autogit_rollback_overwrites_working_tree() {
        let repo = fresh_repo("roll");
        commit(&repo, "notes/foo.md", "first\n", "initial");
        let initial_sha = String::from_utf8(
            Command::new("git")
                .args(["rev-parse", "HEAD"])
                .current_dir(&repo)
                .output()
                .unwrap()
                .stdout,
        )
        .unwrap()
        .trim()
        .to_string();
        commit(&repo, "notes/foo.md", "second\n", "round 2");

        let foo = repo.join("notes/foo.md");
        assert_eq!(fs::read_to_string(&foo).unwrap(), "second\n");
        let written = autogit_rollback_inner(&repo, &foo, &initial_sha).unwrap();
        assert_eq!(written, 6); // "first\n"
        assert_eq!(fs::read_to_string(&foo).unwrap(), "first\n");
    }

    #[test]
    fn sync_status_no_config_means_unlinked() {
        let repo = fresh_repo("st1");
        let v = sync_status_inner(&repo).unwrap();
        assert_eq!(v.get("linked").and_then(|x| x.as_bool()), Some(false));
    }

    #[test]
    fn sync_status_corrupted_json_fails_closed() {
        let repo = fresh_repo("st2");
        fs::create_dir_all(repo.join(".solomd")).unwrap();
        fs::write(repo.join(".solomd/sync.json"), b"{not valid json").unwrap();
        let err = sync_status_inner(&repo).unwrap_err();
        // Same posture as desktop github_push_inner: refuse to invent state.
        assert!(err.contains("corrupted"), "got: {err}");
    }

    #[test]
    fn sync_status_happy_path() {
        let repo = fresh_repo("st3");
        fs::create_dir_all(repo.join(".solomd")).unwrap();
        fs::write(
            repo.join(".solomd/sync.json"),
            br#"{"remote_url":"https://github.com/me/notes.git","branch":"main","encrypted":true}"#,
        )
        .unwrap();
        let v = sync_status_inner(&repo).unwrap();
        assert_eq!(v.get("linked").and_then(|x| x.as_bool()), Some(true));
        assert_eq!(v.get("encrypted").and_then(|x| x.as_bool()), Some(true));
        assert_eq!(v.get("branch").and_then(|x| x.as_str()), Some("main"));
    }

    #[test]
    fn share_url_handles_branch_with_slash() {
        let repo = fresh_repo("share");
        fs::create_dir_all(repo.join(".solomd")).unwrap();
        // Branch name contains '/' — used to be the share-page bug.
        fs::write(
            repo.join(".solomd/sync.json"),
            br#"{"remote_url":"https://github.com/owner/repo.git","branch":"feature/foo"}"#,
        )
        .unwrap();
        let note = repo.join("notes/a.md");
        fs::create_dir_all(note.parent().unwrap()).unwrap();
        fs::write(&note, b"# A").unwrap();

        let v = share_url_inner(&repo, &note).unwrap();
        let url = v.get("url").unwrap().as_str().unwrap();
        // The slash in feature/foo must survive — encodeURIComponent on the
        // whole branch would turn it into %2F and 404 the share page.
        assert!(url.contains("branch=feature/foo"), "url={url}");
        assert!(url.contains("repo=owner/repo"));
        assert!(url.contains("path=notes/a.md"));
    }

    #[test]
    fn parse_owner_repo_handles_https_ssh_with_or_without_dot_git() {
        assert_eq!(
            parse_owner_repo("https://github.com/owner/repo.git"),
            Some("owner/repo".into())
        );
        assert_eq!(
            parse_owner_repo("https://github.com/owner/repo"),
            Some("owner/repo".into())
        );
        assert_eq!(
            parse_owner_repo("git@github.com:owner/repo.git"),
            Some("owner/repo".into())
        );
        assert_eq!(parse_owner_repo("https://gitlab.com/owner/repo.git"), None);
    }

    #[test]
    fn share_url_refuses_when_workspace_not_linked() {
        let repo = fresh_repo("nolink");
        let note = repo.join("notes/a.md");
        fs::create_dir_all(note.parent().unwrap()).unwrap();
        fs::write(&note, b"# A").unwrap();
        let err = share_url_inner(&repo, &note).unwrap_err();
        assert!(err.contains("not linked"), "got: {err}");
    }

    // ----- v4.0 federation: SoloMdServer::resolve_workspace ----------------

    fn fresh_dir(label: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let dir = std::env::temp_dir().join(format!("solomd-mcp-rw-{label}-{nanos}"));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn resolve_workspace_none_returns_default() {
        let a = fresh_dir("rw-default-a").canonicalize().unwrap();
        let b = fresh_dir("rw-default-b").canonicalize().unwrap();
        let server = SoloMdServer::new(
            vec![("first".into(), a.clone()), ("second".into(), b.clone())],
            false,
        );
        // None falls through to the first registered workspace — back-compat
        // with single-workspace clients.
        assert_eq!(server.resolve_workspace(None).unwrap(), a.as_path());
        // Empty string is treated the same as None (defensive).
        assert_eq!(server.resolve_workspace(Some("")).unwrap(), a.as_path());
    }

    #[test]
    fn resolve_workspace_alias_match() {
        let a = fresh_dir("rw-alias-a").canonicalize().unwrap();
        let b = fresh_dir("rw-alias-b").canonicalize().unwrap();
        let server = SoloMdServer::new(
            vec![("notes".into(), a.clone()), ("scratch".into(), b.clone())],
            false,
        );
        assert_eq!(
            server.resolve_workspace(Some("notes")).unwrap(),
            a.as_path()
        );
        assert_eq!(
            server.resolve_workspace(Some("scratch")).unwrap(),
            b.as_path()
        );
    }

    #[test]
    fn resolve_workspace_absolute_path_match() {
        let a = fresh_dir("rw-abs-a").canonicalize().unwrap();
        let server = SoloMdServer::new(vec![("only".into(), a.clone())], false);
        let s = a.to_string_lossy().to_string();
        let resolved = server.resolve_workspace(Some(&s)).unwrap();
        assert_eq!(resolved, a.as_path());
    }

    #[test]
    fn resolve_workspace_unknown_alias_errors_with_available_list() {
        let a = fresh_dir("rw-unknown-a").canonicalize().unwrap();
        let server = SoloMdServer::new(vec![("home".into(), a.clone())], false);
        let err = server.resolve_workspace(Some("bogus")).unwrap_err();
        assert!(err.contains("unknown workspace: bogus"), "got: {err}");
        assert!(
            err.contains("home"),
            "error should list available aliases, got: {err}"
        );
    }

    #[test]
    fn resolve_workspace_unregistered_absolute_path_errors() {
        let a = fresh_dir("rw-bad-abs").canonicalize().unwrap();
        let server = SoloMdServer::new(vec![("only".into(), a.clone())], false);
        // /tmp itself is not a registered workspace — must reject even though
        // it canonicalises fine.
        let err = server.resolve_workspace(Some("/tmp")).unwrap_err();
        assert!(err.contains("unknown workspace"), "got: {err}");
    }

    #[test]
    fn resolve_workspace_single_workspace_back_compat() {
        // Exactly the legacy case: one workspace, no alias arg ever passed.
        // This is what every existing single-`--workspace` client does.
        let a = fresh_dir("rw-legacy").canonicalize().unwrap();
        let server = SoloMdServer::new(vec![("legacy".into(), a.clone())], false);
        assert_eq!(server.resolve_workspace(None).unwrap(), a.as_path());
        // And the alias still works if a curious client sends one.
        assert_eq!(
            server.resolve_workspace(Some("legacy")).unwrap(),
            a.as_path()
        );
    }
}