Skip to main content

vela_cli/server/
serve.rs

1//! Read-only MCP/HTTP frontier server.
2
3#![allow(clippy::too_many_lines)]
4
5use std::collections::{HashMap, HashSet};
6use std::io::{self, BufRead, Write};
7use std::path::{Path, PathBuf};
8use std::sync::Arc;
9
10use axum::{
11    Router,
12    routing::{get, post},
13};
14use reqwest::Client;
15use serde::Serialize;
16use serde_json::{Value, json};
17use tokio::sync::Mutex;
18use tower_http::cors::CorsLayer;
19
20use vela_edge::signals;
21use vela_edge::tool_registry;
22use vela_protocol::bundle::FindingBundle;
23use vela_protocol::project::{self, ConfidenceDistribution, Project, ProjectStats};
24use vela_protocol::repo;
25use vela_protocol::sources;
26
27use super::http::{
28    http_entries, http_entry, http_entry_events, http_entry_finding, http_entry_findings,
29    http_health, http_mcp, http_mcp_get,
30};
31use super::tools::{
32    tool_external, tool_finding, tool_graph, tool_nanopublication, tool_objects, tool_orient,
33    tool_search, tool_verify, tool_work,
34};
35pub enum ProjectSource {
36    Single(PathBuf),
37    Directory(PathBuf),
38}
39
40impl ProjectSource {
41    pub fn from_args(single: Option<&Path>, dir: Option<&Path>) -> Self {
42        if let Some(d) = dir {
43            Self::Directory(d.to_path_buf())
44        } else if let Some(s) = single {
45            Self::Single(s.to_path_buf())
46        } else {
47            eprintln!(
48                "{} provide either a frontier file or --frontiers <dir>",
49                vela_protocol::cli_style::err_prefix()
50            );
51            std::process::exit(1);
52        }
53    }
54}
55
56#[derive(Clone)]
57pub struct ProjectInfo {
58    pub name: String,
59    pub file: String,
60    pub findings_count: usize,
61    pub links_count: usize,
62    pub papers: usize,
63}
64
65pub fn load_projects(source: &ProjectSource) -> (Project, Vec<ProjectInfo>) {
66    match source {
67        ProjectSource::Single(path) => {
68            let mut frontier = repo::load_from_path(path).unwrap_or_else(|e| {
69                eprintln!(
70                    "{} failed to load frontier: {e}",
71                    vela_protocol::cli_style::err_prefix()
72                );
73                std::process::exit(1);
74            });
75            sources::materialize_project(&mut frontier);
76            let info = ProjectInfo {
77                name: frontier.project.name.clone(),
78                file: path.display().to_string(),
79                findings_count: frontier.findings.len(),
80                links_count: frontier.stats.links,
81                papers: frontier.project.papers_processed,
82            };
83            (frontier, vec![info])
84        }
85        ProjectSource::Directory(dir) => {
86            let mut entries: Vec<PathBuf> = std::fs::read_dir(dir)
87                .unwrap_or_else(|e| {
88                    eprintln!(
89                        "{} failed to read directory: {e}",
90                        vela_protocol::cli_style::err_prefix()
91                    );
92                    std::process::exit(1);
93                })
94                .filter_map(Result::ok)
95                .map(|entry| entry.path())
96                .filter(|path| {
97                    (path.is_dir() && path.join(".vela").exists())
98                        || path.extension().is_some_and(|ext| ext == "json")
99                })
100                .collect();
101            entries.sort();
102            if entries.is_empty() {
103                eprintln!("no frontier files found in {}", dir.display());
104                std::process::exit(1);
105            }
106
107            let mut named = Vec::new();
108            for path in &entries {
109                let mut frontier = repo::load_from_path(path).unwrap_or_else(|e| {
110                    eprintln!(
111                        "{} failed to load {}: {e}",
112                        vela_protocol::cli_style::err_prefix(),
113                        path.display()
114                    );
115                    std::process::exit(1);
116                });
117                sources::materialize_project(&mut frontier);
118                let name = path
119                    .file_stem()
120                    .unwrap_or_default()
121                    .to_string_lossy()
122                    .to_string();
123                named.push((name, frontier));
124            }
125            let infos = named
126                .iter()
127                .map(|(name, frontier)| ProjectInfo {
128                    name: frontier.project.name.clone(),
129                    file: name.clone(),
130                    findings_count: frontier.findings.len(),
131                    links_count: frontier.stats.links,
132                    papers: frontier.project.papers_processed,
133                })
134                .collect::<Vec<_>>();
135            (merge_projects(named), infos)
136        }
137    }
138}
139
140fn merge_projects(frontiers: Vec<(String, Project)>) -> Project {
141    let mut findings = Vec::<FindingBundle>::new();
142    let mut categories = HashMap::<String, usize>::new();
143    let mut link_types = HashMap::<String, usize>::new();
144    let mut names = Vec::new();
145    let mut papers_processed = 0usize;
146    let mut errors = 0usize;
147    // v0.36.2: preserve v0.32+ kernel objects across the merge.
148    // Pre-v0.36.2, `artifacts` were dropped during merge, leaving the
149    // merged stats incomplete.
150    let mut artifacts = Vec::new();
151
152    for (name, frontier) in frontiers {
153        names.push(name);
154        papers_processed += frontier.project.papers_processed;
155        errors += frontier.project.errors;
156        for (category, count) in frontier.stats.categories {
157            *categories.entry(category).or_default() += count;
158        }
159        for (link_type, count) in frontier.stats.link_types {
160            *link_types.entry(link_type).or_default() += count;
161        }
162        findings.extend(frontier.findings);
163        artifacts.extend(frontier.artifacts);
164    }
165
166    let mut deduped = Vec::<FindingBundle>::new();
167    let mut seen = HashMap::<String, usize>::new();
168    for finding in findings {
169        if let Some(existing) = seen.get(&finding.id).copied() {
170            if finding.confidence.score > deduped[existing].confidence.score {
171                deduped[existing] = finding;
172            }
173        } else {
174            seen.insert(finding.id.clone(), deduped.len());
175            deduped.push(finding);
176        }
177    }
178
179    let links = deduped.iter().map(|finding| finding.links.len()).sum();
180    let replicated = deduped
181        .iter()
182        .filter(|finding| finding.evidence.replicated)
183        .count();
184    let avg_confidence = if deduped.is_empty() {
185        0.0
186    } else {
187        (deduped
188            .iter()
189            .map(|finding| finding.confidence.score)
190            .sum::<f64>()
191            / deduped.len() as f64
192            * 1000.0)
193            .round()
194            / 1000.0
195    };
196    let stats = ProjectStats {
197        findings: deduped.len(),
198        links,
199        replicated,
200        unreplicated: deduped.len().saturating_sub(replicated),
201        avg_confidence,
202        gaps: deduped.iter().filter(|finding| finding.flags.gap).count(),
203        negative_space: deduped
204            .iter()
205            .filter(|finding| finding.flags.negative_space)
206            .count(),
207        contested: deduped
208            .iter()
209            .filter(|finding| finding.flags.contested)
210            .count(),
211        categories,
212        link_types,
213        human_reviewed: deduped
214            .iter()
215            .filter(|finding| {
216                finding.provenance.review.as_ref().is_some_and(|review| {
217                    review.reviewed
218                        && review
219                            .reviewer
220                            .as_deref()
221                            .map(vela_protocol::events::actor_kind)
222                            .unwrap_or("human")
223                            == "human"
224                })
225            })
226            .count(),
227        agent_reviewed: deduped
228            .iter()
229            .filter(|finding| {
230                finding.provenance.review.as_ref().is_some_and(|review| {
231                    review.reviewed
232                        && review
233                            .reviewer
234                            .as_deref()
235                            .map(vela_protocol::events::actor_kind)
236                            .unwrap_or("human")
237                            != "human"
238                })
239            })
240            .count(),
241        review_event_count: 0,
242        confidence_update_count: 0,
243        event_count: 0,
244        source_count: 0,
245        evidence_atom_count: 0,
246        condition_record_count: 0,
247        proposal_count: 0,
248        confidence_distribution: ConfidenceDistribution {
249            high_gt_80: deduped
250                .iter()
251                .filter(|finding| finding.confidence.score > 0.8)
252                .count(),
253            medium_60_80: deduped
254                .iter()
255                .filter(|finding| (0.6..=0.8).contains(&finding.confidence.score))
256                .count(),
257            low_lt_60: deduped
258                .iter()
259                .filter(|finding| finding.confidence.score < 0.6)
260                .count(),
261        },
262    };
263
264    let mut project = Project {
265        vela_version: project::VELA_SCHEMA_VERSION.to_string(),
266        schema: project::VELA_SCHEMA_URL.to_string(),
267        frontier_id: None,
268        project: project::ProjectMeta {
269            name: format!("merged: {}", names.join(", ")),
270            description: format!("Merged from {} frontiers", names.len()),
271            compiled_at: chrono::Utc::now().to_rfc3339(),
272            compiler: project::VELA_COMPILER_VERSION.to_string(),
273            papers_processed,
274            errors,
275            dependencies: Vec::new(),
276        },
277        stats,
278        findings: deduped,
279        sources: Vec::new(),
280        evidence_atoms: Vec::new(),
281        condition_records: Vec::new(),
282        review_events: Vec::new(),
283        confidence_updates: Vec::new(),
284        events: Vec::new(),
285        proposals: Vec::new(),
286        proof_state: Default::default(),
287        signatures: Vec::new(),
288        actors: Vec::new(),
289        artifacts,
290        released_diff_packs: Vec::new(),
291        verdict_conflicts: Vec::new(),
292        contradictions: Vec::new(),
293        verifier_attachments: Vec::new(),
294        attempts: Vec::new(),
295        attempt_resolutions: Vec::new(),
296        transfers: Vec::new(),
297        endorsements: Vec::new(),
298        statement_attestations: Vec::new(),
299        anchor_links: Vec::new(),
300        attempt_claims: Vec::new(),
301        statement_registrations: Vec::new(),
302    };
303    sources::materialize_project(&mut project);
304    project
305}
306
307pub async fn run(
308    source: ProjectSource,
309    _backend: Option<&str>,
310    profile: tool_registry::McpProfile,
311) {
312    // No working-tree .env: serve runs inside cloned frontier checkouts
313    // (see run_command's note on the injection class).
314    let (frontier, project_infos) = load_projects(&source);
315    let source_path: Option<PathBuf> = match &source {
316        ProjectSource::Single(path) => Some(path.clone()),
317        ProjectSource::Directory(_) => None,
318    };
319    let state = AppState {
320        project: Arc::new(Mutex::new(frontier)),
321        project_infos,
322        client: Client::new(),
323        profile,
324        source_path,
325    };
326    let no_exclusions = HashSet::new();
327    let stdin = io::stdin();
328    let stdout = io::stdout();
329
330    for line in stdin.lock().lines() {
331        let Ok(line) = line else {
332            break;
333        };
334        if line.trim().is_empty() {
335            continue;
336        }
337        let Ok(request) = serde_json::from_str::<Value>(&line) else {
338            continue;
339        };
340        let Some(response) = rpc_dispatch(&request, &state, &no_exclusions).await else {
341            continue;
342        };
343        let mut out = stdout.lock();
344        let _ = serde_json::to_writer(&mut out, &response);
345        let _ = out.write_all(b"\n");
346        let _ = out.flush();
347    }
348}
349
350/// The one JSON-RPC dispatcher behind every MCP transport: the stdio line
351/// loop, the `/mcp` streamable-HTTP route, and the hub's hosted endpoint
352/// (via `McpService`). `None` means the message was a notification and no
353/// response is owed. `excluded` names tools withheld from this transport
354/// (the hosted endpoint drops the filesystem-path `vela_*` family); the
355/// exclusion applies to both `tools/list` and `tools/call`.
356async fn rpc_dispatch(request: &Value, st: &AppState, excluded: &HashSet<String>) -> Option<Value> {
357    let id = request.get("id").cloned();
358    let method = request["method"].as_str().unwrap_or_default();
359    if method.starts_with("notifications/") {
360        return None;
361    }
362    Some(match method {
363        "initialize" => {
364            // Stateless JSON either way, so echo the client's requested
365            // protocol version; default to the widely-supported baseline.
366            let requested = request["params"]["protocolVersion"]
367                .as_str()
368                .unwrap_or("2024-11-05");
369            json_rpc_result(
370                &id,
371                json!({
372                    "protocolVersion": requested,
373                    "capabilities": {"tools": {}},
374                    "serverInfo": {"name": "vela", "version": project::VELA_SCHEMA_VERSION}
375                }),
376            )
377        }
378        "tools/list" => {
379            let mut tools = tool_registry::mcp_tools_json_for_profile(st.profile);
380            if !excluded.is_empty()
381                && let Some(arr) = tools.as_array_mut()
382            {
383                arr.retain(|t| t["name"].as_str().is_none_or(|n| !excluded.contains(n)));
384            }
385            json_rpc_result(&id, json!({"tools": tools}))
386        }
387        "tools/call" => {
388            let name = request["params"]["name"].as_str().unwrap_or_default();
389            let args = request["params"]["arguments"].clone();
390            if excluded.contains(name) {
391                let available: Vec<String> = tool_registry::tools_for_profile(st.profile)
392                    .into_iter()
393                    .map(|t| t.name)
394                    .filter(|n| !excluded.contains(n))
395                    .collect();
396                json_rpc_error(
397                    &id,
398                    -32602,
399                    &format!(
400                        "`{name}` is not served on this hosted endpoint (it operates on \
401                         local filesystem paths); clone the frontier repo and run it \
402                         there. Tools available here: {}",
403                        available.join(", ")
404                    ),
405                )
406            } else if let Some(err) = profile_gate(name, st.profile) {
407                ToolResult::failure(name, err, 0).to_rpc(&id)
408            } else {
409                handle_tool_call(
410                    &id,
411                    name,
412                    &args,
413                    &st.project,
414                    &st.client,
415                    &st.project_infos,
416                    st.source_path.as_deref(),
417                )
418                .await
419            }
420        }
421        "ping" => json_rpc_result(&id, json!({})),
422        _ => json_rpc_error(&id, -32601, "Method not found"),
423    })
424}
425
426/// One streamable-HTTP MCP exchange (stateless JSON responses; no
427/// server-initiated SSE). Accepts a single JSON-RPC message or a batch
428/// array. Returns `(http_status, body)`; `None` body means an empty 202
429/// (the message was all notifications).
430pub(crate) async fn mcp_http_exchange(
431    body: &str,
432    st: &AppState,
433    excluded: &HashSet<String>,
434) -> (u16, Option<Value>) {
435    let Ok(message) = serde_json::from_str::<Value>(body) else {
436        return (
437            400,
438            Some(json!({
439                "jsonrpc": "2.0", "id": null,
440                "error": {"code": -32700, "message": "Parse error"}
441            })),
442        );
443    };
444    if let Some(batch) = message.as_array() {
445        let mut responses = Vec::new();
446        for request in batch {
447            if let Some(response) = rpc_dispatch(request, st, excluded).await {
448                responses.push(response);
449            }
450        }
451        if responses.is_empty() {
452            (202, None)
453        } else {
454            (200, Some(Value::Array(responses)))
455        }
456    } else {
457        match rpc_dispatch(&message, st, excluded).await {
458            Some(response) => (200, Some(response)),
459            None => (202, None),
460        }
461    }
462}
463
464/// A hosted, in-process MCP service over named frontier checkouts. The hub
465/// embeds this to serve `hub.constellate.science/mcp` without a sidecar:
466/// the same dispatcher, profile gate, and tool registry as `vela serve`,
467/// loaded from the git checkouts its ingest lane already maintains.
468pub struct McpService {
469    state: AppState,
470    excluded: HashSet<String>,
471}
472
473impl McpService {
474    /// Load named frontier directories into one merged read-only service.
475    /// A broken entry is skipped and reported in the returned warnings,
476    /// never fatal: one frontier failing to replay must not take the
477    /// hosted endpoint down for the rest. Loading is the only filesystem
478    /// touch; the merge itself is `from_projects`.
479    pub fn from_named_paths(
480        entries: &[(String, PathBuf)],
481        profile_str: &str,
482        exclude: &[String],
483    ) -> Result<(Self, Vec<String>), String> {
484        let mut loaded = Vec::new();
485        let mut warnings = Vec::new();
486        for (name, path) in entries {
487            match repo::load_from_path(path) {
488                Ok(frontier) => loaded.push((name.clone(), frontier)),
489                Err(e) => warnings.push(format!("{name}: {e}")),
490            }
491        }
492        if loaded.is_empty() {
493            return Err(format!(
494                "no loadable frontier among {} entries: {}",
495                entries.len(),
496                warnings.join(" | ")
497            ));
498        }
499        let (service, more) = Self::from_projects(loaded, profile_str, exclude)?;
500        warnings.extend(more);
501        Ok((service, warnings))
502    }
503
504    /// Build the merged read-only service from already-loaded projects —
505    /// the path the hub's DB-hydrated refresher uses (no filesystem at
506    /// all). Each project is re-materialized here: promoted DB snapshots
507    /// were persisted WITHOUT `materialize_project`, so skipping it would
508    /// diverge from the checkout loader's output.
509    pub fn from_projects(
510        entries: Vec<(String, Project)>,
511        profile_str: &str,
512        exclude: &[String],
513    ) -> Result<(Self, Vec<String>), String> {
514        let profile = tool_registry::McpProfile::parse(profile_str)?;
515        if entries.is_empty() {
516            return Err("no frontier projects to serve".to_string());
517        }
518        let mut named = Vec::with_capacity(entries.len());
519        for (name, mut frontier) in entries {
520            sources::materialize_project(&mut frontier);
521            named.push((name, frontier));
522        }
523        let project_infos = named
524            .iter()
525            .map(|(name, frontier)| ProjectInfo {
526                name: frontier.project.name.clone(),
527                file: name.clone(),
528                findings_count: frontier.findings.len(),
529                links_count: frontier.stats.links,
530                papers: frontier.project.papers_processed,
531            })
532            .collect();
533        let project = merge_projects(named);
534        Ok((
535            Self {
536                state: AppState {
537                    project: Arc::new(Mutex::new(project)),
538                    project_infos,
539                    client: Client::new(),
540                    profile,
541                    source_path: None,
542                },
543                excluded: exclude.iter().cloned().collect(),
544            },
545            Vec::new(),
546        ))
547    }
548
549    /// The hosted exclusion set: every tool that operates on a
550    /// caller-supplied filesystem path. On a public endpoint those are
551    /// useless at best (the caller has no paths on the server) and a CPU
552    /// sink at worst (`verify` with mode=witness). The hosted endpoint runs
553    /// the read-only profile, so its `tools/list` is the read-only surface
554    /// minus these three: orient, finding, search, graph, external.
555    pub fn hosted_exclusions() -> Vec<String> {
556        ["verify", "work", "objects"]
557            .into_iter()
558            .map(str::to_string)
559            .collect()
560    }
561
562    /// Handle one streamable-HTTP MCP exchange (single message or batch).
563    /// Returns `(http_status, body)`; `None` body = empty 202.
564    pub async fn handle_http(&self, body: &str) -> (u16, Option<Value>) {
565        mcp_http_exchange(body, &self.state, &self.excluded).await
566    }
567
568    /// The loaded frontier labels, for the hub's status surfaces.
569    pub fn frontier_labels(&self) -> Vec<String> {
570        self.state
571            .project_infos
572            .iter()
573            .map(|i| format!("{} ({})", i.name, i.file))
574            .collect()
575    }
576}
577
578pub async fn run_http(
579    source: ProjectSource,
580    backend: Option<&str>,
581    port: u16,
582    profile: tool_registry::McpProfile,
583) {
584    let _ = backend;
585    // No working-tree .env: serve runs inside cloned frontier checkouts
586    // (see run_command's note on the injection class).
587    let (frontier, project_infos) = load_projects(&source);
588    let source_path = match &source {
589        ProjectSource::Single(path) => Some(path.clone()),
590        ProjectSource::Directory(_) => None,
591    };
592    let state = AppState {
593        project: Arc::new(Mutex::new(frontier)),
594        project_infos,
595        client: Client::new(),
596        profile,
597        source_path,
598    };
599
600    // One HTTP shape: the read surface mirrors the hub's `/entries/{vfr}/…`
601    // paths for the concepts serve supports, and `/mcp` at the root is the
602    // tool surface. The literal segment `self` names the served frontier;
603    // its real vfr_ id (or a prefix) is accepted too.
604    let app = Router::new()
605        .route("/health", get(http_health))
606        .route("/healthz", get(http_health))
607        .route("/entries", get(http_entries))
608        .route("/entries/{vfr}", get(http_entry))
609        .route("/entries/{vfr}/findings", get(http_entry_findings))
610        .route("/entries/{vfr}/findings/{id}", get(http_entry_finding))
611        .route("/entries/{vfr}/events", get(http_entry_events))
612        // Streamable-HTTP MCP (stateless JSON): the same dispatcher as
613        // stdio, so any remote MCP client can connect without a clone.
614        .route("/mcp", post(http_mcp).get(http_mcp_get));
615
616    // Explicit request-body cap for THREAT_MODEL.md A13. Axum's default body
617    // limit is 2 MiB; 8 MiB accommodates ordinary MCP and Receipt envelopes
618    // while refusing unbounded inputs. Pin it so a future Axum default change
619    // cannot silently expose the surface. Localhost-only deploys
620    // are bounded by this limit; remote deploys behind a reverse
621    // proxy should layer rate limiting on top (the substrate does
622    // not enforce per-actor or per-IP request budgets).
623    let app = app
624        .layer(axum::extract::DefaultBodyLimit::max(8 * 1024 * 1024))
625        .layer(CorsLayer::permissive())
626        .with_state(state);
627
628    let addr = format!("0.0.0.0:{port}");
629    eprintln!(
630        "  {}",
631        format!("VELA · SERVE · HTTP :{port}").to_uppercase()
632    );
633    eprintln!("  {}", vela_protocol::cli_style::tick_row(60));
634    eprintln!("  listening on http://{addr}");
635    // Full endpoint enumeration so a fresh user opening `vela serve --http`
636    // knows what they can hit. `self` names the served frontier; its real
637    // vfr_ id works too.
638    eprintln!("  endpoints:");
639    eprintln!("    health:    GET  /health  /healthz");
640    eprintln!("    entries:   GET  /entries                          (single-element list)");
641    eprintln!("               GET  /entries/self                     (frontier summary)");
642    eprintln!("               GET  /entries/self/findings            (?query= to search)");
643    eprintln!("               GET  /entries/self/findings/{{id}}");
644    eprintln!("               GET  /entries/self/events?cursor=&limit=");
645    eprintln!("    tools:     POST /mcp   (streamable-HTTP MCP; the tool surface)");
646    let listener = tokio::net::TcpListener::bind(&addr)
647        .await
648        .unwrap_or_else(|e| {
649            eprintln!(
650                "{} failed to bind to {addr}: {e}",
651                vela_protocol::cli_style::err_prefix()
652            );
653            std::process::exit(1);
654        });
655    axum::serve(listener, app).await.unwrap();
656}
657
658pub fn check_tools(source: ProjectSource, adoption: bool) -> Result<Value, String> {
659    let started = std::time::Instant::now();
660    let source_label = match &source {
661        ProjectSource::Single(path) => path.display().to_string(),
662        ProjectSource::Directory(path) => path.display().to_string(),
663    };
664    let source_path = match &source {
665        ProjectSource::Single(p) => Some(p.as_path()),
666        ProjectSource::Directory(p) => Some(p.as_path()),
667    };
668    let (frontier, _project_infos) = load_projects(&source);
669    let first_id = frontier.findings.first().map(|finding| finding.id.clone());
670    let mut checks = vec![
671        check_tool_result(
672            "orient",
673            tool_orient(&json!({}), &frontier, source_path),
674            started,
675        ),
676        check_tool_result(
677            "search",
678            tool_search(&json!({"query": "Sidon", "limit": 3}), &frontier),
679            started,
680        ),
681        check_tool_result("graph", tool_graph(&json!({}), &frontier), started),
682        check_tool_result(
683            "graph",
684            tool_graph(&json!({"mode": "contradictions"}), &frontier),
685            started,
686        ),
687    ];
688    if let Some(id) = first_id {
689        checks.push(check_tool_result(
690            "finding",
691            tool_finding(
692                &json!({"id": id, "include": ["history", "dependents", "neighborhood"]}),
693                &frontier,
694            ),
695            started,
696        ));
697        checks.push(check_tool_result(
698            "orient",
699            tool_orient(&json!({"problem": id}), &frontier, source_path),
700            started,
701        ));
702        checks.push(check_tool_result(
703            "graph",
704            tool_graph(
705                &json!({"root": id, "mode": "traverse", "max_hops": 3}),
706                &frontier,
707            ),
708            started,
709        ));
710        checks.push(check_tool_result(
711            "graph",
712            tool_graph(&json!({"root": id, "mode": "impact"}), &frontier),
713            started,
714        ));
715        checks.push(check_tool_result(
716            "external",
717            parse_payload(tool_nanopublication(&json!({"finding_id": id}), &frontier))
718                .map(|v| (v, Vec::new())),
719            started,
720        ));
721    }
722    let failures = checks
723        .iter()
724        .filter(|check| check.get("ok").and_then(Value::as_bool) != Some(true))
725        .filter_map(|check| {
726            check
727                .get("tool")
728                .and_then(Value::as_str)
729                .map(str::to_string)
730        })
731        .collect::<Vec<_>>();
732    let checked_tools = checks
733        .iter()
734        .filter_map(|check| check.get("tool").and_then(Value::as_str))
735        .map(str::to_string)
736        .collect::<Vec<_>>();
737    let registered_tools = tool_registry::all_tools()
738        .into_iter()
739        .map(|tool| tool.name)
740        .collect::<Vec<_>>();
741    let adoption_report = adoption.then(|| adoption_tool_report(&checks, &source_label));
742
743    Ok(json!({
744        "ok": failures.is_empty(),
745        "command": if adoption { "serve --check-tools --adoption" } else { "serve --check-tools" },
746        "schema": "vela.tool-check.v0",
747        "frontier": {
748            "name": frontier.project.name,
749            "findings": frontier.stats.findings,
750            "links": frontier.stats.links,
751        },
752        "summary": {
753            "checks": checks.len(),
754            "passed": checks.len().saturating_sub(failures.len()),
755            "failed": failures.len(),
756        },
757        "tool_count": checked_tools.len(),
758        "tools": checked_tools,
759        "registered_tool_count": registered_tools.len(),
760        "registered_tools": registered_tools,
761        "checks": checks,
762        "failures": failures,
763        "adoption": adoption_report,
764    }))
765}
766
767fn adoption_tool_report(checks: &[Value], source_label: &str) -> Value {
768    let required_tools = vec!["orient", "search", "finding", "graph"];
769    let missing_or_failed = required_tools
770        .iter()
771        .filter(|tool| {
772            !checks.iter().any(|check| {
773                check.get("tool").and_then(Value::as_str) == Some(**tool)
774                    && check.get("ok").and_then(Value::as_bool) == Some(true)
775            })
776        })
777        .copied()
778        .collect::<Vec<_>>();
779    json!({
780        "ok": missing_or_failed.is_empty(),
781        "required_tools": required_tools,
782        "missing_or_failed": missing_or_failed,
783        "mcp_config": {
784            "mcpServers": {
785                "vela": {
786                    "command": "vela",
787                    "args": ["serve", source_label]
788                }
789            }
790        },
791        "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.",
792        "commands": [
793            format!("vela serve {source_label} --check-tools --adoption --json"),
794            format!("vela serve {source_label}")
795        ],
796    })
797}
798
799#[derive(Clone)]
800pub(crate) struct AppState {
801    pub(crate) project: Arc<Mutex<Project>>,
802    pub(crate) project_infos: Vec<ProjectInfo>,
803    pub(crate) client: Client,
804    /// MCP exposure profile (memo §9.1). Scopes which tools `tools/list`
805    /// exposes and `tools/call` will execute. Defaults to read-only.
806    pub(crate) profile: tool_registry::McpProfile,
807    /// Phase Q-w (v0.5): when serving a single frontier file, this is
808    /// the path to write back to after a successful signed write. None
809    /// when `--frontiers <dir>` is used; in that mode all writes are
810    /// rejected.
811    pub(crate) source_path: Option<PathBuf>,
812}
813
814/// Structured tool-error kinds. One closed set for every transport: the MCP
815/// envelope and both HTTP servers speak `{kind, message, hint?}`.
816#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
817pub(crate) enum ToolErrorKind {
818    #[serde(rename = "NOT_FOUND")]
819    NotFound,
820    #[serde(rename = "INVALID_ARG")]
821    InvalidArg,
822    #[serde(rename = "PERMISSION_DENIED")]
823    PermissionDenied,
824    #[serde(rename = "INTERNAL")]
825    Internal,
826}
827
828#[derive(Debug, Clone, Serialize)]
829pub(crate) struct ToolError {
830    pub(crate) kind: ToolErrorKind,
831    pub(crate) message: String,
832    #[serde(skip_serializing_if = "Option::is_none")]
833    pub(crate) hint: Option<String>,
834}
835
836impl ToolError {
837    pub(crate) fn new(kind: ToolErrorKind, message: impl Into<String>) -> Self {
838        Self {
839            kind,
840            message: message.into(),
841            hint: None,
842        }
843    }
844
845    pub(crate) fn not_found(message: impl Into<String>) -> Self {
846        Self::new(ToolErrorKind::NotFound, message)
847    }
848
849    pub(crate) fn invalid(message: impl Into<String>) -> Self {
850        Self::new(ToolErrorKind::InvalidArg, message)
851    }
852
853    pub(crate) fn internal(message: impl Into<String>) -> Self {
854        Self::new(ToolErrorKind::Internal, message)
855    }
856
857    pub(crate) fn with_hint(mut self, hint: impl Into<String>) -> Self {
858        self.hint = Some(hint.into());
859        self
860    }
861
862    /// Classify a prose error from an underlying impl. The impls predate the
863    /// kind vocabulary, so this is a boundary heuristic: id/file lookups read
864    /// as NOT_FOUND, argument shapes as INVALID_ARG, everything else INTERNAL.
865    pub(crate) fn classify(message: String) -> Self {
866        let lc = message.to_lowercase();
867        let kind = if lc.contains("not found")
868            || lc.contains("no finding resolves")
869            || lc.contains("is not registered")
870            || lc.contains("no such file")
871            || lc.contains("is neither a finding")
872        {
873            ToolErrorKind::NotFound
874        } else if lc.contains("required")
875            || lc.contains("missing")
876            || lc.contains("must be")
877            || lc.contains("must start")
878            || lc.contains("must include")
879            || lc.contains("must contain")
880            || lc.contains("invalid")
881            || lc.contains("unknown edge kind")
882            || lc.contains("out of [0.0, 1.0]")
883            || lc.contains("is for agent:/ci: actors")
884        {
885            ToolErrorKind::InvalidArg
886        } else {
887            ToolErrorKind::Internal
888        };
889        Self::new(kind, message)
890    }
891}
892
893/// The one result envelope every tool call returns, as a single JSON text
894/// block: `{tool, ok, data, notes?, error?, signals, caveats, duration_ms}`.
895/// No markdown duplication — `data` is the payload, `notes` carries
896/// truncation and degradation notices, `error` carries `{kind, message,
897/// hint?}` on failure.
898#[derive(Debug, Clone, Serialize)]
899struct ToolResult {
900    tool: String,
901    ok: bool,
902    data: Value,
903    #[serde(skip_serializing_if = "Vec::is_empty")]
904    notes: Vec<String>,
905    #[serde(skip_serializing_if = "Option::is_none")]
906    error: Option<ToolError>,
907    signals: Vec<signals::SignalItem>,
908    caveats: Vec<String>,
909    duration_ms: u128,
910}
911
912impl ToolResult {
913    fn success(
914        tool: &str,
915        data: Value,
916        notes: Vec<String>,
917        duration_ms: u128,
918        frontier: Option<&Project>,
919    ) -> Self {
920        let signal_items = frontier
921            .map(|project| signals::analyze(project, &[]).signals)
922            .unwrap_or_default();
923        Self {
924            tool: tool.to_string(),
925            ok: true,
926            data,
927            notes,
928            error: None,
929            signals: signal_items,
930            caveats: tool_registry::tool_caveats(tool),
931            duration_ms,
932        }
933    }
934
935    fn failure(tool: &str, error: ToolError, duration_ms: u128) -> Self {
936        Self {
937            tool: tool.to_string(),
938            ok: false,
939            data: Value::Null,
940            notes: Vec::new(),
941            error: Some(error),
942            signals: Vec::new(),
943            caveats: tool_registry::tool_caveats(tool),
944            duration_ms,
945        }
946    }
947
948    fn metadata(&self) -> Value {
949        json!({
950            "tool": self.tool,
951            "ok": self.ok,
952            "duration_ms": self.duration_ms,
953            "caveats": self.caveats,
954        })
955    }
956
957    fn to_json_text(&self) -> String {
958        serde_json::to_string_pretty(self).unwrap_or_else(|_| "{}".to_string())
959    }
960
961    fn to_rpc(&self, id: &Option<Value>) -> Value {
962        let mut result = json!({
963            "content": [{"type": "text", "text": self.to_json_text()}],
964            "isError": !self.ok,
965            "_meta": self.metadata()
966        });
967        // Structured output (MCP 2025-06): when the tool declares an
968        // outputSchema, mirror the result `data` as `structuredContent` so
969        // typed clients read a validated object instead of parsing JSON out
970        // of the text block. The text block stays for older clients.
971        if self.ok && tool_registry::tool_output_schema(&self.tool).is_some() {
972            result["structuredContent"] = self.data.clone();
973        }
974        json_rpc_result(id, result)
975    }
976}
977
978/// MCP profile gate (memo §9.4): refuse to execute a tool the active profile
979/// does not admit, returning a structured error envelope. `None` means the
980/// call may proceed (allowed, or unknown — the dispatch then returns its own
981/// NOT_FOUND). This is the execution boundary; `tools/list` already hides the
982/// tool, but a client could still call it by name.
983fn profile_gate(name: &str, profile: tool_registry::McpProfile) -> Option<ToolError> {
984    let tool = tool_registry::get_tool(name)?;
985    if profile.allows(&tool) {
986        return None;
987    }
988    let hint = if tool_registry::McpProfile::Draft.allows(&tool) {
989        "restart `vela serve` with `--profile draft` for non-finalizing draft/work capabilities; human finalization is unavailable through MCP and remains terminal-only (`vela sign`)"
990    } else {
991        "this capability is unavailable through MCP"
992    };
993    Some(
994        ToolError::new(
995            ToolErrorKind::PermissionDenied,
996            format!(
997                "tool `{name}` ({}) is not available in the `{}` MCP profile",
998                tool.permission_level,
999                profile.as_str()
1000            ),
1001        )
1002        .with_hint(hint),
1003    )
1004}
1005
1006async fn handle_tool_call(
1007    id: &Option<Value>,
1008    name: &str,
1009    args: &Value,
1010    frontier: &Arc<Mutex<Project>>,
1011    client: &Client,
1012    project_infos: &[ProjectInfo],
1013    source_path: Option<&Path>,
1014) -> Value {
1015    let started = std::time::Instant::now();
1016    let (result, snapshot) =
1017        execute_tool(name, args, frontier, client, project_infos, source_path).await;
1018    let elapsed = started.elapsed().as_millis();
1019    match result {
1020        Ok((data, notes)) => {
1021            ToolResult::success(name, data, notes, elapsed, snapshot.as_ref()).to_rpc(id)
1022        }
1023        Err(error) => ToolResult::failure(name, error, elapsed).to_rpc(id),
1024    }
1025}
1026
1027/// Every tool call resolves to `(data, notes)` or a typed error. `notes`
1028/// carries truncation and degradation notices for the envelope.
1029pub(crate) type ToolOutput = Result<(Value, Vec<String>), ToolError>;
1030
1031/// Parse an underlying impl's JSON-string result into the envelope's `data`,
1032/// classifying prose errors into the kind vocabulary at the boundary.
1033pub(crate) fn parse_payload(result: Result<String, String>) -> Result<Value, ToolError> {
1034    let text = result.map_err(ToolError::classify)?;
1035    serde_json::from_str(&text)
1036        .map_err(|e| ToolError::internal(format!("tool payload did not parse as JSON: {e}")))
1037}
1038
1039pub(crate) fn clamp_limit(args: &Value, default: u64, max: u64) -> usize {
1040    args.get("limit")
1041        .and_then(Value::as_u64)
1042        .unwrap_or(default)
1043        .clamp(1, max) as usize
1044}
1045
1046/// Decode an opaque list cursor (an offset into the stable result order,
1047/// issued by a previous response's `next_cursor`).
1048pub(crate) fn decode_cursor(args: &Value) -> Result<usize, ToolError> {
1049    match args.get("cursor").and_then(Value::as_str) {
1050        None => Ok(0),
1051        Some(c) => c.parse::<usize>().map_err(|_| {
1052            ToolError::invalid(format!("cursor '{c}' is not a cursor this server issued"))
1053                .with_hint("pass a previous response's next_cursor back unchanged")
1054        }),
1055    }
1056}
1057
1058/// Reload the served read snapshot after a successful path-bound write.
1059///
1060/// The cache lock is acquired *before* reading disk. Otherwise an earlier
1061/// writer can read its old postimage, pause, and overwrite the cache after a
1062/// later writer has already installed a newer snapshot. Holding the lock over
1063/// reload makes cache installation follow disk observation monotonically,
1064/// while the durable frontier transaction remains the write authority.
1065pub(crate) async fn reload_served_project(
1066    frontier: &Arc<Mutex<Project>>,
1067    path: &Path,
1068) -> Result<Project, String> {
1069    let mut cached = frontier.lock().await;
1070    let mut fresh = repo::load_from_path(path)?;
1071    sources::materialize_project(&mut fresh);
1072    let snapshot = clone_project(&fresh);
1073    *cached = fresh;
1074    Ok(snapshot)
1075}
1076
1077async fn execute_tool(
1078    name: &str,
1079    args: &Value,
1080    frontier: &Arc<Mutex<Project>>,
1081    client: &Client,
1082    _project_infos: &[ProjectInfo],
1083    source_path: Option<&Path>,
1084) -> (ToolOutput, Option<Project>) {
1085    match name {
1086        "orient" => {
1087            let project = {
1088                let cached = frontier.lock().await;
1089                clone_project(&cached)
1090            };
1091            let output = tool_orient(args, &project, source_path);
1092            (output, Some(clone_project(&project)))
1093        }
1094        "finding" => {
1095            let project = frontier.lock().await;
1096            (tool_finding(args, &project), Some(clone_project(&project)))
1097        }
1098        "search" => {
1099            let project = frontier.lock().await;
1100            (tool_search(args, &project), Some(clone_project(&project)))
1101        }
1102        "graph" => {
1103            let project = frontier.lock().await;
1104            (tool_graph(args, &project), Some(clone_project(&project)))
1105        }
1106        "verify" => (tool_verify(args, source_path), None),
1107        "work" => {
1108            let result = tool_work(args, source_path);
1109            match result {
1110                Ok((data, mut notes)) => {
1111                    let Some(path) = source_path else {
1112                        // `tool_work` rejects this mode before writing; keep a
1113                        // defensive guard here so a future action cannot make
1114                        // a merged service writable by accident.
1115                        return (
1116                            Err(ToolError::new(
1117                                ToolErrorKind::PermissionDenied,
1118                                "work writes are unavailable without one configured frontier",
1119                            )),
1120                            None,
1121                        );
1122                    };
1123                    match reload_served_project(frontier, path).await {
1124                        Ok(snapshot) => (Ok((data, notes)), Some(snapshot)),
1125                        Err(error) => {
1126                            // Preserve the successful write result (including
1127                            // its operation/publication identifiers) while
1128                            // making the stale read surface explicit.
1129                            notes.push(format!(
1130                                "write completed, but the MCP snapshot reload failed; reconnect before reading: {error}"
1131                            ));
1132                            (Ok((data, notes)), None)
1133                        }
1134                    }
1135                }
1136                Err(error) => (Err(error), None),
1137            }
1138        }
1139        "objects" => (tool_objects(args, source_path), None),
1140        "external" => {
1141            let project = frontier.lock().await;
1142            (
1143                tool_external(args, &project, client).await,
1144                Some(clone_project(&project)),
1145            )
1146        }
1147        _ => {
1148            let known: Vec<String> = tool_registry::all_tools()
1149                .into_iter()
1150                .map(|t| t.name)
1151                .collect();
1152            (
1153                Err(ToolError::not_found(format!("unknown tool `{name}`"))
1154                    .with_hint(format!("this server exposes: {}", known.join(", ")))),
1155                None,
1156            )
1157        }
1158    }
1159}
1160
1161fn check_tool_result(name: &str, result: ToolOutput, started: std::time::Instant) -> Value {
1162    let duration_ms = started.elapsed().as_millis();
1163    match result {
1164        Ok((data, notes)) => {
1165            let has_data = !data.is_null();
1166            json!({
1167                "tool": name,
1168                "ok": has_data,
1169                "data": data,
1170                "notes": notes,
1171                "has_data": has_data,
1172                "caveats": tool_registry::tool_caveats(name),
1173                "duration_ms": duration_ms,
1174            })
1175        }
1176        Err(error) => json!({
1177            "tool": name,
1178            "ok": false,
1179            "data": Value::Null,
1180            "error": error,
1181            "caveats": tool_registry::tool_caveats(name),
1182            "duration_ms": duration_ms,
1183        }),
1184    }
1185}
1186
1187fn clone_project(project: &Project) -> Project {
1188    serde_json::from_value(serde_json::to_value(project).unwrap_or_default()).unwrap_or_else(|_| {
1189        project::assemble("unavailable", Vec::new(), 0, 1, "failed to clone frontier")
1190    })
1191}
1192
1193fn json_rpc_result(id: &Option<Value>, result: Value) -> Value {
1194    json!({"jsonrpc": "2.0", "id": id, "result": result})
1195}
1196
1197fn json_rpc_error(id: &Option<Value>, code: i32, message: &str) -> Value {
1198    json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}})
1199}
1200
1201#[cfg(test)]
1202mod mcp_service_tests {
1203    use super::*;
1204
1205    fn fixture() -> PathBuf {
1206        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../examples/erdos-formalization")
1207    }
1208
1209    fn work_fixture(root: &Path) -> PathBuf {
1210        let path = root.join("work-frontier");
1211        let mut project = vela_protocol::project::assemble("scope", vec![], 0, 0, "test");
1212        let event =
1213            vela_protocol::events::new_finding_event(vela_protocol::events::FindingEventInput {
1214                kind: "attempt.claimed",
1215                finding_id: "scope:probe",
1216                actor_id: "agent:owner",
1217                actor_type: "agent",
1218                reason: "scope test",
1219                before_hash: "sha256:null",
1220                after_hash: "sha256:null",
1221                payload: json!({
1222                    "obligation_id": "scope:probe",
1223                    "lease_ttl_seconds": 60,
1224                    "claimant_actor": "agent:owner",
1225                    "claimant_pubkey": "test"
1226                }),
1227                caveats: Vec::new(),
1228                timestamp: Some("2026-07-13T00:00:00Z"),
1229            });
1230        vela_protocol::reducer::apply_event(&mut project, &event).unwrap();
1231        project.events.push(event);
1232        vela_protocol::repo::init_repo(&path, &project).unwrap();
1233        let session = crate::workflow::session_dir(&path, "scope:probe");
1234        std::fs::create_dir_all(&session).unwrap();
1235        std::fs::write(session.join("producer-scratch.txt"), "fixture\n").unwrap();
1236        path
1237    }
1238
1239    fn service() -> McpService {
1240        let entries = vec![("erdos-formalization".to_string(), fixture())];
1241        let (service, warnings) =
1242            McpService::from_named_paths(&entries, "read-only", &McpService::hosted_exclusions())
1243                .expect("fixture frontier loads");
1244        assert!(warnings.is_empty(), "unexpected warnings: {warnings:?}");
1245        service
1246    }
1247
1248    #[tokio::test]
1249    async fn initialize_echoes_protocol_version_and_lists_filtered_tools() {
1250        let svc = service();
1251        let (status, body) = svc
1252            .handle_http(
1253                r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#,
1254            )
1255            .await;
1256        assert_eq!(status, 200);
1257        let body = body.unwrap();
1258        assert_eq!(body["result"]["protocolVersion"], "2025-06-18");
1259
1260        let (status, body) = svc
1261            .handle_http(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#)
1262            .await;
1263        assert_eq!(status, 200);
1264        let tools = body.unwrap()["result"]["tools"].clone();
1265        let names: Vec<String> = tools
1266            .as_array()
1267            .unwrap()
1268            .iter()
1269            .map(|t| t["name"].as_str().unwrap().to_string())
1270            .collect();
1271        // Hosted = the read-only profile minus the path-bound exclusions:
1272        // exactly these five.
1273        assert_eq!(
1274            names,
1275            vec!["orient", "finding", "search", "graph", "external"],
1276            "hosted tools/list is the read-only surface minus verify/work/objects"
1277        );
1278    }
1279
1280    #[tokio::test]
1281    async fn tool_call_returns_envelope_and_excluded_tool_is_refused_by_name() {
1282        let svc = service();
1283        let (status, body) = svc
1284            .handle_http(
1285                r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"orient","arguments":{}}}"#,
1286            )
1287            .await;
1288        assert_eq!(status, 200);
1289        let body = body.unwrap();
1290        assert_eq!(body["result"]["isError"], false, "orient call succeeds");
1291        // The one JSON text block: {tool, ok, data, notes?, signals,
1292        // caveats, duration_ms} — and no markdown duplication.
1293        let text = body["result"]["content"][0]["text"].as_str().unwrap();
1294        let envelope: Value = serde_json::from_str(text).unwrap();
1295        assert_eq!(envelope["tool"], "orient");
1296        assert_eq!(envelope["ok"], true);
1297        assert!(envelope["data"].is_object(), "data payload present");
1298        assert!(envelope.get("markdown").is_none(), "no markdown field");
1299        assert!(envelope["duration_ms"].is_number());
1300
1301        let (status, body) = svc
1302            .handle_http(
1303                r#"{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"verify","arguments":{}}}"#,
1304            )
1305            .await;
1306        assert_eq!(status, 200);
1307        let body = body.unwrap();
1308        assert_eq!(body["error"]["code"], -32602, "excluded tool refused");
1309        let message = body["error"]["message"].as_str().unwrap();
1310        assert!(
1311            message.contains("orient, finding, search, graph, external"),
1312            "refusal names the available tool set: {message}"
1313        );
1314    }
1315
1316    #[tokio::test]
1317    async fn errors_carry_kind_and_profile_gate_refuses_writes() {
1318        let svc = service();
1319        // Unknown finding id → NOT_FOUND in the envelope, isError true.
1320        let (_, body) = svc
1321            .handle_http(
1322                r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"finding","arguments":{"id":"vf_does_not_exist"}}}"#,
1323            )
1324            .await;
1325        let body = body.unwrap();
1326        assert_eq!(body["result"]["isError"], true);
1327        let text = body["result"]["content"][0]["text"].as_str().unwrap();
1328        let envelope: Value = serde_json::from_str(text).unwrap();
1329        assert_eq!(envelope["ok"], false);
1330        assert_eq!(envelope["error"]["kind"], "NOT_FOUND");
1331
1332        // The hosted fixture excludes path-bound tools before the profile gate.
1333        // Use the local MCP surface here so this assertion exercises the
1334        // read-only profile's refusal of the task-first write tool itself.
1335        let entries = vec![("erdos-formalization".to_string(), fixture())];
1336        let (local_svc, warnings) = McpService::from_named_paths(&entries, "read-only", &[])
1337            .expect("fixture frontier loads");
1338        assert!(warnings.is_empty(), "unexpected warnings: {warnings:?}");
1339        let (_, body) = local_svc
1340            .handle_http(
1341                r#"{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"work","arguments":{}}}"#,
1342            )
1343            .await;
1344        let text = body.unwrap()["result"]["content"][0]["text"]
1345            .as_str()
1346            .unwrap()
1347            .to_string();
1348        let envelope: Value = serde_json::from_str(&text).unwrap();
1349        assert_eq!(envelope["error"]["kind"], "PERMISSION_DENIED");
1350    }
1351
1352    #[tokio::test]
1353    async fn failed_in_scope_work_does_not_refresh_the_served_snapshot() {
1354        let temp = tempfile::tempdir().unwrap();
1355        let path = work_fixture(temp.path()).canonicalize().unwrap();
1356        let project = repo::load_from_path(&path).unwrap();
1357        let frontier = Arc::new(Mutex::new(project));
1358        let args = json!({
1359            "frontier_path": path.display().to_string(),
1360            "action": "drop",
1361            "obligation_id": "scope:probe",
1362            "agent_actor": "agent:other"
1363        });
1364        let (result, snapshot) =
1365            execute_tool("work", &args, &frontier, &Client::new(), &[], Some(&path)).await;
1366        let error = result.unwrap_err();
1367        assert_eq!(error.kind, ToolErrorKind::PermissionDenied);
1368        assert!(snapshot.is_none(), "failed work must not refresh MCP reads");
1369    }
1370
1371    #[tokio::test]
1372    async fn delayed_earlier_refresh_cannot_overwrite_a_later_disk_state() {
1373        use vela_protocol::sign::ActorRecord;
1374
1375        let temp = tempfile::tempdir().unwrap();
1376        let path = temp.path().join("cache-race");
1377        let mut initial = project::assemble("cache-race", vec![], 0, 0, "initial");
1378        initial.project.description = "earlier write".to_string();
1379        repo::init_repo(&path, &initial).unwrap();
1380
1381        let frontier = Arc::new(Mutex::new(initial));
1382        // Hold the cache lock so the refresh belonging to the earlier write is
1383        // delayed until after a later state has reached disk. The old
1384        // load-then-lock sequence could have captured this actor-free snapshot
1385        // here and installed it last.
1386        let cache_guard = frontier.lock().await;
1387        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
1388        let early_frontier = Arc::clone(&frontier);
1389        let early_path = path.clone();
1390        let early_refresh = tokio::spawn(async move {
1391            started_tx.send(()).unwrap();
1392            reload_served_project(&early_frontier, &early_path).await
1393        });
1394        started_rx.await.unwrap();
1395        tokio::task::yield_now().await;
1396
1397        let mut later = repo::load_from_path(&path).unwrap();
1398        later.actors.push(ActorRecord {
1399            id: "agent:later-write".to_string(),
1400            public_key: "11".repeat(32),
1401            algorithm: "ed25519".to_string(),
1402            created_at: "2026-07-14T00:00:00Z".to_string(),
1403            tier: None,
1404            orcid: None,
1405            access_clearance: None,
1406            revoked_at: None,
1407            revoked_reason: None,
1408        });
1409        repo::save_to_path(&path, &later).unwrap();
1410        let late_frontier = Arc::clone(&frontier);
1411        let late_path = path.clone();
1412        let late_refresh =
1413            tokio::spawn(async move { reload_served_project(&late_frontier, &late_path).await });
1414
1415        drop(cache_guard);
1416        let early_snapshot = early_refresh.await.unwrap().unwrap();
1417        let late_snapshot = late_refresh.await.unwrap().unwrap();
1418        let has_later_write = |project: &Project| {
1419            project
1420                .actors
1421                .iter()
1422                .any(|actor| actor.id == "agent:later-write")
1423        };
1424        assert!(has_later_write(&early_snapshot));
1425        assert!(has_later_write(&late_snapshot));
1426        assert!(has_later_write(&*frontier.lock().await));
1427    }
1428
1429    #[tokio::test]
1430    async fn finalization_is_absent_and_unroutable_in_every_profile() {
1431        for profile in ["read-only", "draft"] {
1432            let entries = vec![("erdos-formalization".to_string(), fixture())];
1433            let (svc, warnings) = McpService::from_named_paths(&entries, profile, &[])
1434                .expect("fixture frontier loads");
1435            assert!(warnings.is_empty(), "unexpected warnings: {warnings:?}");
1436
1437            let (_, listed) = svc
1438                .handle_http(r#"{"jsonrpc":"2.0","id":7,"method":"tools/list"}"#)
1439                .await;
1440            assert!(
1441                !listed.unwrap()["result"]["tools"]
1442                    .as_array()
1443                    .unwrap()
1444                    .iter()
1445                    .any(|tool| tool["name"] == "decide"),
1446                "decide leaked into {profile} discovery"
1447            );
1448
1449            let before = serde_json::to_value(&*svc.state.project.lock().await).unwrap();
1450            let (_, body) = svc
1451                .handle_http(
1452                    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"}}}"#,
1453                )
1454                .await;
1455            let text = body.unwrap()["result"]["content"][0]["text"]
1456                .as_str()
1457                .unwrap()
1458                .to_string();
1459            let envelope: Value = serde_json::from_str(&text).unwrap();
1460            assert_eq!(
1461                envelope["error"]["kind"], "NOT_FOUND",
1462                "removed finalizer must not reach a schema, profile gate, key lookup, or state handler in {profile}"
1463            );
1464            let after = serde_json::to_value(&*svc.state.project.lock().await).unwrap();
1465            assert_eq!(
1466                after, before,
1467                "removed finalizer mutated state in {profile}"
1468            );
1469        }
1470    }
1471
1472    /// Fetch one orient envelope and strip the per-build noise: the
1473    /// envelope's `duration_ms`, the merged project's `compiled_at`
1474    /// (merge_projects stamps `Utc::now()`), and the replay report's
1475    /// snapshot hashes (they hash the merged snapshot, which embeds that
1476    /// timestamp). Two builds of the same frontier differ there and
1477    /// nowhere else.
1478    async fn orient_envelope_normalized(svc: &McpService) -> Value {
1479        let (status, body) = svc
1480            .handle_http(
1481                r#"{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"orient","arguments":{}}}"#,
1482            )
1483            .await;
1484        assert_eq!(status, 200);
1485        let body = body.unwrap();
1486        assert_eq!(body["result"]["isError"], false, "orient call succeeds");
1487        let text = body["result"]["content"][0]["text"].as_str().unwrap();
1488        let mut envelope: Value = serde_json::from_str(text).unwrap();
1489        envelope.as_object_mut().unwrap().remove("duration_ms");
1490        if let Some(frontier) = envelope
1491            .pointer_mut("/data/frontier")
1492            .and_then(Value::as_object_mut)
1493        {
1494            frontier.remove("compiled_at");
1495        }
1496        if let Some(replay) = envelope
1497            .pointer_mut("/data/verification/events/replay")
1498            .and_then(Value::as_object_mut)
1499        {
1500            for key in ["current_hash", "replayed_hash", "source_hash"] {
1501                replay.remove(key);
1502            }
1503        }
1504        envelope
1505    }
1506
1507    /// The hosted-parity contract: a service hydrated from already-loaded
1508    /// `Project`s (the hub's DB path) must be indistinguishable from one
1509    /// loaded off the filesystem — same tools/list, same orient output.
1510    #[tokio::test]
1511    async fn from_projects_matches_from_named_paths() {
1512        let via_paths = service();
1513
1514        // The DB path: load the raw project (no materialize — DB snapshots
1515        // are persisted un-materialized too) and hand it to from_projects.
1516        let project = repo::load_from_path(&fixture()).expect("fixture frontier loads raw");
1517        let (via_projects, warnings) = McpService::from_projects(
1518            vec![("erdos-formalization".to_string(), project)],
1519            "read-only",
1520            &McpService::hosted_exclusions(),
1521        )
1522        .expect("service builds from in-memory projects");
1523        assert!(warnings.is_empty(), "unexpected warnings: {warnings:?}");
1524
1525        let list_req = r#"{"jsonrpc":"2.0","id":8,"method":"tools/list"}"#;
1526        let (s1, list_paths) = via_paths.handle_http(list_req).await;
1527        let (s2, list_projects) = via_projects.handle_http(list_req).await;
1528        assert_eq!(s1, 200);
1529        assert_eq!(s2, 200);
1530        assert_eq!(
1531            list_paths, list_projects,
1532            "tools/list must be identical across the two constructors"
1533        );
1534
1535        let orient_paths = orient_envelope_normalized(&via_paths).await;
1536        let orient_projects = orient_envelope_normalized(&via_projects).await;
1537        assert_eq!(
1538            orient_paths, orient_projects,
1539            "orient output must be identical across the two constructors"
1540        );
1541    }
1542
1543    #[tokio::test]
1544    async fn notifications_get_202_and_batches_collect() {
1545        let svc = service();
1546        let (status, body) = svc
1547            .handle_http(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#)
1548            .await;
1549        assert_eq!(status, 202);
1550        assert!(body.is_none());
1551
1552        let (status, body) = svc
1553            .handle_http(
1554                r#"[{"jsonrpc":"2.0","method":"notifications/initialized"},{"jsonrpc":"2.0","id":5,"method":"ping"}]"#,
1555            )
1556            .await;
1557        assert_eq!(status, 200);
1558        assert_eq!(body.unwrap().as_array().unwrap().len(), 1);
1559
1560        let (status, body) = svc.handle_http("not json").await;
1561        assert_eq!(status, 400);
1562        assert_eq!(body.unwrap()["error"]["code"], -32700);
1563    }
1564}