mcp-methods 0.3.32

Reusable utility methods for MCP servers — pure-Rust library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
//! YAML manifest schema + loader.
//!
//! A manifest is a YAML file declaring the tools, source roots, custom
//! embedder, and trust gates the server should apply. The loader parses,
//! validates, and returns a [`Manifest`]; consumers (CLI wiring, tool
//! registration) operate on the validated structure.
//!
//! Path strings (`source_root`, `python:` tool paths, embedder module)
//! are kept as the raw user input — relative-to-yaml resolution happens
//! at the use site so the data stays pure and testable.
//!
//! Validation is fail-fast and user-facing: the caller surfaces
//! [`ManifestError`] messages directly to the operator.
//!
//! Schema mirrors the Python `kglite.mcp_server.manifest` module 1:1 so
//! a manifest written for the Python server boots unchanged on the new
//! Rust server.

// A handful of fields/helpers are exposed for downstream consumers
// (e.g. kglite-mcp-server reads `CypherTool::cypher` directly when
// registering manifest-declared tools) and so look unused from this
// crate's perspective. Silence dead-code warnings rather than chase
// every cross-crate use.
#![allow(dead_code)]

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

use serde::Deserialize;
use thiserror::Error;

const ALLOWED_TOP_KEYS: &[&str] = &[
    "name",
    "instructions",
    "overview_prefix",
    "source_root",
    "source_roots",
    "trust",
    "tools",
    "embedder",
    "builtins",
    "env_file",
    "workspace",
    "extensions",
];
const ALLOWED_WORKSPACE_KEYS: &[&str] = &["kind", "root", "watch", "applies_to"];
const VALID_WORKSPACE_KIND: &[&str] = &["github", "local"];
const ALLOWED_TRUST_KEYS: &[&str] = &[
    "allow_python_tools",
    "allow_embedder",
    "allow_query_preprocessor",
];
const ALLOWED_TOOL_KEYS: &[&str] = &[
    "name",
    "description",
    "parameters",
    "cypher",
    "python",
    "function",
    "bundled",
    "hidden",
];
const ALLOWED_EMBEDDER_KEYS: &[&str] = &["module", "class", "kwargs"];
const ALLOWED_BUILTIN_KEYS: &[&str] = &["save_graph", "temp_cleanup"];
const VALID_TEMP_CLEANUP: &[&str] = &["never", "on_overview"];

#[derive(Debug, Error)]
#[error("{path}: {message}")]
pub struct ManifestError {
    pub path: String,
    pub message: String,
}

impl ManifestError {
    pub fn at(path: &Path, message: impl Into<String>) -> Self {
        Self {
            path: path.display().to_string(),
            message: message.into(),
        }
    }

    pub fn bare(message: impl Into<String>) -> Self {
        Self {
            path: "<manifest>".to_string(),
            message: message.into(),
        }
    }
}

#[derive(Debug, Default, Clone)]
pub struct TrustConfig {
    pub allow_python_tools: bool,
    pub allow_embedder: bool,
    /// Advisory gate: the manifest declares that an extension-defined
    /// query preprocessor hook is permitted to run. The framework does
    /// not parse or execute the preprocessor itself — it lives in the
    /// opaque `extensions:` passthrough — but downstream consumers
    /// (e.g. kglite-mcp-server) read this flag and refuse to boot the
    /// hook when it is false. Same pattern as `allow_embedder`.
    pub allow_query_preprocessor: bool,
}

#[derive(Debug, Clone)]
pub enum ToolSpec {
    Cypher(CypherTool),
    Python(PythonTool),
    /// Override the agent-facing surface of a bundled tool (one the
    /// downstream binary provides natively — `cypher_query`,
    /// `graph_overview`, `read_source`, etc.). The framework parses
    /// the override but does not enforce that the named tool exists;
    /// the downstream consumer (e.g. `kglite-mcp-server`) is
    /// responsible for validating the name against its bundled
    /// catalogue at boot time and applying the override when
    /// emitting `tools/list`.
    ///
    /// Pre-0.3.31 the only customisation path for the bundled tool
    /// surface was the manifest's global `instructions:` block —
    /// useful for first-message orientation but not attached to
    /// individual tools. Bundled overrides let operators rewrite a
    /// specific tool's `description` (what the agent sees in
    /// `tools/list`) or `hidden`-flag it out entirely.
    Bundled(BundledOverride),
}

impl ToolSpec {
    pub fn name(&self) -> &str {
        match self {
            ToolSpec::Cypher(t) => &t.name,
            ToolSpec::Python(t) => &t.name,
            ToolSpec::Bundled(t) => &t.name,
        }
    }
}

#[derive(Debug, Clone)]
pub struct CypherTool {
    pub name: String,
    pub cypher: String,
    pub description: Option<String>,
    pub parameters: Option<serde_json::Value>,
}

#[derive(Debug, Clone)]
pub struct PythonTool {
    pub name: String,
    pub python: String,
    pub function: String,
    pub description: Option<String>,
    pub parameters: Option<serde_json::Value>,
}

#[derive(Debug, Clone)]
pub struct BundledOverride {
    /// Name of the bundled tool to override (e.g. `cypher_query`,
    /// `repo_management`). Validation against the downstream
    /// binary's actual catalogue happens at the consumer's boot
    /// time — the framework only checks shape here.
    pub name: String,
    /// New agent-facing description that replaces the bundled
    /// tool's default. `None` means "do not override; keep the
    /// default."
    pub description: Option<String>,
    /// When true, the downstream consumer should omit this tool
    /// from `tools/list` AND reject calls to it. Defaults to
    /// false (visible).
    pub hidden: bool,
}

#[derive(Debug, Clone)]
pub struct EmbedderConfig {
    pub module: String,
    pub class: String,
    pub kwargs: serde_json::Map<String, serde_json::Value>,
}

#[derive(Debug, Default, Clone)]
pub struct BuiltinsConfig {
    pub save_graph: bool,
    pub temp_cleanup: TempCleanup,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum TempCleanup {
    #[default]
    Never,
    OnOverview,
}

impl TempCleanup {
    pub fn as_str(&self) -> &'static str {
        match self {
            TempCleanup::Never => "never",
            TempCleanup::OnOverview => "on_overview",
        }
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum WorkspaceKind {
    /// Clone-and-track GitHub repos. The default when no `workspace:`
    /// block is set and the operator passed `--workspace DIR`.
    #[default]
    Github,
    /// Bind a fixed local directory as the active source root. No
    /// cloning happens; `set_root_dir(path)` swaps the active root.
    Local,
}

impl WorkspaceKind {
    pub fn as_str(&self) -> &'static str {
        match self {
            WorkspaceKind::Github => "github",
            WorkspaceKind::Local => "local",
        }
    }
}

#[derive(Debug, Clone, Default)]
pub struct WorkspaceConfig {
    pub kind: WorkspaceKind,
    /// Local-mode only: path to the directory to bind as the source
    /// root. Relative paths resolve against the YAML's parent dir.
    pub root: Option<String>,
    /// Local-mode only: wire the framework's file watcher to `root`
    /// (debounced rebuild trigger via the post-activate hook).
    pub watch: bool,
    /// Optional opt-in for the [`find_workspace_manifest`] parent-walk
    /// fallback. When set, this manifest is auto-discovered by
    /// ``mcp-server --workspace DIR`` (and similar callers) only when
    /// ``DIR`` canonicalises to ``applies_to`` resolved against the
    /// manifest's parent directory. When unset, the parent-walk
    /// fallback NEVER fires for this manifest — operators must pass
    /// ``--mcp-config`` explicitly.
    ///
    /// Eliminates the accidental-discovery footgun where a workspace
    /// manifest is auto-picked-up by an unrelated sibling dir. The
    /// manifest's own declaration is the opt-in.
    pub applies_to: Option<String>,
}

#[derive(Debug, Clone)]
pub struct Manifest {
    pub yaml_path: PathBuf,
    pub name: Option<String>,
    pub instructions: Option<String>,
    pub overview_prefix: Option<String>,
    pub source_roots: Vec<String>,
    pub trust: TrustConfig,
    pub tools: Vec<ToolSpec>,
    pub embedder: Option<EmbedderConfig>,
    pub builtins: BuiltinsConfig,
    /// Optional explicit `.env` path (relative to the YAML or absolute).
    /// When unset, the runtime walks upward from the start directory
    /// looking for a `.env` file.
    pub env_file: Option<String>,
    /// Optional explicit workspace declaration. When set, this wins
    /// over CLI `--workspace`/`--source-root` flags interpretation
    /// (manifest is the source of truth — same rule as `source_root:`).
    pub workspace: Option<WorkspaceConfig>,
    /// Raw passthrough for downstream-binary-specific manifest keys.
    /// The framework accepts any mapping under `extensions:` and stores
    /// it here without validating the inner keys; downstream consumers
    /// (e.g. kglite-mcp-server) read whatever they need from this map.
    ///
    /// This keeps the framework's strict-unknown-key validation strong
    /// for the surfaces it owns (`builtins`, `workspace`, …) while
    /// letting consumers add their own configuration namespace without
    /// per-key framework round-trips.
    pub extensions: serde_json::Map<String, serde_json::Value>,
}

impl Manifest {
    /// JSON-friendly representation of the validated manifest for
    /// FFI / RPC exposure (pyo3 wrappers, JSON-RPC bridges, etc.).
    ///
    /// The shape is stable across patch releases: fields can be added
    /// non-breaking, but key renames or removals are breaking changes.
    /// When adding a new field to `Manifest`, extend this method too —
    /// the `to_json_shape_is_stable` test will fail until you do.
    /// The `extensions` map is passed through unchanged; downstream
    /// consumers parse their own namespace from it.
    pub fn to_json(&self) -> serde_json::Value {
        serde_json::json!({
            "yaml_path": self.yaml_path.display().to_string(),
            "name": self.name,
            "instructions": self.instructions,
            "overview_prefix": self.overview_prefix,
            "source_roots": self.source_roots,
            "trust": {
                "allow_python_tools": self.trust.allow_python_tools,
                "allow_embedder": self.trust.allow_embedder,
                "allow_query_preprocessor": self.trust.allow_query_preprocessor,
            },
            "tools": self.tools.iter().map(|t| match t {
                ToolSpec::Cypher(c) => serde_json::json!({
                    "kind": "cypher",
                    "name": c.name,
                    "cypher": c.cypher,
                    "description": c.description,
                    "parameters": c.parameters,
                }),
                ToolSpec::Python(p) => serde_json::json!({
                    "kind": "python",
                    "name": p.name,
                    "python": p.python,
                    "function": p.function,
                    "description": p.description,
                    "parameters": p.parameters,
                }),
                ToolSpec::Bundled(b) => serde_json::json!({
                    "kind": "bundled",
                    "name": b.name,
                    "description": b.description,
                    "hidden": b.hidden,
                }),
            }).collect::<Vec<_>>(),
            "embedder": self.embedder.as_ref().map(|e| serde_json::json!({
                "module": e.module,
                "class": e.class,
                "kwargs": e.kwargs,
            })),
            "builtins": {
                "save_graph": self.builtins.save_graph,
                "temp_cleanup": self.builtins.temp_cleanup.as_str(),
            },
            "env_file": self.env_file,
            "workspace": self.workspace.as_ref().map(|w| serde_json::json!({
                "kind": w.kind.as_str(),
                "root": w.root,
                "watch": w.watch,
                "applies_to": w.applies_to,
            })),
            "extensions": self.extensions,
        })
    }
}

/// Auto-detect ``<basename>_mcp.yaml`` next to a graph file.
pub fn find_sibling_manifest(graph_path: &Path) -> Option<PathBuf> {
    let stem = graph_path.file_stem()?;
    let parent = graph_path.parent()?;
    let candidate = parent.join(format!("{}_mcp.yaml", stem.to_string_lossy()));
    if candidate.is_file() {
        Some(candidate)
    } else {
        None
    }
}

/// Auto-detect ``workspace_mcp.yaml`` for a workspace directory.
///
/// Checks two locations in strict priority order:
///
/// 1. **Primary** — ``<workspace_dir>/workspace_mcp.yaml``. The
///    documented and recommended location. If this exists, it is
///    returned unconditionally; the parent-walk fallback is NOT
///    consulted even if a parent manifest also exists. No opt-in
///    declaration required — the manifest sitting inside the
///    workspace dir is itself the operator's intent.
/// 2. **Parent-walk fallback** —
///    ``<workspace_dir>/../workspace_mcp.yaml``. Triggered only when
///    the primary is absent AND the parent manifest *declares* it
///    applies to this specific workspace dir via the
///    ``workspace.applies_to:`` field:
///
///    ```yaml
///    # open_source/workspace_mcp.yaml
///    workspace:
///      kind: github
///      applies_to: ./repos     # required for parent-walk discovery
///    ```
///
///    The framework loads the parent manifest, canonicalises
///    ``manifest.workspace.applies_to`` against the manifest's parent
///    directory, and compares it to the actual ``workspace_dir``.
///    Match → manifest is returned. No declaration or path mismatch
///    → discovery returns ``None`` (operator must pass
///    ``--mcp-config`` explicitly).
///
///    The natural layout for github-clone-tracker workspaces is:
///
///    ```text
///    open_source/
///    ├── workspace_mcp.yaml     # config sits beside the sandbox; declares
///    │                          # workspace.applies_to: ./repos
///    └── repos/                 # --workspace points here
///    ```
///
///    The ``applies_to`` opt-in eliminates the accidental-discovery
///    footgun where a manifest in a project root would auto-attach to
///    any unrelated sibling dir. Operators who didn't author the
///    manifest get the safe default (no auto-detection); operators
///    who did get the ergonomic UX (no ``--mcp-config`` boilerplate).
///
/// Bounded to one level up; will not walk past the filesystem root.
/// Symlink-safe via canonicalisation. Added per kglite operator
/// feedback after the 0.6.x → 0.9.x migration audit.
pub fn find_workspace_manifest(workspace_dir: &Path) -> Option<PathBuf> {
    let primary = workspace_dir.join("workspace_mcp.yaml");
    if primary.is_file() {
        return Some(primary);
    }
    // Parent-walk fallback. Compare against canonicalised paths to
    // handle "/" (where parent == self) and symlinks consistently.
    let parent = workspace_dir.parent()?;
    let workspace_resolved = workspace_dir.canonicalize().ok()?;
    let parent_resolved = parent.canonicalize().ok()?;
    if parent_resolved == workspace_resolved {
        // No real parent (filesystem root).
        return None;
    }
    let fallback = parent.join("workspace_mcp.yaml");
    if !fallback.is_file() {
        return None;
    }

    // The fallback manifest must declare workspace.applies_to and
    // that declaration must canonicalise to the actual workspace_dir.
    // Otherwise the discovery is unsafe (could be accidental).
    let manifest = match load(&fallback) {
        Ok(m) => m,
        Err(e) => {
            tracing::warn!(
                manifest = %fallback.display(),
                error = %e,
                "parent-walk manifest exists but failed to parse; ignoring"
            );
            return None;
        }
    };
    let declared = manifest
        .workspace
        .as_ref()
        .and_then(|w| w.applies_to.as_ref());
    let Some(declared_path) = declared else {
        tracing::info!(
            manifest = %fallback.display(),
            "parent-walk manifest does not declare workspace.applies_to; \
             ignoring (set workspace.applies_to: <relative path> to opt in)"
        );
        return None;
    };
    let manifest_dir = fallback.parent()?;
    let declared_abs = match manifest_dir.join(declared_path).canonicalize() {
        Ok(p) => p,
        Err(e) => {
            tracing::warn!(
                manifest = %fallback.display(),
                applies_to = %declared_path,
                error = %e,
                "parent-walk manifest's workspace.applies_to cannot be resolved; ignoring"
            );
            return None;
        }
    };
    if declared_abs == workspace_resolved {
        tracing::info!(
            workspace_dir = %workspace_dir.display(),
            manifest = %fallback.display(),
            "manifest discovered via parent-walk fallback (workspace.applies_to matched)"
        );
        Some(fallback)
    } else {
        tracing::info!(
            workspace_dir = %workspace_resolved.display(),
            manifest = %fallback.display(),
            declared = %declared_abs.display(),
            "parent-walk manifest's workspace.applies_to does not match \
             this workspace_dir; ignoring"
        );
        None
    }
}

/// Parse and validate a manifest YAML file.
pub fn load(yaml_path: &Path) -> Result<Manifest, ManifestError> {
    let text = fs::read_to_string(yaml_path)
        .map_err(|e| ManifestError::at(yaml_path, format!("read error: {e}")))?;
    let raw: serde_yaml::Value = serde_yaml::from_str(&text)
        .map_err(|e| ManifestError::at(yaml_path, format!("YAML parse error: {e}")))?;
    let raw = match raw {
        serde_yaml::Value::Null => serde_yaml::Value::Mapping(serde_yaml::Mapping::new()),
        v => v,
    };
    let map = raw
        .as_mapping()
        .ok_or_else(|| ManifestError::at(yaml_path, "top-level must be a mapping"))?;
    build(map, yaml_path)
}

fn build(raw: &serde_yaml::Mapping, yaml_path: &Path) -> Result<Manifest, ManifestError> {
    check_keys(raw, ALLOWED_TOP_KEYS, "top-level keys", yaml_path)?;

    if raw.contains_key("source_root") && raw.contains_key("source_roots") {
        return Err(ManifestError::at(
            yaml_path,
            "specify either source_root (str) or source_roots (list), not both",
        ));
    }

    let mut source_roots: Vec<String> = Vec::new();
    if let Some(v) = raw.get("source_root") {
        let s = v.as_str().filter(|s| !s.is_empty()).ok_or_else(|| {
            ManifestError::at(yaml_path, "source_root must be a non-empty string")
        })?;
        source_roots.push(s.to_string());
    } else if let Some(v) = raw.get("source_roots") {
        let seq = v.as_sequence().ok_or_else(|| {
            ManifestError::at(
                yaml_path,
                "source_roots must be a list of non-empty strings",
            )
        })?;
        if seq.is_empty() {
            return Err(ManifestError::at(
                yaml_path,
                "source_roots must be non-empty when set",
            ));
        }
        for item in seq {
            let s = item.as_str().filter(|s| !s.is_empty()).ok_or_else(|| {
                ManifestError::at(
                    yaml_path,
                    "source_roots must be a list of non-empty strings",
                )
            })?;
            source_roots.push(s.to_string());
        }
    }

    let trust = build_trust(raw.get("trust"), yaml_path)?;
    let tools = build_tools(raw.get("tools"), yaml_path)?;
    let embedder = build_embedder(raw.get("embedder"), yaml_path)?;
    let builtins = build_builtins(raw.get("builtins"), yaml_path)?;
    let workspace = build_workspace(raw.get("workspace"), yaml_path)?;
    let extensions = build_extensions(raw.get("extensions"), yaml_path)?;

    Ok(Manifest {
        yaml_path: yaml_path.to_path_buf(),
        name: optional_str(raw, "name", yaml_path)?,
        instructions: optional_str(raw, "instructions", yaml_path)?,
        overview_prefix: optional_str(raw, "overview_prefix", yaml_path)?,
        source_roots,
        trust,
        tools,
        embedder,
        builtins,
        env_file: optional_str(raw, "env_file", yaml_path)?,
        workspace,
        extensions,
    })
}

fn build_extensions(
    raw: Option<&serde_yaml::Value>,
    yaml_path: &Path,
) -> Result<serde_json::Map<String, serde_json::Value>, ManifestError> {
    let Some(raw) = raw else {
        return Ok(serde_json::Map::new());
    };
    if matches!(raw, serde_yaml::Value::Null) {
        return Ok(serde_json::Map::new());
    }
    if !raw.is_mapping() {
        return Err(ManifestError::at(
            yaml_path,
            "extensions must be a mapping (downstream-binary-specific keys)",
        ));
    }
    match yaml_to_json(raw.clone())? {
        serde_json::Value::Object(o) => Ok(o),
        _ => Err(ManifestError::at(yaml_path, "extensions must be a mapping")),
    }
}

fn build_workspace(
    raw: Option<&serde_yaml::Value>,
    yaml_path: &Path,
) -> Result<Option<WorkspaceConfig>, ManifestError> {
    let Some(raw) = raw else { return Ok(None) };
    if matches!(raw, serde_yaml::Value::Null) {
        return Ok(None);
    }
    let map = raw
        .as_mapping()
        .ok_or_else(|| ManifestError::at(yaml_path, "workspace must be a mapping"))?;
    check_keys(map, ALLOWED_WORKSPACE_KEYS, "workspace keys", yaml_path)?;
    let kind = match map.get("kind") {
        None | Some(serde_yaml::Value::Null) => WorkspaceKind::default(),
        Some(serde_yaml::Value::String(s)) => match s.as_str() {
            "github" => WorkspaceKind::Github,
            "local" => WorkspaceKind::Local,
            other => {
                return Err(ManifestError::at(
                    yaml_path,
                    format!(
                        "workspace.kind must be one of {VALID_WORKSPACE_KIND:?}, got {other:?}"
                    ),
                ));
            }
        },
        Some(_) => {
            return Err(ManifestError::at(
                yaml_path,
                format!("workspace.kind must be one of {VALID_WORKSPACE_KIND:?}"),
            ))
        }
    };
    let root = match map.get("root") {
        None | Some(serde_yaml::Value::Null) => None,
        Some(serde_yaml::Value::String(s)) if !s.is_empty() => Some(s.clone()),
        _ => {
            return Err(ManifestError::at(
                yaml_path,
                "workspace.root must be a non-empty string",
            ))
        }
    };
    let watch = match map.get("watch") {
        None | Some(serde_yaml::Value::Null) => false,
        Some(serde_yaml::Value::Bool(b)) => *b,
        Some(_) => {
            return Err(ManifestError::at(
                yaml_path,
                "workspace.watch must be a bool",
            ))
        }
    };
    let applies_to = match map.get("applies_to") {
        None | Some(serde_yaml::Value::Null) => None,
        Some(serde_yaml::Value::String(s)) if !s.is_empty() => Some(s.clone()),
        _ => {
            return Err(ManifestError::at(
                yaml_path,
                "workspace.applies_to must be a non-empty string (a relative path)",
            ))
        }
    };
    if kind == WorkspaceKind::Local && root.is_none() {
        return Err(ManifestError::at(
            yaml_path,
            "workspace.kind: local requires workspace.root to be set",
        ));
    }
    if kind == WorkspaceKind::Github && watch {
        return Err(ManifestError::at(
            yaml_path,
            "workspace.watch is only valid with workspace.kind: local",
        ));
    }
    Ok(Some(WorkspaceConfig {
        kind,
        root,
        watch,
        applies_to,
    }))
}

fn check_keys(
    map: &serde_yaml::Mapping,
    allowed: &[&str],
    label: &str,
    yaml_path: &Path,
) -> Result<(), ManifestError> {
    let mut unknown: Vec<String> = Vec::new();
    for (k, _) in map {
        let key = k.as_str().unwrap_or("<non-string-key>");
        if !allowed.contains(&key) {
            unknown.push(key.to_string());
        }
    }
    if !unknown.is_empty() {
        unknown.sort();
        return Err(ManifestError::at(
            yaml_path,
            format!("unknown {label}: {unknown:?}. Allowed: {allowed:?}"),
        ));
    }
    Ok(())
}

fn optional_str(
    raw: &serde_yaml::Mapping,
    key: &str,
    yaml_path: &Path,
) -> Result<Option<String>, ManifestError> {
    match raw.get(key) {
        None | Some(serde_yaml::Value::Null) => Ok(None),
        Some(serde_yaml::Value::String(s)) => Ok(Some(s.clone())),
        Some(_) => Err(ManifestError::at(
            yaml_path,
            format!("{key} must be a string"),
        )),
    }
}

fn build_trust(
    raw: Option<&serde_yaml::Value>,
    yaml_path: &Path,
) -> Result<TrustConfig, ManifestError> {
    let Some(raw) = raw else {
        return Ok(TrustConfig::default());
    };
    let map = raw
        .as_mapping()
        .ok_or_else(|| ManifestError::at(yaml_path, "trust must be a mapping"))?;
    check_keys(map, ALLOWED_TRUST_KEYS, "trust keys", yaml_path)?;
    let mut cfg = TrustConfig::default();
    if let Some(v) = map.get("allow_python_tools") {
        cfg.allow_python_tools = v.as_bool().ok_or_else(|| {
            ManifestError::at(yaml_path, "trust.allow_python_tools must be a bool")
        })?;
    }
    if let Some(v) = map.get("allow_embedder") {
        cfg.allow_embedder = v
            .as_bool()
            .ok_or_else(|| ManifestError::at(yaml_path, "trust.allow_embedder must be a bool"))?;
    }
    if let Some(v) = map.get("allow_query_preprocessor") {
        cfg.allow_query_preprocessor = v.as_bool().ok_or_else(|| {
            ManifestError::at(yaml_path, "trust.allow_query_preprocessor must be a bool")
        })?;
    }
    Ok(cfg)
}

fn build_tools(
    raw: Option<&serde_yaml::Value>,
    yaml_path: &Path,
) -> Result<Vec<ToolSpec>, ManifestError> {
    let Some(raw) = raw else {
        return Ok(Vec::new());
    };
    let seq = raw
        .as_sequence()
        .ok_or_else(|| ManifestError::at(yaml_path, "tools must be a list"))?;
    let mut tools: Vec<ToolSpec> = Vec::new();
    let mut seen: BTreeMap<String, ()> = BTreeMap::new();
    for (i, entry) in seq.iter().enumerate() {
        let tool = build_tool(entry, i, yaml_path)?;
        let name = tool.name().to_string();
        if seen.insert(name.clone(), ()).is_some() {
            return Err(ManifestError::at(
                yaml_path,
                format!("duplicate tool name: {name:?}"),
            ));
        }
        tools.push(tool);
    }
    Ok(tools)
}

fn build_tool(
    entry: &serde_yaml::Value,
    idx: usize,
    yaml_path: &Path,
) -> Result<ToolSpec, ManifestError> {
    let map = entry
        .as_mapping()
        .ok_or_else(|| ManifestError::at(yaml_path, format!("tools[{idx}] must be a mapping")))?;
    check_keys(map, ALLOWED_TOOL_KEYS, "tool keys", yaml_path)?;

    // Kind detection. `cypher` and `python` are tool-creation kinds
    // (operator declares a new named tool); `bundled` is a tool-
    // override kind (operator picks a bundled tool name and customises
    // its agent-facing surface). Exactly one must be present.
    let has_cypher = map.contains_key("cypher");
    let has_python = map.contains_key("python");
    let has_bundled = map.contains_key("bundled");
    let kinds_present: Vec<&str> = [
        ("cypher", has_cypher),
        ("python", has_python),
        ("bundled", has_bundled),
    ]
    .into_iter()
    .filter(|(_, p)| *p)
    .map(|(k, _)| k)
    .collect();
    if kinds_present.is_empty() {
        return Err(ManifestError::at(
            yaml_path,
            format!("tools[{idx}] needs exactly one of: [\"cypher\", \"python\", \"bundled\"]"),
        ));
    }
    if kinds_present.len() > 1 {
        return Err(ManifestError::at(
            yaml_path,
            format!("tools[{idx}] has multiple kinds set ({kinds_present:?}); pick exactly one"),
        ));
    }

    // The `bundled` kind takes its name from the `bundled:` value
    // itself (e.g. `bundled: cypher_query`) and forbids the
    // tool-creation fields. Branch early so we don't run the
    // tool-creation `name:` requirement against an override entry.
    if has_bundled {
        return build_bundled_override(map, idx, yaml_path);
    }

    let name = map
        .get("name")
        .and_then(|v| v.as_str())
        .filter(|s| valid_identifier(s))
        .ok_or_else(|| {
            ManifestError::at(
                yaml_path,
                format!("tools[{idx}] needs a string `name:` matching ^[a-zA-Z_][a-zA-Z0-9_]*$"),
            )
        })?
        .to_string();

    // `hidden:` is only valid on bundled overrides (`hidden:`-flagging
    // a tool you're declaring inline doesn't make sense — just don't
    // declare it). Reject early so the operator gets a clear error.
    if map.contains_key("hidden") {
        return Err(ManifestError::at(
            yaml_path,
            format!(
                "tools[{idx}] ({name:?}) `hidden:` is only valid on `bundled:` override entries"
            ),
        ));
    }

    let description = match map.get("description") {
        None | Some(serde_yaml::Value::Null) => None,
        Some(serde_yaml::Value::String(s)) => Some(s.clone()),
        Some(_) => {
            return Err(ManifestError::at(
                yaml_path,
                format!("tools[{idx}] ({name:?}).description must be a string"),
            ))
        }
    };

    let parameters = match map.get("parameters") {
        None | Some(serde_yaml::Value::Null) => None,
        Some(v) if v.is_mapping() => Some(yaml_to_json(v.clone())?),
        Some(_) => {
            return Err(ManifestError::at(
                yaml_path,
                format!("tools[{idx}] ({name:?}).parameters must be a mapping"),
            ))
        }
    };

    if has_cypher {
        let cypher = map
            .get("cypher")
            .and_then(|v| v.as_str())
            .filter(|s| !s.trim().is_empty())
            .ok_or_else(|| {
                ManifestError::at(
                    yaml_path,
                    format!("tools[{idx}] ({name:?}).cypher must be a non-empty string"),
                )
            })?
            .to_string();
        return Ok(ToolSpec::Cypher(CypherTool {
            name,
            cypher,
            description,
            parameters,
        }));
    }

    // python tool
    let python = map
        .get("python")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .ok_or_else(|| {
            ManifestError::at(
                yaml_path,
                format!("tools[{idx}] ({name:?}).python must be a non-empty path string"),
            )
        })?
        .to_string();
    let function = map
        .get("function")
        .and_then(|v| v.as_str())
        .filter(|s| valid_identifier(s))
        .ok_or_else(|| {
            ManifestError::at(
                yaml_path,
                format!(
                    "tools[{idx}] ({name:?}) python tools need `function:` set to a valid Python identifier"
                ),
            )
        })?
        .to_string();
    Ok(ToolSpec::Python(PythonTool {
        name,
        python,
        function,
        description,
        parameters,
    }))
}

/// Parse a `bundled:` override entry from `tools[idx]`. The caller
/// (`build_tool`) has already established that the entry has
/// `bundled:` set as the kind discriminator.
fn build_bundled_override(
    map: &serde_yaml::Mapping,
    idx: usize,
    yaml_path: &Path,
) -> Result<ToolSpec, ManifestError> {
    let name = map
        .get("bundled")
        .and_then(|v| v.as_str())
        .filter(|s| valid_identifier(s))
        .ok_or_else(|| {
            ManifestError::at(
                yaml_path,
                format!(
                    "tools[{idx}] `bundled:` must be a string naming a bundled tool \
                     (must match ^[a-zA-Z_][a-zA-Z0-9_]*$)"
                ),
            )
        })?
        .to_string();

    // Tool-creation fields are forbidden on override entries — the
    // override only customises an existing bundled tool's surface,
    // it doesn't declare a new tool. Catch these at parse time so
    // operators get a clear error rather than silent confusion.
    for forbidden in ["name", "parameters", "function"] {
        if map.contains_key(forbidden) {
            return Err(ManifestError::at(
                yaml_path,
                format!(
                    "tools[{idx}] bundled override {name:?} cannot set `{forbidden}:` \
                     (only `description:` and `hidden:` are permitted on overrides)"
                ),
            ));
        }
    }

    let description = match map.get("description") {
        None | Some(serde_yaml::Value::Null) => None,
        Some(serde_yaml::Value::String(s)) => Some(s.clone()),
        Some(_) => {
            return Err(ManifestError::at(
                yaml_path,
                format!("tools[{idx}] bundled override {name:?}.description must be a string"),
            ))
        }
    };

    let hidden = match map.get("hidden") {
        None | Some(serde_yaml::Value::Null) => false,
        Some(serde_yaml::Value::Bool(b)) => *b,
        Some(_) => {
            return Err(ManifestError::at(
                yaml_path,
                format!("tools[{idx}] bundled override {name:?}.hidden must be a bool"),
            ))
        }
    };

    Ok(ToolSpec::Bundled(BundledOverride {
        name,
        description,
        hidden,
    }))
}

fn build_embedder(
    raw: Option<&serde_yaml::Value>,
    yaml_path: &Path,
) -> Result<Option<EmbedderConfig>, ManifestError> {
    let Some(raw) = raw else { return Ok(None) };
    if matches!(raw, serde_yaml::Value::Null) {
        return Ok(None);
    }
    let map = raw
        .as_mapping()
        .ok_or_else(|| ManifestError::at(yaml_path, "embedder must be a mapping"))?;
    check_keys(map, ALLOWED_EMBEDDER_KEYS, "embedder keys", yaml_path)?;
    let module = map
        .get("module")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .ok_or_else(|| {
            ManifestError::at(
                yaml_path,
                "embedder.module must be a non-empty string (path or dotted name)",
            )
        })?
        .to_string();
    let class = map
        .get("class")
        .and_then(|v| v.as_str())
        .filter(|s| valid_identifier(s))
        .ok_or_else(|| {
            ManifestError::at(
                yaml_path,
                "embedder.class must be a valid identifier matching ^[a-zA-Z_][a-zA-Z0-9_]*$",
            )
        })?
        .to_string();
    let kwargs = match map.get("kwargs") {
        None | Some(serde_yaml::Value::Null) => serde_json::Map::new(),
        Some(v) if v.is_mapping() => match yaml_to_json(v.clone())? {
            serde_json::Value::Object(o) => o,
            _ => {
                return Err(ManifestError::at(
                    yaml_path,
                    "embedder.kwargs must be a mapping",
                ))
            }
        },
        Some(_) => {
            return Err(ManifestError::at(
                yaml_path,
                "embedder.kwargs must be a mapping",
            ))
        }
    };
    Ok(Some(EmbedderConfig {
        module,
        class,
        kwargs,
    }))
}

fn build_builtins(
    raw: Option<&serde_yaml::Value>,
    yaml_path: &Path,
) -> Result<BuiltinsConfig, ManifestError> {
    let Some(raw) = raw else {
        return Ok(BuiltinsConfig::default());
    };
    if matches!(raw, serde_yaml::Value::Null) {
        return Ok(BuiltinsConfig::default());
    }
    let map = raw
        .as_mapping()
        .ok_or_else(|| ManifestError::at(yaml_path, "builtins must be a mapping"))?;
    check_keys(map, ALLOWED_BUILTIN_KEYS, "builtins keys", yaml_path)?;
    let mut cfg = BuiltinsConfig::default();
    if let Some(v) = map.get("save_graph") {
        cfg.save_graph = v
            .as_bool()
            .ok_or_else(|| ManifestError::at(yaml_path, "builtins.save_graph must be a bool"))?;
    }
    if let Some(v) = map.get("temp_cleanup") {
        let s = v.as_str().ok_or_else(|| {
            ManifestError::at(
                yaml_path,
                format!("builtins.temp_cleanup must be one of {VALID_TEMP_CLEANUP:?}"),
            )
        })?;
        cfg.temp_cleanup = match s {
            "never" => TempCleanup::Never,
            "on_overview" => TempCleanup::OnOverview,
            other => {
                return Err(ManifestError::at(
                    yaml_path,
                    format!(
                        "builtins.temp_cleanup must be one of {VALID_TEMP_CLEANUP:?}, got {other:?}"
                    ),
                ))
            }
        };
    }
    Ok(cfg)
}

fn valid_identifier(s: &str) -> bool {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
        _ => return false,
    }
    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

fn yaml_to_json(v: serde_yaml::Value) -> Result<serde_json::Value, ManifestError> {
    serde_json::to_value(&v)
        .map_err(|e| ManifestError::bare(format!("yaml→json conversion failed: {e}")))
}

#[derive(Debug, Deserialize)]
struct _Reserved;

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

    fn write_tmp(text: &str) -> tempfile::NamedTempFile {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        std::io::Write::write_all(&mut f, text.as_bytes()).unwrap();
        f
    }

    #[test]
    fn loads_minimal_empty_manifest() {
        let f = write_tmp("");
        let m = load(f.path()).unwrap();
        assert_eq!(m.tools.len(), 0);
        assert_eq!(m.source_roots.len(), 0);
        assert!(!m.trust.allow_python_tools);
        assert!(!m.trust.allow_embedder);
        assert_eq!(m.builtins.temp_cleanup, TempCleanup::Never);
    }

    #[test]
    fn loads_name_and_instructions() {
        let f = write_tmp("name: Demo\ninstructions: |\n  multi-line\n  block\n");
        let m = load(f.path()).unwrap();
        assert_eq!(m.name.as_deref(), Some("Demo"));
        assert!(m.instructions.unwrap().contains("multi-line"));
    }

    #[test]
    fn rejects_unknown_top_key() {
        let f = write_tmp("bogus: 1\n");
        let err = load(f.path()).unwrap_err();
        assert!(err.message.contains("unknown top-level"));
    }

    #[test]
    fn source_root_string_normalises_to_list() {
        let f = write_tmp("source_root: ./data\n");
        let m = load(f.path()).unwrap();
        assert_eq!(m.source_roots, vec!["./data".to_string()]);
    }

    #[test]
    fn source_roots_list_preserved() {
        let f = write_tmp("source_roots:\n  - ./a\n  - ./b\n");
        let m = load(f.path()).unwrap();
        assert_eq!(m.source_roots, vec!["./a".to_string(), "./b".to_string()]);
    }

    #[test]
    fn rejects_both_source_root_and_source_roots() {
        let f = write_tmp("source_root: ./a\nsource_roots: [./b]\n");
        assert!(load(f.path()).unwrap_err().message.contains("not both"));
    }

    #[test]
    fn cypher_tool_parses() {
        let f = write_tmp("tools:\n  - name: lookup\n    cypher: MATCH (n) RETURN n\n");
        let m = load(f.path()).unwrap();
        assert_eq!(m.tools.len(), 1);
        match &m.tools[0] {
            ToolSpec::Cypher(t) => {
                assert_eq!(t.name, "lookup");
                assert!(t.cypher.contains("MATCH"));
            }
            _ => panic!("expected cypher tool"),
        }
    }

    #[test]
    fn python_tool_parses() {
        let f =
            write_tmp("tools:\n  - name: detail\n    python: ./tools.py\n    function: detail\n");
        let m = load(f.path()).unwrap();
        match &m.tools[0] {
            ToolSpec::Python(t) => {
                assert_eq!(t.python, "./tools.py");
                assert_eq!(t.function, "detail");
            }
            _ => panic!("expected python tool"),
        }
    }

    #[test]
    fn rejects_tool_with_both_kinds() {
        let f = write_tmp(
            "tools:\n  - name: x\n    cypher: 'MATCH (n) RETURN n'\n    python: ./t.py\n    function: x\n",
        );
        assert!(load(f.path())
            .unwrap_err()
            .message
            .contains("multiple kinds"));
    }

    #[test]
    fn rejects_tool_with_no_kind() {
        let f = write_tmp("tools:\n  - name: x\n");
        assert!(load(f.path())
            .unwrap_err()
            .message
            .contains("needs exactly one"));
    }

    #[test]
    fn rejects_duplicate_tool_names() {
        let f = write_tmp(
            "tools:\n  - name: same\n    cypher: 'MATCH (n) RETURN n'\n  - name: same\n    cypher: 'MATCH (m) RETURN m'\n",
        );
        assert!(load(f.path()).unwrap_err().message.contains("duplicate"));
    }

    // ─── Bundled override shape (0.3.31) ────────────────────────

    #[test]
    fn bundled_override_with_description_parses() {
        let f =
            write_tmp("tools:\n  - bundled: repo_management\n    description: \"FIRST STEP\"\n");
        let m = load(f.path()).unwrap();
        assert_eq!(m.tools.len(), 1);
        match &m.tools[0] {
            ToolSpec::Bundled(b) => {
                assert_eq!(b.name, "repo_management");
                assert_eq!(b.description.as_deref(), Some("FIRST STEP"));
                assert!(!b.hidden);
            }
            _ => panic!("expected bundled override"),
        }
    }

    #[test]
    fn bundled_override_with_hidden_parses() {
        let f = write_tmp("tools:\n  - bundled: ping\n    hidden: true\n");
        let m = load(f.path()).unwrap();
        match &m.tools[0] {
            ToolSpec::Bundled(b) => {
                assert_eq!(b.name, "ping");
                assert!(b.hidden);
                assert!(b.description.is_none());
            }
            _ => panic!("expected bundled override"),
        }
    }

    #[test]
    fn bundled_override_alongside_cypher_tools_parses() {
        let f = write_tmp(
            "tools:\n\
             \x20\x20- bundled: cypher_query\n\
             \x20\x20\x20\x20description: \"Custom server description\"\n\
             \x20\x20- name: lookup\n\
             \x20\x20\x20\x20cypher: \"MATCH (n) RETURN n\"\n",
        );
        let m = load(f.path()).unwrap();
        assert_eq!(m.tools.len(), 2);
        assert!(matches!(m.tools[0], ToolSpec::Bundled(_)));
        assert!(matches!(m.tools[1], ToolSpec::Cypher(_)));
    }

    #[test]
    fn rejects_bundled_with_cypher_kind() {
        let f =
            write_tmp("tools:\n  - bundled: cypher_query\n    cypher: \"MATCH (n) RETURN n\"\n");
        let err = load(f.path()).unwrap_err();
        assert!(
            err.message.contains("multiple kinds"),
            "got: {}",
            err.message
        );
    }

    #[test]
    fn rejects_bundled_with_name_field() {
        let f = write_tmp("tools:\n  - bundled: ping\n    name: ping\n");
        let err = load(f.path()).unwrap_err();
        assert!(
            err.message.contains("cannot set `name:`"),
            "got: {}",
            err.message
        );
    }

    #[test]
    fn rejects_bundled_with_parameters_field() {
        let f =
            write_tmp("tools:\n  - bundled: cypher_query\n    parameters:\n      type: object\n");
        let err = load(f.path()).unwrap_err();
        assert!(
            err.message.contains("cannot set `parameters:`"),
            "got: {}",
            err.message
        );
    }

    #[test]
    fn rejects_bundled_with_non_bool_hidden() {
        let f = write_tmp("tools:\n  - bundled: ping\n    hidden: yes-please\n");
        let err = load(f.path()).unwrap_err();
        assert!(
            err.message.contains("hidden must be a bool"),
            "got: {}",
            err.message
        );
    }

    #[test]
    fn rejects_hidden_on_cypher_tool() {
        let f = write_tmp(
            "tools:\n  - name: lookup\n    cypher: \"MATCH (n) RETURN n\"\n    hidden: true\n",
        );
        let err = load(f.path()).unwrap_err();
        assert!(
            err.message
                .contains("`hidden:` is only valid on `bundled:` override entries"),
            "got: {}",
            err.message
        );
    }

    #[test]
    fn rejects_duplicate_bundled_overrides() {
        // The dedup check is on tool name; two `bundled: ping` entries
        // share the same name and should be rejected the same way
        // duplicate cypher tools are.
        let f = write_tmp(
            "tools:\n  - bundled: ping\n    hidden: true\n  - bundled: ping\n    description: \"x\"\n",
        );
        assert!(load(f.path()).unwrap_err().message.contains("duplicate"));
    }

    #[test]
    fn rejects_bundled_with_invalid_identifier() {
        let f = write_tmp("tools:\n  - bundled: \"123-bad\"\n    hidden: true\n");
        let err = load(f.path()).unwrap_err();
        assert!(
            err.message.contains("must be a string"),
            "got: {}",
            err.message
        );
    }

    #[test]
    fn bundled_override_to_json_shape() {
        let f = write_tmp(
            "tools:\n  - bundled: repo_management\n    description: \"FIRST STEP\"\n    hidden: false\n",
        );
        let m = load(f.path()).unwrap();
        let v = m.to_json();
        assert_eq!(v["tools"][0]["kind"], "bundled");
        assert_eq!(v["tools"][0]["name"], "repo_management");
        assert_eq!(v["tools"][0]["description"], "FIRST STEP");
        assert_eq!(v["tools"][0]["hidden"], false);
    }

    #[test]
    fn embedder_parses() {
        let f = write_tmp(
            "embedder:\n  module: ./e.py\n  class: GraphEmbedder\n  kwargs:\n    cooldown: 900\n",
        );
        let m = load(f.path()).unwrap();
        let e = m.embedder.unwrap();
        assert_eq!(e.module, "./e.py");
        assert_eq!(e.class, "GraphEmbedder");
        assert_eq!(e.kwargs.get("cooldown").unwrap().as_i64(), Some(900));
    }

    #[test]
    fn builtins_parses_temp_cleanup() {
        let f = write_tmp("builtins:\n  save_graph: true\n  temp_cleanup: on_overview\n");
        let m = load(f.path()).unwrap();
        assert!(m.builtins.save_graph);
        assert_eq!(m.builtins.temp_cleanup, TempCleanup::OnOverview);
    }

    #[test]
    fn rejects_invalid_temp_cleanup() {
        let f = write_tmp("builtins:\n  temp_cleanup: nuke\n");
        assert!(load(f.path()).unwrap_err().message.contains("temp_cleanup"));
    }

    #[test]
    fn allow_embedder_trust_parses() {
        let f = write_tmp("trust:\n  allow_embedder: true\n");
        let m = load(f.path()).unwrap();
        assert!(m.trust.allow_embedder);
    }

    #[test]
    fn allow_query_preprocessor_trust_parses() {
        let f = write_tmp("trust:\n  allow_query_preprocessor: true\n");
        let m = load(f.path()).unwrap();
        assert!(m.trust.allow_query_preprocessor);
        assert!(!m.trust.allow_embedder);
        assert!(!m.trust.allow_python_tools);
    }

    #[test]
    fn allow_query_preprocessor_rejects_non_bool() {
        let f = write_tmp("trust:\n  allow_query_preprocessor: \"yes\"\n");
        let err = load(f.path()).unwrap_err();
        assert!(err
            .message
            .contains("allow_query_preprocessor must be a bool"));
    }

    #[test]
    fn find_sibling_works() {
        let dir = tempfile::tempdir().unwrap();
        let graph = dir.path().join("demo.kgl");
        std::fs::write(&graph, b"\x00").unwrap();
        let sibling = dir.path().join("demo_mcp.yaml");
        std::fs::write(&sibling, "name: x\n").unwrap();
        assert_eq!(find_sibling_manifest(&graph), Some(sibling));
    }

    #[test]
    fn workspace_local_parses() {
        let f = write_tmp("workspace:\n  kind: local\n  root: ./src\n  watch: true\n");
        let m = load(f.path()).unwrap();
        let w = m.workspace.unwrap();
        assert_eq!(w.kind, WorkspaceKind::Local);
        assert_eq!(w.root.as_deref(), Some("./src"));
        assert!(w.watch);
    }

    #[test]
    fn workspace_github_default_kind() {
        let f = write_tmp("workspace: {}\n");
        let m = load(f.path()).unwrap();
        let w = m.workspace.unwrap();
        assert_eq!(w.kind, WorkspaceKind::Github);
        assert!(w.root.is_none());
        assert!(!w.watch);
    }

    #[test]
    fn workspace_local_without_root_errors() {
        let f = write_tmp("workspace:\n  kind: local\n");
        let err = load(f.path()).unwrap_err();
        assert!(err.message.contains("requires workspace.root"));
    }

    #[test]
    fn workspace_unknown_key_rejected() {
        let f = write_tmp("workspace:\n  kind: local\n  root: ./x\n  bogus: 1\n");
        let err = load(f.path()).unwrap_err();
        assert!(err.message.contains("unknown workspace keys"));
    }

    #[test]
    fn workspace_invalid_kind_rejected() {
        let f = write_tmp("workspace:\n  kind: docker\n  root: ./x\n");
        let err = load(f.path()).unwrap_err();
        assert!(err.message.contains("workspace.kind"));
    }

    #[test]
    fn workspace_watch_invalid_for_github() {
        let f = write_tmp("workspace:\n  kind: github\n  watch: true\n");
        let err = load(f.path()).unwrap_err();
        assert!(err.message.contains("watch is only valid"));
    }

    #[test]
    fn extensions_passthrough_parses() {
        let f = write_tmp(
            "extensions:\n  csv_http_server: true\n  csv_http_server_dir: temp/\n  arbitrary:\n    nested: 1\n",
        );
        let m = load(f.path()).unwrap();
        assert_eq!(
            m.extensions
                .get("csv_http_server")
                .and_then(|v| v.as_bool()),
            Some(true)
        );
        assert_eq!(
            m.extensions
                .get("csv_http_server_dir")
                .and_then(|v| v.as_str()),
            Some("temp/")
        );
        // Nested values pass through unchanged.
        assert_eq!(
            m.extensions
                .get("arbitrary")
                .and_then(|v| v.get("nested"))
                .and_then(|v| v.as_i64()),
            Some(1)
        );
    }

    #[test]
    fn extensions_absent_defaults_to_empty() {
        let f = write_tmp("name: x\n");
        let m = load(f.path()).unwrap();
        assert!(m.extensions.is_empty());
    }

    #[test]
    fn extensions_inner_keys_unvalidated() {
        // The framework intentionally does NOT validate keys inside
        // `extensions:` — they're downstream-binary concerns. Any shape
        // that's a YAML mapping must round-trip.
        let f = write_tmp(
            "extensions:\n  whatever_kglite_wants: foo\n  some_other_consumer: { a: 1, b: 2 }\n",
        );
        load(f.path()).unwrap();
    }

    #[test]
    fn extensions_must_be_a_mapping() {
        let f = write_tmp("extensions: not-a-mapping\n");
        let err = load(f.path()).unwrap_err();
        assert!(err.message.contains("extensions must be a mapping"));
    }

    #[test]
    fn env_file_key_parses() {
        let f = write_tmp("env_file: ../.env\n");
        let m = load(f.path()).unwrap();
        assert_eq!(m.env_file.as_deref(), Some("../.env"));
    }

    #[test]
    fn env_file_unset_is_none() {
        let f = write_tmp("name: Demo\n");
        let m = load(f.path()).unwrap();
        assert!(m.env_file.is_none());
    }

    #[test]
    fn find_workspace_works() {
        let dir = tempfile::tempdir().unwrap();
        let manifest = dir.path().join("workspace_mcp.yaml");
        std::fs::write(&manifest, "name: ws\n").unwrap();
        assert_eq!(find_workspace_manifest(dir.path()), Some(manifest));
    }

    #[test]
    fn find_workspace_walks_one_level_up_with_applies_to() {
        // Layout: <tmp>/parent/workspace_mcp.yaml (declares
        // workspace.applies_to: ./repos) + <tmp>/parent/repos/.
        // Discovery from <tmp>/parent/repos/ should walk up one level
        // and find the sibling manifest because applies_to matches.
        let dir = tempfile::tempdir().unwrap();
        let parent = dir.path().join("parent");
        std::fs::create_dir(&parent).unwrap();
        let manifest = parent.join("workspace_mcp.yaml");
        std::fs::write(
            &manifest,
            "workspace:\n  kind: github\n  applies_to: ./repos\n",
        )
        .unwrap();
        let repos = parent.join("repos");
        std::fs::create_dir(&repos).unwrap();

        // Primary location still works.
        assert_eq!(find_workspace_manifest(&parent), Some(manifest.clone()));

        // Parent-walk fallback resolves to the same manifest. Compare
        // canonicalised paths to handle macOS /private/var vs /var.
        let found = find_workspace_manifest(&repos).expect("parent fallback should fire");
        assert_eq!(
            found.canonicalize().unwrap(),
            manifest.canonicalize().unwrap()
        );
    }

    #[test]
    fn find_workspace_ignores_parent_without_applies_to() {
        // Parent manifest exists but does NOT declare workspace.applies_to.
        // The parent-walk fallback must refuse to auto-detect it —
        // otherwise an unrelated workspace_mcp.yaml in a sibling dir
        // could surprise-attach to whatever --workspace path the
        // operator passes. Safe default: require the opt-in.
        let dir = tempfile::tempdir().unwrap();
        let parent = dir.path().join("parent");
        std::fs::create_dir(&parent).unwrap();
        let manifest = parent.join("workspace_mcp.yaml");
        std::fs::write(&manifest, "name: not for repos\n").unwrap();
        let repos = parent.join("repos");
        std::fs::create_dir(&repos).unwrap();

        assert_eq!(
            find_workspace_manifest(&repos),
            None,
            "parent manifest without workspace.applies_to must NOT auto-attach"
        );
    }

    #[test]
    fn find_workspace_ignores_parent_with_mismatched_applies_to() {
        // Parent manifest declares applies_to: ./repos but the
        // actual --workspace path is ./other_dir. The mismatch must
        // suppress auto-detection.
        let dir = tempfile::tempdir().unwrap();
        let parent = dir.path().join("parent");
        std::fs::create_dir(&parent).unwrap();
        let manifest = parent.join("workspace_mcp.yaml");
        std::fs::write(
            &manifest,
            "workspace:\n  kind: github\n  applies_to: ./repos\n",
        )
        .unwrap();
        let other = parent.join("other_dir");
        std::fs::create_dir(&other).unwrap();

        assert_eq!(
            find_workspace_manifest(&other),
            None,
            "applies_to: ./repos must NOT match --workspace ./other_dir"
        );
    }

    #[test]
    fn find_workspace_returns_none_when_missing_everywhere() {
        let dir = tempfile::tempdir().unwrap();
        let child = dir.path().join("child");
        std::fs::create_dir(&child).unwrap();
        // No manifest in either child or its parent (tmpdir root).
        assert_eq!(find_workspace_manifest(&child), None);
    }

    #[test]
    fn find_workspace_primary_wins_over_parent_fallback() {
        // Both primary AND parent-fallback exist. The primary must
        // win — this anchors the precedence rule documented on
        // `find_workspace_manifest`. The parent declares applies_to
        // matching the child dir, so it WOULD be a valid fallback —
        // but the primary preempts it. If a future refactor swaps
        // the order, this test fails loudly.
        let dir = tempfile::tempdir().unwrap();
        let parent_manifest = dir.path().join("workspace_mcp.yaml");
        std::fs::write(
            &parent_manifest,
            "workspace:\n  kind: github\n  applies_to: ./repos\n",
        )
        .unwrap();
        let child = dir.path().join("repos");
        std::fs::create_dir(&child).unwrap();
        let child_manifest = child.join("workspace_mcp.yaml");
        std::fs::write(&child_manifest, "name: child\n").unwrap();

        // Discovery from `child` should return the child manifest,
        // NOT the parent's. Compare canonicalised to handle the
        // macOS /private/var vs /var symlink consistently.
        let found = find_workspace_manifest(&child).expect("primary should resolve");
        assert_eq!(
            found.canonicalize().unwrap(),
            child_manifest.canonicalize().unwrap(),
            "primary location must win when both primary and parent fallback exist"
        );
    }

    #[test]
    fn to_json_shape_is_stable() {
        let f = write_tmp(
            r#"
name: KGLite Codebase
source_roots: [src, lib]
trust:
  allow_embedder: true
embedder:
  module: kglite.embed
  class: SentenceTransformerEmbedder
builtins:
  save_graph: true
  temp_cleanup: on_overview
"#,
        );
        let m = load(f.path()).unwrap();
        let actual = m.to_json();
        let expected = serde_json::json!({
            "yaml_path": f.path().display().to_string(),
            "name": "KGLite Codebase",
            "instructions": null,
            "overview_prefix": null,
            "source_roots": ["src", "lib"],
            "trust": {
                "allow_python_tools": false,
                "allow_embedder": true,
                "allow_query_preprocessor": false,
            },
            "tools": [],
            "embedder": {
                "module": "kglite.embed",
                "class": "SentenceTransformerEmbedder",
                "kwargs": {},
            },
            "builtins": { "save_graph": true, "temp_cleanup": "on_overview" },
            "env_file": null,
            "workspace": null,
            "extensions": {},
        });
        assert_eq!(actual, expected);
    }

    #[test]
    fn to_json_round_trips_tools_and_workspace() {
        let f = write_tmp(
            r#"
name: Full Surface
source_root: ./src
trust:
  allow_python_tools: true
tools:
  - name: nodes_for
    cypher: "MATCH (n {name: $name}) RETURN n"
    description: "fetch nodes by name"
  - name: run_query
    python: tools.py
    function: run
workspace:
  kind: local
  root: /tmp/ws
  watch: true
builtins:
  save_graph: false
env_file: .env.local
extensions:
  kglite:
    flavour: standard
"#,
        );
        let m = load(f.path()).unwrap();
        let v = m.to_json();
        assert_eq!(v["name"], "Full Surface");
        assert_eq!(v["trust"]["allow_python_tools"], true);
        assert_eq!(v["workspace"]["kind"], "local");
        assert_eq!(v["workspace"]["root"], "/tmp/ws");
        assert_eq!(v["workspace"]["watch"], true);
        assert_eq!(v["env_file"], ".env.local");
        assert_eq!(v["tools"][0]["kind"], "cypher");
        assert_eq!(v["tools"][0]["name"], "nodes_for");
        assert_eq!(v["tools"][1]["kind"], "python");
        assert_eq!(v["tools"][1]["name"], "run_query");
        assert_eq!(v["tools"][1]["python"], "tools.py");
        assert_eq!(v["tools"][1]["function"], "run");
        assert_eq!(v["extensions"]["kglite"]["flavour"], "standard");
    }
}