vela-cli 0.913.0

The vela command-line tool: build, check, sign, replay, and publish scientific frontier state.
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
//! Read-only MCP/HTTP frontier server.

#![allow(clippy::too_many_lines)]

use std::collections::{HashMap, HashSet};
use std::io::{self, BufRead, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;

use axum::{
    Router,
    routing::{get, post},
};
use reqwest::Client;
use serde::Serialize;
use serde_json::{Value, json};
use tokio::sync::Mutex;
use tower_http::cors::CorsLayer;

use vela_edge::signals;
use vela_edge::tool_registry;
use vela_protocol::bundle::FindingBundle;
use vela_protocol::project::{self, ConfidenceDistribution, Project, ProjectStats};
use vela_protocol::repo;
use vela_protocol::sources;

use super::http::{
    http_entries, http_entry, http_entry_events, http_entry_finding, http_entry_findings,
    http_health, http_mcp, http_mcp_get,
};
use super::tools::{
    tool_external, tool_finding, tool_graph, tool_nanopublication, tool_objects, tool_orient,
    tool_search, tool_verify, tool_work,
};
pub enum ProjectSource {
    Single(PathBuf),
    Directory(PathBuf),
}

impl ProjectSource {
    pub fn from_args(single: Option<&Path>, dir: Option<&Path>) -> Self {
        if let Some(d) = dir {
            Self::Directory(d.to_path_buf())
        } else if let Some(s) = single {
            Self::Single(s.to_path_buf())
        } else {
            eprintln!(
                "{} provide either a frontier file or --frontiers <dir>",
                vela_protocol::cli_style::err_prefix()
            );
            std::process::exit(1);
        }
    }
}

#[derive(Clone)]
pub struct ProjectInfo {
    pub name: String,
    pub file: String,
    pub findings_count: usize,
    pub links_count: usize,
    pub papers: usize,
}

pub fn load_projects(source: &ProjectSource) -> (Project, Vec<ProjectInfo>) {
    match source {
        ProjectSource::Single(path) => {
            let mut frontier = repo::load_from_path(path).unwrap_or_else(|e| {
                eprintln!(
                    "{} failed to load frontier: {e}",
                    vela_protocol::cli_style::err_prefix()
                );
                std::process::exit(1);
            });
            sources::materialize_project(&mut frontier);
            let info = ProjectInfo {
                name: frontier.project.name.clone(),
                file: path.display().to_string(),
                findings_count: frontier.findings.len(),
                links_count: frontier.stats.links,
                papers: frontier.project.papers_processed,
            };
            (frontier, vec![info])
        }
        ProjectSource::Directory(dir) => {
            let mut entries: Vec<PathBuf> = std::fs::read_dir(dir)
                .unwrap_or_else(|e| {
                    eprintln!(
                        "{} failed to read directory: {e}",
                        vela_protocol::cli_style::err_prefix()
                    );
                    std::process::exit(1);
                })
                .filter_map(Result::ok)
                .map(|entry| entry.path())
                .filter(|path| {
                    (path.is_dir() && path.join(".vela").exists())
                        || path.extension().is_some_and(|ext| ext == "json")
                })
                .collect();
            entries.sort();
            if entries.is_empty() {
                eprintln!("no frontier files found in {}", dir.display());
                std::process::exit(1);
            }

            let mut named = Vec::new();
            for path in &entries {
                let mut frontier = repo::load_from_path(path).unwrap_or_else(|e| {
                    eprintln!(
                        "{} failed to load {}: {e}",
                        vela_protocol::cli_style::err_prefix(),
                        path.display()
                    );
                    std::process::exit(1);
                });
                sources::materialize_project(&mut frontier);
                let name = path
                    .file_stem()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .to_string();
                named.push((name, frontier));
            }
            let infos = named
                .iter()
                .map(|(name, frontier)| ProjectInfo {
                    name: frontier.project.name.clone(),
                    file: name.clone(),
                    findings_count: frontier.findings.len(),
                    links_count: frontier.stats.links,
                    papers: frontier.project.papers_processed,
                })
                .collect::<Vec<_>>();
            (merge_projects(named), infos)
        }
    }
}

fn merge_projects(frontiers: Vec<(String, Project)>) -> Project {
    let mut findings = Vec::<FindingBundle>::new();
    let mut categories = HashMap::<String, usize>::new();
    let mut link_types = HashMap::<String, usize>::new();
    let mut names = Vec::new();
    let mut papers_processed = 0usize;
    let mut errors = 0usize;
    // v0.36.2: preserve v0.32+ kernel objects across the merge.
    // Pre-v0.36.2, `artifacts` were dropped during merge, leaving the
    // merged stats incomplete.
    let mut artifacts = Vec::new();

    for (name, frontier) in frontiers {
        names.push(name);
        papers_processed += frontier.project.papers_processed;
        errors += frontier.project.errors;
        for (category, count) in frontier.stats.categories {
            *categories.entry(category).or_default() += count;
        }
        for (link_type, count) in frontier.stats.link_types {
            *link_types.entry(link_type).or_default() += count;
        }
        findings.extend(frontier.findings);
        artifacts.extend(frontier.artifacts);
    }

    let mut deduped = Vec::<FindingBundle>::new();
    let mut seen = HashMap::<String, usize>::new();
    for finding in findings {
        if let Some(existing) = seen.get(&finding.id).copied() {
            if finding.confidence.score > deduped[existing].confidence.score {
                deduped[existing] = finding;
            }
        } else {
            seen.insert(finding.id.clone(), deduped.len());
            deduped.push(finding);
        }
    }

    let links = deduped.iter().map(|finding| finding.links.len()).sum();
    let replicated = deduped
        .iter()
        .filter(|finding| finding.evidence.replicated)
        .count();
    let avg_confidence = if deduped.is_empty() {
        0.0
    } else {
        (deduped
            .iter()
            .map(|finding| finding.confidence.score)
            .sum::<f64>()
            / deduped.len() as f64
            * 1000.0)
            .round()
            / 1000.0
    };
    let stats = ProjectStats {
        findings: deduped.len(),
        links,
        replicated,
        unreplicated: deduped.len().saturating_sub(replicated),
        avg_confidence,
        gaps: deduped.iter().filter(|finding| finding.flags.gap).count(),
        negative_space: deduped
            .iter()
            .filter(|finding| finding.flags.negative_space)
            .count(),
        contested: deduped
            .iter()
            .filter(|finding| finding.flags.contested)
            .count(),
        categories,
        link_types,
        human_reviewed: deduped
            .iter()
            .filter(|finding| {
                finding.provenance.review.as_ref().is_some_and(|review| {
                    review.reviewed
                        && review
                            .reviewer
                            .as_deref()
                            .map(vela_protocol::events::actor_kind)
                            .unwrap_or("human")
                            == "human"
                })
            })
            .count(),
        agent_reviewed: deduped
            .iter()
            .filter(|finding| {
                finding.provenance.review.as_ref().is_some_and(|review| {
                    review.reviewed
                        && review
                            .reviewer
                            .as_deref()
                            .map(vela_protocol::events::actor_kind)
                            .unwrap_or("human")
                            != "human"
                })
            })
            .count(),
        review_event_count: 0,
        confidence_update_count: 0,
        event_count: 0,
        source_count: 0,
        evidence_atom_count: 0,
        condition_record_count: 0,
        proposal_count: 0,
        confidence_distribution: ConfidenceDistribution {
            high_gt_80: deduped
                .iter()
                .filter(|finding| finding.confidence.score > 0.8)
                .count(),
            medium_60_80: deduped
                .iter()
                .filter(|finding| (0.6..=0.8).contains(&finding.confidence.score))
                .count(),
            low_lt_60: deduped
                .iter()
                .filter(|finding| finding.confidence.score < 0.6)
                .count(),
        },
    };

    let mut project = Project {
        vela_version: project::VELA_SCHEMA_VERSION.to_string(),
        schema: project::VELA_SCHEMA_URL.to_string(),
        frontier_id: None,
        project: project::ProjectMeta {
            name: format!("merged: {}", names.join(", ")),
            description: format!("Merged from {} frontiers", names.len()),
            compiled_at: chrono::Utc::now().to_rfc3339(),
            compiler: project::VELA_COMPILER_VERSION.to_string(),
            papers_processed,
            errors,
            dependencies: Vec::new(),
        },
        stats,
        findings: deduped,
        sources: Vec::new(),
        evidence_atoms: Vec::new(),
        condition_records: Vec::new(),
        review_events: Vec::new(),
        confidence_updates: Vec::new(),
        events: Vec::new(),
        proposals: Vec::new(),
        proof_state: Default::default(),
        signatures: Vec::new(),
        actors: Vec::new(),
        artifacts,
        released_diff_packs: Vec::new(),
        verdict_conflicts: Vec::new(),
        contradictions: Vec::new(),
        verifier_attachments: Vec::new(),
        attempts: Vec::new(),
        attempt_resolutions: Vec::new(),
        transfers: Vec::new(),
        endorsements: Vec::new(),
        statement_attestations: Vec::new(),
        anchor_links: Vec::new(),
        attempt_claims: Vec::new(),
        statement_registrations: Vec::new(),
    };
    sources::materialize_project(&mut project);
    project
}

pub async fn run(
    source: ProjectSource,
    _backend: Option<&str>,
    profile: tool_registry::McpProfile,
) {
    // No working-tree .env: serve runs inside cloned frontier checkouts
    // (see run_command's note on the injection class).
    let (frontier, project_infos) = load_projects(&source);
    let source_path: Option<PathBuf> = match &source {
        ProjectSource::Single(path) => Some(path.clone()),
        ProjectSource::Directory(_) => None,
    };
    let state = AppState {
        project: Arc::new(Mutex::new(frontier)),
        project_infos,
        client: Client::new(),
        profile,
        source_path,
    };
    let no_exclusions = HashSet::new();
    let stdin = io::stdin();
    let stdout = io::stdout();

    for line in stdin.lock().lines() {
        let Ok(line) = line else {
            break;
        };
        if line.trim().is_empty() {
            continue;
        }
        let Ok(request) = serde_json::from_str::<Value>(&line) else {
            continue;
        };
        let Some(response) = rpc_dispatch(&request, &state, &no_exclusions).await else {
            continue;
        };
        let mut out = stdout.lock();
        let _ = serde_json::to_writer(&mut out, &response);
        let _ = out.write_all(b"\n");
        let _ = out.flush();
    }
}

/// The one JSON-RPC dispatcher behind every MCP transport: the stdio line
/// loop, the `/mcp` streamable-HTTP route, and the hub's hosted endpoint
/// (via `McpService`). `None` means the message was a notification and no
/// response is owed. `excluded` names tools withheld from this transport
/// (the hosted endpoint drops the filesystem-path `vela_*` family); the
/// exclusion applies to both `tools/list` and `tools/call`.
async fn rpc_dispatch(request: &Value, st: &AppState, excluded: &HashSet<String>) -> Option<Value> {
    let id = request.get("id").cloned();
    let method = request["method"].as_str().unwrap_or_default();
    if method.starts_with("notifications/") {
        return None;
    }
    Some(match method {
        "initialize" => {
            // Stateless JSON either way, so echo the client's requested
            // protocol version; default to the widely-supported baseline.
            let requested = request["params"]["protocolVersion"]
                .as_str()
                .unwrap_or("2024-11-05");
            json_rpc_result(
                &id,
                json!({
                    "protocolVersion": requested,
                    "capabilities": {"tools": {}},
                    "serverInfo": {"name": "vela", "version": project::VELA_SCHEMA_VERSION}
                }),
            )
        }
        "tools/list" => {
            let mut tools = tool_registry::mcp_tools_json_for_profile(st.profile);
            if !excluded.is_empty()
                && let Some(arr) = tools.as_array_mut()
            {
                arr.retain(|t| t["name"].as_str().is_none_or(|n| !excluded.contains(n)));
            }
            json_rpc_result(&id, json!({"tools": tools}))
        }
        "tools/call" => {
            let name = request["params"]["name"].as_str().unwrap_or_default();
            let args = request["params"]["arguments"].clone();
            if excluded.contains(name) {
                let available: Vec<String> = tool_registry::tools_for_profile(st.profile)
                    .into_iter()
                    .map(|t| t.name)
                    .filter(|n| !excluded.contains(n))
                    .collect();
                json_rpc_error(
                    &id,
                    -32602,
                    &format!(
                        "`{name}` is not served on this hosted endpoint (it operates on \
                         local filesystem paths); clone the frontier repo and run it \
                         there. Tools available here: {}",
                        available.join(", ")
                    ),
                )
            } else if let Some(err) = profile_gate(name, st.profile) {
                ToolResult::failure(name, err, 0).to_rpc(&id)
            } else {
                handle_tool_call(
                    &id,
                    name,
                    &args,
                    &st.project,
                    &st.client,
                    &st.project_infos,
                    st.source_path.as_deref(),
                )
                .await
            }
        }
        "ping" => json_rpc_result(&id, json!({})),
        _ => json_rpc_error(&id, -32601, "Method not found"),
    })
}

/// One streamable-HTTP MCP exchange (stateless JSON responses; no
/// server-initiated SSE). Accepts a single JSON-RPC message or a batch
/// array. Returns `(http_status, body)`; `None` body means an empty 202
/// (the message was all notifications).
pub(crate) async fn mcp_http_exchange(
    body: &str,
    st: &AppState,
    excluded: &HashSet<String>,
) -> (u16, Option<Value>) {
    let Ok(message) = serde_json::from_str::<Value>(body) else {
        return (
            400,
            Some(json!({
                "jsonrpc": "2.0", "id": null,
                "error": {"code": -32700, "message": "Parse error"}
            })),
        );
    };
    if let Some(batch) = message.as_array() {
        let mut responses = Vec::new();
        for request in batch {
            if let Some(response) = rpc_dispatch(request, st, excluded).await {
                responses.push(response);
            }
        }
        if responses.is_empty() {
            (202, None)
        } else {
            (200, Some(Value::Array(responses)))
        }
    } else {
        match rpc_dispatch(&message, st, excluded).await {
            Some(response) => (200, Some(response)),
            None => (202, None),
        }
    }
}

/// A hosted, in-process MCP service over named frontier checkouts. The hub
/// embeds this to serve `hub.constellate.science/mcp` without a sidecar:
/// the same dispatcher, profile gate, and tool registry as `vela serve`,
/// loaded from the git checkouts its ingest lane already maintains.
pub struct McpService {
    state: AppState,
    excluded: HashSet<String>,
}

impl McpService {
    /// Load named frontier directories into one merged read-only service.
    /// A broken entry is skipped and reported in the returned warnings,
    /// never fatal: one frontier failing to replay must not take the
    /// hosted endpoint down for the rest. Loading is the only filesystem
    /// touch; the merge itself is `from_projects`.
    pub fn from_named_paths(
        entries: &[(String, PathBuf)],
        profile_str: &str,
        exclude: &[String],
    ) -> Result<(Self, Vec<String>), String> {
        let mut loaded = Vec::new();
        let mut warnings = Vec::new();
        for (name, path) in entries {
            match repo::load_from_path(path) {
                Ok(frontier) => loaded.push((name.clone(), frontier)),
                Err(e) => warnings.push(format!("{name}: {e}")),
            }
        }
        if loaded.is_empty() {
            return Err(format!(
                "no loadable frontier among {} entries: {}",
                entries.len(),
                warnings.join(" | ")
            ));
        }
        let (service, more) = Self::from_projects(loaded, profile_str, exclude)?;
        warnings.extend(more);
        Ok((service, warnings))
    }

    /// Build the merged read-only service from already-loaded projects —
    /// the path the hub's DB-hydrated refresher uses (no filesystem at
    /// all). Each project is re-materialized here: promoted DB snapshots
    /// were persisted WITHOUT `materialize_project`, so skipping it would
    /// diverge from the checkout loader's output.
    pub fn from_projects(
        entries: Vec<(String, Project)>,
        profile_str: &str,
        exclude: &[String],
    ) -> Result<(Self, Vec<String>), String> {
        let profile = tool_registry::McpProfile::parse(profile_str)?;
        if entries.is_empty() {
            return Err("no frontier projects to serve".to_string());
        }
        let mut named = Vec::with_capacity(entries.len());
        for (name, mut frontier) in entries {
            sources::materialize_project(&mut frontier);
            named.push((name, frontier));
        }
        let project_infos = named
            .iter()
            .map(|(name, frontier)| ProjectInfo {
                name: frontier.project.name.clone(),
                file: name.clone(),
                findings_count: frontier.findings.len(),
                links_count: frontier.stats.links,
                papers: frontier.project.papers_processed,
            })
            .collect();
        let project = merge_projects(named);
        Ok((
            Self {
                state: AppState {
                    project: Arc::new(Mutex::new(project)),
                    project_infos,
                    client: Client::new(),
                    profile,
                    source_path: None,
                },
                excluded: exclude.iter().cloned().collect(),
            },
            Vec::new(),
        ))
    }

    /// The hosted exclusion set: every tool that operates on a
    /// caller-supplied filesystem path. On a public endpoint those are
    /// useless at best (the caller has no paths on the server) and a CPU
    /// sink at worst (`verify` with mode=witness). The hosted endpoint runs
    /// the read-only profile, so its `tools/list` is the read-only surface
    /// minus these three: orient, finding, search, graph, external.
    pub fn hosted_exclusions() -> Vec<String> {
        ["verify", "work", "objects"]
            .into_iter()
            .map(str::to_string)
            .collect()
    }

    /// Handle one streamable-HTTP MCP exchange (single message or batch).
    /// Returns `(http_status, body)`; `None` body = empty 202.
    pub async fn handle_http(&self, body: &str) -> (u16, Option<Value>) {
        mcp_http_exchange(body, &self.state, &self.excluded).await
    }

    /// The loaded frontier labels, for the hub's status surfaces.
    pub fn frontier_labels(&self) -> Vec<String> {
        self.state
            .project_infos
            .iter()
            .map(|i| format!("{} ({})", i.name, i.file))
            .collect()
    }
}

pub async fn run_http(
    source: ProjectSource,
    backend: Option<&str>,
    port: u16,
    profile: tool_registry::McpProfile,
) {
    let _ = backend;
    // No working-tree .env: serve runs inside cloned frontier checkouts
    // (see run_command's note on the injection class).
    let (frontier, project_infos) = load_projects(&source);
    let source_path = match &source {
        ProjectSource::Single(path) => Some(path.clone()),
        ProjectSource::Directory(_) => None,
    };
    let state = AppState {
        project: Arc::new(Mutex::new(frontier)),
        project_infos,
        client: Client::new(),
        profile,
        source_path,
    };

    // One HTTP shape: the read surface mirrors the hub's `/entries/{vfr}/…`
    // paths for the concepts serve supports, and `/mcp` at the root is the
    // tool surface. The literal segment `self` names the served frontier;
    // its real vfr_ id (or a prefix) is accepted too.
    let app = Router::new()
        .route("/health", get(http_health))
        .route("/healthz", get(http_health))
        .route("/entries", get(http_entries))
        .route("/entries/{vfr}", get(http_entry))
        .route("/entries/{vfr}/findings", get(http_entry_findings))
        .route("/entries/{vfr}/findings/{id}", get(http_entry_finding))
        .route("/entries/{vfr}/events", get(http_entry_events))
        // Streamable-HTTP MCP (stateless JSON): the same dispatcher as
        // stdio, so any remote MCP client can connect without a clone.
        .route("/mcp", post(http_mcp).get(http_mcp_get));

    // Explicit request-body cap for THREAT_MODEL.md A13. Axum's default body
    // limit is 2 MiB; 8 MiB accommodates ordinary MCP and Receipt envelopes
    // while refusing unbounded inputs. Pin it so a future Axum default change
    // cannot silently expose the surface. Localhost-only deploys
    // are bounded by this limit; remote deploys behind a reverse
    // proxy should layer rate limiting on top (the substrate does
    // not enforce per-actor or per-IP request budgets).
    let app = app
        .layer(axum::extract::DefaultBodyLimit::max(8 * 1024 * 1024))
        .layer(CorsLayer::permissive())
        .with_state(state);

    let addr = format!("0.0.0.0:{port}");
    eprintln!(
        "  {}",
        format!("VELA · SERVE · HTTP :{port}").to_uppercase()
    );
    eprintln!("  {}", vela_protocol::cli_style::tick_row(60));
    eprintln!("  listening on http://{addr}");
    // Full endpoint enumeration so a fresh user opening `vela serve --http`
    // knows what they can hit. `self` names the served frontier; its real
    // vfr_ id works too.
    eprintln!("  endpoints:");
    eprintln!("    health:    GET  /health  /healthz");
    eprintln!("    entries:   GET  /entries                          (single-element list)");
    eprintln!("               GET  /entries/self                     (frontier summary)");
    eprintln!("               GET  /entries/self/findings            (?query= to search)");
    eprintln!("               GET  /entries/self/findings/{{id}}");
    eprintln!("               GET  /entries/self/events?cursor=&limit=");
    eprintln!("    tools:     POST /mcp   (streamable-HTTP MCP; the tool surface)");
    let listener = tokio::net::TcpListener::bind(&addr)
        .await
        .unwrap_or_else(|e| {
            eprintln!(
                "{} failed to bind to {addr}: {e}",
                vela_protocol::cli_style::err_prefix()
            );
            std::process::exit(1);
        });
    axum::serve(listener, app).await.unwrap();
}

pub fn check_tools(source: ProjectSource, adoption: bool) -> Result<Value, String> {
    let started = std::time::Instant::now();
    let source_label = match &source {
        ProjectSource::Single(path) => path.display().to_string(),
        ProjectSource::Directory(path) => path.display().to_string(),
    };
    let source_path = match &source {
        ProjectSource::Single(p) => Some(p.as_path()),
        ProjectSource::Directory(p) => Some(p.as_path()),
    };
    let (frontier, _project_infos) = load_projects(&source);
    let first_id = frontier.findings.first().map(|finding| finding.id.clone());
    let mut checks = vec![
        check_tool_result(
            "orient",
            tool_orient(&json!({}), &frontier, source_path),
            started,
        ),
        check_tool_result(
            "search",
            tool_search(&json!({"query": "Sidon", "limit": 3}), &frontier),
            started,
        ),
        check_tool_result("graph", tool_graph(&json!({}), &frontier), started),
        check_tool_result(
            "graph",
            tool_graph(&json!({"mode": "contradictions"}), &frontier),
            started,
        ),
    ];
    if let Some(id) = first_id {
        checks.push(check_tool_result(
            "finding",
            tool_finding(
                &json!({"id": id, "include": ["history", "dependents", "neighborhood"]}),
                &frontier,
            ),
            started,
        ));
        checks.push(check_tool_result(
            "orient",
            tool_orient(&json!({"problem": id}), &frontier, source_path),
            started,
        ));
        checks.push(check_tool_result(
            "graph",
            tool_graph(
                &json!({"root": id, "mode": "traverse", "max_hops": 3}),
                &frontier,
            ),
            started,
        ));
        checks.push(check_tool_result(
            "graph",
            tool_graph(&json!({"root": id, "mode": "impact"}), &frontier),
            started,
        ));
        checks.push(check_tool_result(
            "external",
            parse_payload(tool_nanopublication(&json!({"finding_id": id}), &frontier))
                .map(|v| (v, Vec::new())),
            started,
        ));
    }
    let failures = checks
        .iter()
        .filter(|check| check.get("ok").and_then(Value::as_bool) != Some(true))
        .filter_map(|check| {
            check
                .get("tool")
                .and_then(Value::as_str)
                .map(str::to_string)
        })
        .collect::<Vec<_>>();
    let checked_tools = checks
        .iter()
        .filter_map(|check| check.get("tool").and_then(Value::as_str))
        .map(str::to_string)
        .collect::<Vec<_>>();
    let registered_tools = tool_registry::all_tools()
        .into_iter()
        .map(|tool| tool.name)
        .collect::<Vec<_>>();
    let adoption_report = adoption.then(|| adoption_tool_report(&checks, &source_label));

    Ok(json!({
        "ok": failures.is_empty(),
        "command": if adoption { "serve --check-tools --adoption" } else { "serve --check-tools" },
        "schema": "vela.tool-check.v0",
        "frontier": {
            "name": frontier.project.name,
            "findings": frontier.stats.findings,
            "links": frontier.stats.links,
        },
        "summary": {
            "checks": checks.len(),
            "passed": checks.len().saturating_sub(failures.len()),
            "failed": failures.len(),
        },
        "tool_count": checked_tools.len(),
        "tools": checked_tools,
        "registered_tool_count": registered_tools.len(),
        "registered_tools": registered_tools,
        "checks": checks,
        "failures": failures,
        "adoption": adoption_report,
    }))
}

fn adoption_tool_report(checks: &[Value], source_label: &str) -> Value {
    let required_tools = vec!["orient", "search", "finding", "graph"];
    let missing_or_failed = required_tools
        .iter()
        .filter(|tool| {
            !checks.iter().any(|check| {
                check.get("tool").and_then(Value::as_str) == Some(**tool)
                    && check.get("ok").and_then(Value::as_bool) == Some(true)
            })
        })
        .copied()
        .collect::<Vec<_>>();
    json!({
        "ok": missing_or_failed.is_empty(),
        "required_tools": required_tools,
        "missing_or_failed": missing_or_failed,
        "mcp_config": {
            "mcpServers": {
                "vela": {
                    "command": "vela",
                    "args": ["serve", source_label]
                }
            }
        },
        "prompt": "Call orient first. Then use search for the review question. Inspect important results with finding (include history/dependents/neighborhood as needed). Cite vf_* ids. Review graph mode=contradictions and orient's gaps as candidate signals. Use graph mode=traverse on a root before summarizing provenance. Preserve caveats and do not present Vela output as field consensus.",
        "commands": [
            format!("vela serve {source_label} --check-tools --adoption --json"),
            format!("vela serve {source_label}")
        ],
    })
}

#[derive(Clone)]
pub(crate) struct AppState {
    pub(crate) project: Arc<Mutex<Project>>,
    pub(crate) project_infos: Vec<ProjectInfo>,
    pub(crate) client: Client,
    /// MCP exposure profile (memo §9.1). Scopes which tools `tools/list`
    /// exposes and `tools/call` will execute. Defaults to read-only.
    pub(crate) profile: tool_registry::McpProfile,
    /// Phase Q-w (v0.5): when serving a single frontier file, this is
    /// the path to write back to after a successful signed write. None
    /// when `--frontiers <dir>` is used; in that mode all writes are
    /// rejected.
    pub(crate) source_path: Option<PathBuf>,
}

/// Structured tool-error kinds. One closed set for every transport: the MCP
/// envelope and both HTTP servers speak `{kind, message, hint?}`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub(crate) enum ToolErrorKind {
    #[serde(rename = "NOT_FOUND")]
    NotFound,
    #[serde(rename = "INVALID_ARG")]
    InvalidArg,
    #[serde(rename = "PERMISSION_DENIED")]
    PermissionDenied,
    #[serde(rename = "INTERNAL")]
    Internal,
}

#[derive(Debug, Clone, Serialize)]
pub(crate) struct ToolError {
    pub(crate) kind: ToolErrorKind,
    pub(crate) message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) hint: Option<String>,
}

impl ToolError {
    pub(crate) fn new(kind: ToolErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
            hint: None,
        }
    }

    pub(crate) fn not_found(message: impl Into<String>) -> Self {
        Self::new(ToolErrorKind::NotFound, message)
    }

    pub(crate) fn invalid(message: impl Into<String>) -> Self {
        Self::new(ToolErrorKind::InvalidArg, message)
    }

    pub(crate) fn internal(message: impl Into<String>) -> Self {
        Self::new(ToolErrorKind::Internal, message)
    }

    pub(crate) fn with_hint(mut self, hint: impl Into<String>) -> Self {
        self.hint = Some(hint.into());
        self
    }

    /// Classify a prose error from an underlying impl. The impls predate the
    /// kind vocabulary, so this is a boundary heuristic: id/file lookups read
    /// as NOT_FOUND, argument shapes as INVALID_ARG, everything else INTERNAL.
    pub(crate) fn classify(message: String) -> Self {
        let lc = message.to_lowercase();
        let kind = if lc.contains("not found")
            || lc.contains("no finding resolves")
            || lc.contains("is not registered")
            || lc.contains("no such file")
            || lc.contains("is neither a finding")
        {
            ToolErrorKind::NotFound
        } else if lc.contains("required")
            || lc.contains("missing")
            || lc.contains("must be")
            || lc.contains("must start")
            || lc.contains("must include")
            || lc.contains("must contain")
            || lc.contains("invalid")
            || lc.contains("unknown edge kind")
            || lc.contains("out of [0.0, 1.0]")
            || lc.contains("is for agent:/ci: actors")
        {
            ToolErrorKind::InvalidArg
        } else {
            ToolErrorKind::Internal
        };
        Self::new(kind, message)
    }
}

/// The one result envelope every tool call returns, as a single JSON text
/// block: `{tool, ok, data, notes?, error?, signals, caveats, duration_ms}`.
/// No markdown duplication — `data` is the payload, `notes` carries
/// truncation and degradation notices, `error` carries `{kind, message,
/// hint?}` on failure.
#[derive(Debug, Clone, Serialize)]
struct ToolResult {
    tool: String,
    ok: bool,
    data: Value,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    notes: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<ToolError>,
    signals: Vec<signals::SignalItem>,
    caveats: Vec<String>,
    duration_ms: u128,
}

impl ToolResult {
    fn success(
        tool: &str,
        data: Value,
        notes: Vec<String>,
        duration_ms: u128,
        frontier: Option<&Project>,
    ) -> Self {
        let signal_items = frontier
            .map(|project| signals::analyze(project, &[]).signals)
            .unwrap_or_default();
        Self {
            tool: tool.to_string(),
            ok: true,
            data,
            notes,
            error: None,
            signals: signal_items,
            caveats: tool_registry::tool_caveats(tool),
            duration_ms,
        }
    }

    fn failure(tool: &str, error: ToolError, duration_ms: u128) -> Self {
        Self {
            tool: tool.to_string(),
            ok: false,
            data: Value::Null,
            notes: Vec::new(),
            error: Some(error),
            signals: Vec::new(),
            caveats: tool_registry::tool_caveats(tool),
            duration_ms,
        }
    }

    fn metadata(&self) -> Value {
        json!({
            "tool": self.tool,
            "ok": self.ok,
            "duration_ms": self.duration_ms,
            "caveats": self.caveats,
        })
    }

    fn to_json_text(&self) -> String {
        serde_json::to_string_pretty(self).unwrap_or_else(|_| "{}".to_string())
    }

    fn to_rpc(&self, id: &Option<Value>) -> Value {
        let mut result = json!({
            "content": [{"type": "text", "text": self.to_json_text()}],
            "isError": !self.ok,
            "_meta": self.metadata()
        });
        // Structured output (MCP 2025-06): when the tool declares an
        // outputSchema, mirror the result `data` as `structuredContent` so
        // typed clients read a validated object instead of parsing JSON out
        // of the text block. The text block stays for older clients.
        if self.ok && tool_registry::tool_output_schema(&self.tool).is_some() {
            result["structuredContent"] = self.data.clone();
        }
        json_rpc_result(id, result)
    }
}

/// MCP profile gate (memo §9.4): refuse to execute a tool the active profile
/// does not admit, returning a structured error envelope. `None` means the
/// call may proceed (allowed, or unknown — the dispatch then returns its own
/// NOT_FOUND). This is the execution boundary; `tools/list` already hides the
/// tool, but a client could still call it by name.
fn profile_gate(name: &str, profile: tool_registry::McpProfile) -> Option<ToolError> {
    let tool = tool_registry::get_tool(name)?;
    if profile.allows(&tool) {
        return None;
    }
    let hint = if tool_registry::McpProfile::Draft.allows(&tool) {
        "restart `vela serve` with `--profile draft` for non-finalizing draft/work capabilities; human finalization is unavailable through MCP and remains terminal-only (`vela sign`)"
    } else {
        "this capability is unavailable through MCP"
    };
    Some(
        ToolError::new(
            ToolErrorKind::PermissionDenied,
            format!(
                "tool `{name}` ({}) is not available in the `{}` MCP profile",
                tool.permission_level,
                profile.as_str()
            ),
        )
        .with_hint(hint),
    )
}

async fn handle_tool_call(
    id: &Option<Value>,
    name: &str,
    args: &Value,
    frontier: &Arc<Mutex<Project>>,
    client: &Client,
    project_infos: &[ProjectInfo],
    source_path: Option<&Path>,
) -> Value {
    let started = std::time::Instant::now();
    let (result, snapshot) =
        execute_tool(name, args, frontier, client, project_infos, source_path).await;
    let elapsed = started.elapsed().as_millis();
    match result {
        Ok((data, notes)) => {
            ToolResult::success(name, data, notes, elapsed, snapshot.as_ref()).to_rpc(id)
        }
        Err(error) => ToolResult::failure(name, error, elapsed).to_rpc(id),
    }
}

/// Every tool call resolves to `(data, notes)` or a typed error. `notes`
/// carries truncation and degradation notices for the envelope.
pub(crate) type ToolOutput = Result<(Value, Vec<String>), ToolError>;

/// Parse an underlying impl's JSON-string result into the envelope's `data`,
/// classifying prose errors into the kind vocabulary at the boundary.
pub(crate) fn parse_payload(result: Result<String, String>) -> Result<Value, ToolError> {
    let text = result.map_err(ToolError::classify)?;
    serde_json::from_str(&text)
        .map_err(|e| ToolError::internal(format!("tool payload did not parse as JSON: {e}")))
}

pub(crate) fn clamp_limit(args: &Value, default: u64, max: u64) -> usize {
    args.get("limit")
        .and_then(Value::as_u64)
        .unwrap_or(default)
        .clamp(1, max) as usize
}

/// Decode an opaque list cursor (an offset into the stable result order,
/// issued by a previous response's `next_cursor`).
pub(crate) fn decode_cursor(args: &Value) -> Result<usize, ToolError> {
    match args.get("cursor").and_then(Value::as_str) {
        None => Ok(0),
        Some(c) => c.parse::<usize>().map_err(|_| {
            ToolError::invalid(format!("cursor '{c}' is not a cursor this server issued"))
                .with_hint("pass a previous response's next_cursor back unchanged")
        }),
    }
}

/// Reload the served read snapshot after a successful path-bound write.
///
/// The cache lock is acquired *before* reading disk. Otherwise an earlier
/// writer can read its old postimage, pause, and overwrite the cache after a
/// later writer has already installed a newer snapshot. Holding the lock over
/// reload makes cache installation follow disk observation monotonically,
/// while the durable frontier transaction remains the write authority.
pub(crate) async fn reload_served_project(
    frontier: &Arc<Mutex<Project>>,
    path: &Path,
) -> Result<Project, String> {
    let mut cached = frontier.lock().await;
    let mut fresh = repo::load_from_path(path)?;
    sources::materialize_project(&mut fresh);
    let snapshot = clone_project(&fresh);
    *cached = fresh;
    Ok(snapshot)
}

async fn execute_tool(
    name: &str,
    args: &Value,
    frontier: &Arc<Mutex<Project>>,
    client: &Client,
    _project_infos: &[ProjectInfo],
    source_path: Option<&Path>,
) -> (ToolOutput, Option<Project>) {
    match name {
        "orient" => {
            let project = {
                let cached = frontier.lock().await;
                clone_project(&cached)
            };
            let output = tool_orient(args, &project, source_path);
            (output, Some(clone_project(&project)))
        }
        "finding" => {
            let project = frontier.lock().await;
            (tool_finding(args, &project), Some(clone_project(&project)))
        }
        "search" => {
            let project = frontier.lock().await;
            (tool_search(args, &project), Some(clone_project(&project)))
        }
        "graph" => {
            let project = frontier.lock().await;
            (tool_graph(args, &project), Some(clone_project(&project)))
        }
        "verify" => (tool_verify(args, source_path), None),
        "work" => {
            let result = tool_work(args, source_path);
            match result {
                Ok((data, mut notes)) => {
                    let Some(path) = source_path else {
                        // `tool_work` rejects this mode before writing; keep a
                        // defensive guard here so a future action cannot make
                        // a merged service writable by accident.
                        return (
                            Err(ToolError::new(
                                ToolErrorKind::PermissionDenied,
                                "work writes are unavailable without one configured frontier",
                            )),
                            None,
                        );
                    };
                    match reload_served_project(frontier, path).await {
                        Ok(snapshot) => (Ok((data, notes)), Some(snapshot)),
                        Err(error) => {
                            // Preserve the successful write result (including
                            // its operation/publication identifiers) while
                            // making the stale read surface explicit.
                            notes.push(format!(
                                "write completed, but the MCP snapshot reload failed; reconnect before reading: {error}"
                            ));
                            (Ok((data, notes)), None)
                        }
                    }
                }
                Err(error) => (Err(error), None),
            }
        }
        "objects" => (tool_objects(args, source_path), None),
        "external" => {
            let project = frontier.lock().await;
            (
                tool_external(args, &project, client).await,
                Some(clone_project(&project)),
            )
        }
        _ => {
            let known: Vec<String> = tool_registry::all_tools()
                .into_iter()
                .map(|t| t.name)
                .collect();
            (
                Err(ToolError::not_found(format!("unknown tool `{name}`"))
                    .with_hint(format!("this server exposes: {}", known.join(", ")))),
                None,
            )
        }
    }
}

fn check_tool_result(name: &str, result: ToolOutput, started: std::time::Instant) -> Value {
    let duration_ms = started.elapsed().as_millis();
    match result {
        Ok((data, notes)) => {
            let has_data = !data.is_null();
            json!({
                "tool": name,
                "ok": has_data,
                "data": data,
                "notes": notes,
                "has_data": has_data,
                "caveats": tool_registry::tool_caveats(name),
                "duration_ms": duration_ms,
            })
        }
        Err(error) => json!({
            "tool": name,
            "ok": false,
            "data": Value::Null,
            "error": error,
            "caveats": tool_registry::tool_caveats(name),
            "duration_ms": duration_ms,
        }),
    }
}

fn clone_project(project: &Project) -> Project {
    serde_json::from_value(serde_json::to_value(project).unwrap_or_default()).unwrap_or_else(|_| {
        project::assemble("unavailable", Vec::new(), 0, 1, "failed to clone frontier")
    })
}

fn json_rpc_result(id: &Option<Value>, result: Value) -> Value {
    json!({"jsonrpc": "2.0", "id": id, "result": result})
}

fn json_rpc_error(id: &Option<Value>, code: i32, message: &str) -> Value {
    json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}})
}

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

    fn fixture() -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../examples/erdos-formalization")
    }

    fn work_fixture(root: &Path) -> PathBuf {
        let path = root.join("work-frontier");
        let mut project = vela_protocol::project::assemble("scope", vec![], 0, 0, "test");
        let event =
            vela_protocol::events::new_finding_event(vela_protocol::events::FindingEventInput {
                kind: "attempt.claimed",
                finding_id: "scope:probe",
                actor_id: "agent:owner",
                actor_type: "agent",
                reason: "scope test",
                before_hash: "sha256:null",
                after_hash: "sha256:null",
                payload: json!({
                    "obligation_id": "scope:probe",
                    "lease_ttl_seconds": 60,
                    "claimant_actor": "agent:owner",
                    "claimant_pubkey": "test"
                }),
                caveats: Vec::new(),
                timestamp: Some("2026-07-13T00:00:00Z"),
            });
        vela_protocol::reducer::apply_event(&mut project, &event).unwrap();
        project.events.push(event);
        vela_protocol::repo::init_repo(&path, &project).unwrap();
        let session = crate::workflow::session_dir(&path, "scope:probe");
        std::fs::create_dir_all(&session).unwrap();
        std::fs::write(session.join("producer-scratch.txt"), "fixture\n").unwrap();
        path
    }

    fn service() -> McpService {
        let entries = vec![("erdos-formalization".to_string(), fixture())];
        let (service, warnings) =
            McpService::from_named_paths(&entries, "read-only", &McpService::hosted_exclusions())
                .expect("fixture frontier loads");
        assert!(warnings.is_empty(), "unexpected warnings: {warnings:?}");
        service
    }

    #[tokio::test]
    async fn initialize_echoes_protocol_version_and_lists_filtered_tools() {
        let svc = service();
        let (status, body) = svc
            .handle_http(
                r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#,
            )
            .await;
        assert_eq!(status, 200);
        let body = body.unwrap();
        assert_eq!(body["result"]["protocolVersion"], "2025-06-18");

        let (status, body) = svc
            .handle_http(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#)
            .await;
        assert_eq!(status, 200);
        let tools = body.unwrap()["result"]["tools"].clone();
        let names: Vec<String> = tools
            .as_array()
            .unwrap()
            .iter()
            .map(|t| t["name"].as_str().unwrap().to_string())
            .collect();
        // Hosted = the read-only profile minus the path-bound exclusions:
        // exactly these five.
        assert_eq!(
            names,
            vec!["orient", "finding", "search", "graph", "external"],
            "hosted tools/list is the read-only surface minus verify/work/objects"
        );
    }

    #[tokio::test]
    async fn tool_call_returns_envelope_and_excluded_tool_is_refused_by_name() {
        let svc = service();
        let (status, body) = svc
            .handle_http(
                r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"orient","arguments":{}}}"#,
            )
            .await;
        assert_eq!(status, 200);
        let body = body.unwrap();
        assert_eq!(body["result"]["isError"], false, "orient call succeeds");
        // The one JSON text block: {tool, ok, data, notes?, signals,
        // caveats, duration_ms} — and no markdown duplication.
        let text = body["result"]["content"][0]["text"].as_str().unwrap();
        let envelope: Value = serde_json::from_str(text).unwrap();
        assert_eq!(envelope["tool"], "orient");
        assert_eq!(envelope["ok"], true);
        assert!(envelope["data"].is_object(), "data payload present");
        assert!(envelope.get("markdown").is_none(), "no markdown field");
        assert!(envelope["duration_ms"].is_number());

        let (status, body) = svc
            .handle_http(
                r#"{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"verify","arguments":{}}}"#,
            )
            .await;
        assert_eq!(status, 200);
        let body = body.unwrap();
        assert_eq!(body["error"]["code"], -32602, "excluded tool refused");
        let message = body["error"]["message"].as_str().unwrap();
        assert!(
            message.contains("orient, finding, search, graph, external"),
            "refusal names the available tool set: {message}"
        );
    }

    #[tokio::test]
    async fn errors_carry_kind_and_profile_gate_refuses_writes() {
        let svc = service();
        // Unknown finding id → NOT_FOUND in the envelope, isError true.
        let (_, body) = svc
            .handle_http(
                r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"finding","arguments":{"id":"vf_does_not_exist"}}}"#,
            )
            .await;
        let body = body.unwrap();
        assert_eq!(body["result"]["isError"], true);
        let text = body["result"]["content"][0]["text"].as_str().unwrap();
        let envelope: Value = serde_json::from_str(text).unwrap();
        assert_eq!(envelope["ok"], false);
        assert_eq!(envelope["error"]["kind"], "NOT_FOUND");

        // The hosted fixture excludes path-bound tools before the profile gate.
        // Use the local MCP surface here so this assertion exercises the
        // read-only profile's refusal of the task-first write tool itself.
        let entries = vec![("erdos-formalization".to_string(), fixture())];
        let (local_svc, warnings) = McpService::from_named_paths(&entries, "read-only", &[])
            .expect("fixture frontier loads");
        assert!(warnings.is_empty(), "unexpected warnings: {warnings:?}");
        let (_, body) = local_svc
            .handle_http(
                r#"{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"work","arguments":{}}}"#,
            )
            .await;
        let text = body.unwrap()["result"]["content"][0]["text"]
            .as_str()
            .unwrap()
            .to_string();
        let envelope: Value = serde_json::from_str(&text).unwrap();
        assert_eq!(envelope["error"]["kind"], "PERMISSION_DENIED");
    }

    #[tokio::test]
    async fn failed_in_scope_work_does_not_refresh_the_served_snapshot() {
        let temp = tempfile::tempdir().unwrap();
        let path = work_fixture(temp.path()).canonicalize().unwrap();
        let project = repo::load_from_path(&path).unwrap();
        let frontier = Arc::new(Mutex::new(project));
        let args = json!({
            "frontier_path": path.display().to_string(),
            "action": "drop",
            "obligation_id": "scope:probe",
            "agent_actor": "agent:other"
        });
        let (result, snapshot) =
            execute_tool("work", &args, &frontier, &Client::new(), &[], Some(&path)).await;
        let error = result.unwrap_err();
        assert_eq!(error.kind, ToolErrorKind::PermissionDenied);
        assert!(snapshot.is_none(), "failed work must not refresh MCP reads");
    }

    #[tokio::test]
    async fn delayed_earlier_refresh_cannot_overwrite_a_later_disk_state() {
        use vela_protocol::sign::ActorRecord;

        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("cache-race");
        let mut initial = project::assemble("cache-race", vec![], 0, 0, "initial");
        initial.project.description = "earlier write".to_string();
        repo::init_repo(&path, &initial).unwrap();

        let frontier = Arc::new(Mutex::new(initial));
        // Hold the cache lock so the refresh belonging to the earlier write is
        // delayed until after a later state has reached disk. The old
        // load-then-lock sequence could have captured this actor-free snapshot
        // here and installed it last.
        let cache_guard = frontier.lock().await;
        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
        let early_frontier = Arc::clone(&frontier);
        let early_path = path.clone();
        let early_refresh = tokio::spawn(async move {
            started_tx.send(()).unwrap();
            reload_served_project(&early_frontier, &early_path).await
        });
        started_rx.await.unwrap();
        tokio::task::yield_now().await;

        let mut later = repo::load_from_path(&path).unwrap();
        later.actors.push(ActorRecord {
            id: "agent:later-write".to_string(),
            public_key: "11".repeat(32),
            algorithm: "ed25519".to_string(),
            created_at: "2026-07-14T00:00:00Z".to_string(),
            tier: None,
            orcid: None,
            access_clearance: None,
            revoked_at: None,
            revoked_reason: None,
        });
        repo::save_to_path(&path, &later).unwrap();
        let late_frontier = Arc::clone(&frontier);
        let late_path = path.clone();
        let late_refresh =
            tokio::spawn(async move { reload_served_project(&late_frontier, &late_path).await });

        drop(cache_guard);
        let early_snapshot = early_refresh.await.unwrap().unwrap();
        let late_snapshot = late_refresh.await.unwrap().unwrap();
        let has_later_write = |project: &Project| {
            project
                .actors
                .iter()
                .any(|actor| actor.id == "agent:later-write")
        };
        assert!(has_later_write(&early_snapshot));
        assert!(has_later_write(&late_snapshot));
        assert!(has_later_write(&*frontier.lock().await));
    }

    #[tokio::test]
    async fn finalization_is_absent_and_unroutable_in_every_profile() {
        for profile in ["read-only", "draft"] {
            let entries = vec![("erdos-formalization".to_string(), fixture())];
            let (svc, warnings) = McpService::from_named_paths(&entries, profile, &[])
                .expect("fixture frontier loads");
            assert!(warnings.is_empty(), "unexpected warnings: {warnings:?}");

            let (_, listed) = svc
                .handle_http(r#"{"jsonrpc":"2.0","id":7,"method":"tools/list"}"#)
                .await;
            assert!(
                !listed.unwrap()["result"]["tools"]
                    .as_array()
                    .unwrap()
                    .iter()
                    .any(|tool| tool["name"] == "decide"),
                "decide leaked into {profile} discovery"
            );

            let before = serde_json::to_value(&*svc.state.project.lock().await).unwrap();
            let (_, body) = svc
                .handle_http(
                    r#"{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"decide","arguments":{"proposal_id":"vpr_removed","action":"accept","reason":"must never route","reviewer_id":"reviewer:test","signature":"00"}}}"#,
                )
                .await;
            let text = body.unwrap()["result"]["content"][0]["text"]
                .as_str()
                .unwrap()
                .to_string();
            let envelope: Value = serde_json::from_str(&text).unwrap();
            assert_eq!(
                envelope["error"]["kind"], "NOT_FOUND",
                "removed finalizer must not reach a schema, profile gate, key lookup, or state handler in {profile}"
            );
            let after = serde_json::to_value(&*svc.state.project.lock().await).unwrap();
            assert_eq!(
                after, before,
                "removed finalizer mutated state in {profile}"
            );
        }
    }

    /// Fetch one orient envelope and strip the per-build noise: the
    /// envelope's `duration_ms`, the merged project's `compiled_at`
    /// (merge_projects stamps `Utc::now()`), and the replay report's
    /// snapshot hashes (they hash the merged snapshot, which embeds that
    /// timestamp). Two builds of the same frontier differ there and
    /// nowhere else.
    async fn orient_envelope_normalized(svc: &McpService) -> Value {
        let (status, body) = svc
            .handle_http(
                r#"{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"orient","arguments":{}}}"#,
            )
            .await;
        assert_eq!(status, 200);
        let body = body.unwrap();
        assert_eq!(body["result"]["isError"], false, "orient call succeeds");
        let text = body["result"]["content"][0]["text"].as_str().unwrap();
        let mut envelope: Value = serde_json::from_str(text).unwrap();
        envelope.as_object_mut().unwrap().remove("duration_ms");
        if let Some(frontier) = envelope
            .pointer_mut("/data/frontier")
            .and_then(Value::as_object_mut)
        {
            frontier.remove("compiled_at");
        }
        if let Some(replay) = envelope
            .pointer_mut("/data/verification/events/replay")
            .and_then(Value::as_object_mut)
        {
            for key in ["current_hash", "replayed_hash", "source_hash"] {
                replay.remove(key);
            }
        }
        envelope
    }

    /// The hosted-parity contract: a service hydrated from already-loaded
    /// `Project`s (the hub's DB path) must be indistinguishable from one
    /// loaded off the filesystem — same tools/list, same orient output.
    #[tokio::test]
    async fn from_projects_matches_from_named_paths() {
        let via_paths = service();

        // The DB path: load the raw project (no materialize — DB snapshots
        // are persisted un-materialized too) and hand it to from_projects.
        let project = repo::load_from_path(&fixture()).expect("fixture frontier loads raw");
        let (via_projects, warnings) = McpService::from_projects(
            vec![("erdos-formalization".to_string(), project)],
            "read-only",
            &McpService::hosted_exclusions(),
        )
        .expect("service builds from in-memory projects");
        assert!(warnings.is_empty(), "unexpected warnings: {warnings:?}");

        let list_req = r#"{"jsonrpc":"2.0","id":8,"method":"tools/list"}"#;
        let (s1, list_paths) = via_paths.handle_http(list_req).await;
        let (s2, list_projects) = via_projects.handle_http(list_req).await;
        assert_eq!(s1, 200);
        assert_eq!(s2, 200);
        assert_eq!(
            list_paths, list_projects,
            "tools/list must be identical across the two constructors"
        );

        let orient_paths = orient_envelope_normalized(&via_paths).await;
        let orient_projects = orient_envelope_normalized(&via_projects).await;
        assert_eq!(
            orient_paths, orient_projects,
            "orient output must be identical across the two constructors"
        );
    }

    #[tokio::test]
    async fn notifications_get_202_and_batches_collect() {
        let svc = service();
        let (status, body) = svc
            .handle_http(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#)
            .await;
        assert_eq!(status, 202);
        assert!(body.is_none());

        let (status, body) = svc
            .handle_http(
                r#"[{"jsonrpc":"2.0","method":"notifications/initialized"},{"jsonrpc":"2.0","id":5,"method":"ping"}]"#,
            )
            .await;
        assert_eq!(status, 200);
        assert_eq!(body.unwrap().as_array().unwrap().len(), 1);

        let (status, body) = svc.handle_http("not json").await;
        assert_eq!(status, 400);
        assert_eq!(body.unwrap()["error"]["code"], -32700);
    }
}