vela-cli 0.914.2

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
//! The HTTP read surface for `vela serve --http`: the `/entries/{vfr}/…`
//! route handlers, the `/mcp` streamable-HTTP endpoints, and their shared
//! error/lookup helpers. Moved verbatim from `server/serve.rs`; the router
//! itself (`run_http`) and `McpService` stay there.

use std::collections::{HashMap, HashSet};

use axum::{Json, extract::State, http::StatusCode};
use serde_json::{Value, json};

use vela_edge::signals;
use vela_protocol::project::Project;

use super::serve::{AppState, mcp_http_exchange};
use super::tools::tool_search_findings;

/// JSON error body shared by every serve HTTP error response:
/// `{"error": {"kind": "...", "message": "..."}}`, matching the hub's shape
/// and the MCP envelope's kind vocabulary.
fn http_error(status: StatusCode, kind: &str, message: String) -> (StatusCode, Json<Value>) {
    (
        status,
        Json(json!({"error": {"kind": kind, "message": message}})),
    )
}

/// Resolve the `{vfr}` path segment: the literal `self`, the served
/// frontier's real vfr_ id, or a vfr_ prefix of it.
fn resolve_vfr(project: &Project, segment: &str) -> Option<String> {
    let fid = project.frontier_id();
    if segment == "self" || (segment.starts_with("vfr_") && fid.starts_with(segment)) {
        Some(fid)
    } else {
        None
    }
}

fn vfr_not_found(project: &Project, segment: &str) -> (StatusCode, Json<Value>) {
    http_error(
        StatusCode::NOT_FOUND,
        "NOT_FOUND",
        format!(
            "{segment} is not served here; this server serves {} (use `self`)",
            project.frontier_id()
        ),
    )
}

/// GET /entries/{vfr}/events — cursor-paginated read over the canonical
/// event log, mirroring the hub's shape.
///
/// Query params:
///   - `cursor` (optional): a `vev_…` event id; events strictly after this
///     id are returned. Omit to start from the genesis event.
///   - `limit` (optional, default 100, max 500): cap the response size.
///   - `kind`, `target` (optional): server-side filters, applied before
///     pagination so the cursor walks the filtered view.
///
/// Returns `{events: [...], next_cursor: "vev_..." | null, count: usize}`.
/// `next_cursor` is null when the response includes the tail of the log.
/// 400 if `cursor` does not exist in the log (the client is out of sync;
/// better to fail loudly than to silently skip).
pub(crate) async fn http_entry_events(
    State(state): State<AppState>,
    axum::extract::Path(vfr): axum::extract::Path<String>,
    axum::extract::Query(params): axum::extract::Query<HashMap<String, String>>,
) -> (StatusCode, Json<Value>) {
    let project = state.project.lock().await;
    let Some(vfr_id) = resolve_vfr(&project, &vfr) else {
        return vfr_not_found(&project, &vfr);
    };
    let limit = params
        .get("limit")
        .and_then(|v| v.parse::<usize>().ok())
        .unwrap_or(100)
        .min(500);
    let start_idx: usize = match params.get("cursor") {
        None => 0,
        Some(cursor) => match project.events.iter().position(|event| &event.id == cursor) {
            Some(idx) => idx + 1,
            None => {
                return http_error(
                    StatusCode::BAD_REQUEST,
                    "INVALID_ARG",
                    format!("cursor '{cursor}' not found in event log; client is out of sync"),
                );
            }
        },
    };
    // Server-side `?kind=` and `?target=` filters. Agents watching for
    // specific event kinds (e.g. polling for new finding.superseded events)
    // shouldn't need to fetch the whole log to locate one match. Filters
    // apply BEFORE the limit/cursor so pagination works on the filtered view.
    let kind_filter = params.get("kind").map(String::as_str);
    let target_filter = params.get("target").map(String::as_str);
    let filtered: Vec<&vela_protocol::events::StateEvent> = project
        .events
        .iter()
        .skip(start_idx)
        .filter(|e| kind_filter.is_none_or(|k| e.kind == k))
        .filter(|e| target_filter.is_none_or(|t| e.target.id == t))
        .collect();
    let total_filtered = filtered.len();
    let take_n = limit.min(total_filtered);
    let slice: Vec<&vela_protocol::events::StateEvent> =
        filtered.into_iter().take(take_n).collect();
    let next_cursor = if take_n < total_filtered {
        slice.last().map(|event| event.id.clone())
    } else {
        None
    };
    (
        StatusCode::OK,
        Json(json!({
            "vfr_id": vfr_id,
            "events": slice,
            "count": slice.len(),
            "next_cursor": next_cursor,
            "log_total": project.events.len(),
            "filtered_total": total_filtered,
        })),
    )
}

/// GET /entries — the single-element registry list. `vela serve` serves one
/// (possibly merged) frontier; this mirrors the hub's `/entries` shape so a
/// client can speak one protocol to either server.
pub(crate) async fn http_entries(State(state): State<AppState>) -> Json<Value> {
    let project = state.project.lock().await;
    Json(json!({
        "schema": "vela.entries.v0",
        "count": 1,
        "entries": [{
            "vfr_id": project.frontier_id(),
            "name": project.project.name,
            "findings": project.stats.findings,
            "links": project.stats.links,
            "events": project.events.len(),
            "sources": state.project_infos.iter().map(|info| json!({
                "name": info.name,
                "file": info.file,
                "findings": info.findings_count,
                "links": info.links_count,
                "papers": info.papers,
            })).collect::<Vec<_>>(),
        }],
    }))
}

/// GET /entries/{vfr} — the frontier summary: stats, proof state, signals.
pub(crate) async fn http_entry(
    State(state): State<AppState>,
    axum::extract::Path(vfr): axum::extract::Path<String>,
) -> (StatusCode, Json<Value>) {
    let project = state.project.lock().await;
    let Some(vfr_id) = resolve_vfr(&project, &vfr) else {
        return vfr_not_found(&project, &vfr);
    };
    (
        StatusCode::OK,
        Json(json!({
            "vfr_id": vfr_id,
            "frontier": {
                "name": project.project.name,
                "description": project.project.description,
                "compiled_at": project.project.compiled_at,
                "compiler": project.project.compiler,
            },
            "stats": project.stats,
            "events": project.events.len(),
            "proof_state": project.proof_state,
            "signals": signals::analyze_at(&project, &[], state.source_path.as_deref()).signals,
        })),
    )
}

/// GET /entries/{vfr}/findings — structured list, or text-shaped search when
/// a `query`/`entity`/`entity_type`/`type` filter is supplied.
pub(crate) async fn http_entry_findings(
    State(state): State<AppState>,
    axum::extract::Path(vfr): axum::extract::Path<String>,
    axum::extract::Query(params): axum::extract::Query<HashMap<String, String>>,
) -> (StatusCode, Json<Value>) {
    let project = state.project.lock().await;
    if resolve_vfr(&project, &vfr).is_none() {
        return vfr_not_found(&project, &vfr);
    }
    // The local HTTP reader has no authenticated request identity. An actor
    // name supplied by a caller is not proof of possession, so HTTP is always
    // public-only until a real end-to-end authentication protocol exists.
    let clearance = None;
    let view = vela_protocol::access_tier::redact_for_actor(&project, clearance);

    // v0.91: When no search-style filter is supplied, return a
    // structured `{findings, count}` list rather than the search
    // tool's text-shaped result. The previous behavior was
    // surprising for API consumers expecting a REST-style list
    // and forced them to scrape free-text. Search filters
    // (`query`, `entity`, `entity_type`, `type`) preserve the
    // existing search-tool behavior for callers that depend on it.
    let has_search = params.contains_key("query")
        || params.contains_key("entity")
        || params.contains_key("entity_type")
        || params.contains_key("type");
    if !has_search {
        let limit = params
            .get("limit")
            .and_then(|v| v.parse::<usize>().ok())
            .unwrap_or(view.findings.len());
        let findings: Vec<Value> = view
            .findings
            .iter()
            .take(limit)
            .map(|f| serde_json::to_value(f).unwrap_or_default())
            .collect();
        return (
            StatusCode::OK,
            Json(json!({
                "count": view.findings.len(),
                "returned": findings.len(),
                "findings": findings,
            })),
        );
    }

    let args = json!({
        "query": params.get("query"),
        "entity": params.get("entity"),
        "entity_type": params.get("entity_type"),
        "assertion_type": params.get("type"),
        "limit": params.get("limit").and_then(|v| v.parse::<u64>().ok()).unwrap_or(50),
    });
    match tool_search_findings(&args, &view) {
        Ok(text) => (StatusCode::OK, Json(json!({"result": text}))),
        Err(error) => http_error(StatusCode::INTERNAL_SERVER_ERROR, "INTERNAL", error),
    }
}

/// GET /entries/{vfr}/findings/{id} — one finding with its derived Belnap
/// status and provenance overlays.
pub(crate) async fn http_entry_finding(
    State(state): State<AppState>,
    axum::extract::Path((vfr, id)): axum::extract::Path<(String, String)>,
) -> (StatusCode, Json<Value>) {
    let project = state.project.lock().await;
    if resolve_vfr(&project, &vfr).is_none() {
        return vfr_not_found(&project, &vfr);
    }
    let clearance = None;
    match project
        .findings
        .iter()
        .find(|finding| finding.id == id || finding.id.starts_with(&id))
    {
        Some(finding) => {
            if !vela_protocol::access_tier::actor_may_read(finding.access_tier, clearance) {
                // v0.51: above-clearance findings 404 — the existence
                // of the object is itself part of the tiered content.
                return http_error(
                    StatusCode::NOT_FOUND,
                    "NOT_FOUND",
                    format!("Finding not found: {id}"),
                );
            }
            // v0.85: surface the substrate-derived Belnap status
            // alongside the on-disk finding. Computed read-only
            // from the event log via `provenance_compute`. The
            // existing finding fields remain authoritative; this
            // is a derived view per docs/THEORY.md Section 7.
            let sp =
                vela_edge::provenance_compute::status_provenance_for_finding(&project, &finding.id);
            let belnap = sp.derive_status();
            let mut value = serde_json::to_value(finding).unwrap_or_default();
            if let Some(map) = value.as_object_mut() {
                map.insert(
                    "belnap_status".to_string(),
                    serde_json::to_value(belnap).unwrap_or_default(),
                );
                map.insert(
                    "belnap_letter".to_string(),
                    json!(belnap.letter().to_string()),
                );
                map.insert("support_term_count".to_string(), json!(sp.support.len()));
                map.insert("refute_term_count".to_string(), json!(sp.refute.len()));
                // Surface the support/refute id sets per docs/THEORY.md
                // §7, suitable for audit trails and downstream tooling
                // that needs to know which events derive support.
                map.insert(
                    "support_provenance".to_string(),
                    serde_json::to_value(&sp.support).unwrap_or_default(),
                );
                map.insert(
                    "refute_provenance".to_string(),
                    serde_json::to_value(&sp.refute).unwrap_or_default(),
                );
                // Display strings join the ids additively (`vev_a + vev_b`).
                // Suitable for debug surfaces and Workbench tooltips.
                let join = |s: &std::collections::BTreeSet<String>| -> String {
                    if s.is_empty() {
                        "0".to_string()
                    } else {
                        s.iter().cloned().collect::<Vec<_>>().join(" + ")
                    }
                };
                map.insert(
                    "support_provenance_display".to_string(),
                    json!(join(&sp.support)),
                );
                map.insert(
                    "refute_provenance_display".to_string(),
                    json!(join(&sp.refute)),
                );
            }
            (StatusCode::OK, Json(value))
        }
        None => http_error(
            StatusCode::NOT_FOUND,
            "NOT_FOUND",
            format!("Finding not found: {id}"),
        ),
    }
}

pub(crate) async fn http_health(State(state): State<AppState>) -> Json<Value> {
    let project = state.project.lock().await;
    Json(json!({
        "ok": true,
        "frontier": {
            "name": project.project.name,
            "findings": project.stats.findings,
            "events": project.events.len(),
        }
    }))
}

/// POST /mcp — streamable-HTTP MCP with stateless JSON responses.
pub(crate) async fn http_mcp(
    State(state): State<AppState>,
    body: String,
) -> axum::response::Response {
    use axum::response::IntoResponse;
    let (status, response) = mcp_http_exchange(&body, &state, &HashSet::new()).await;
    let status = StatusCode::from_u16(status).unwrap_or(StatusCode::OK);
    match response {
        Some(value) => (status, Json(value)).into_response(),
        None => status.into_response(),
    }
}

/// GET /mcp — this endpoint offers no server-initiated SSE stream.
pub(crate) async fn http_mcp_get() -> (StatusCode, Json<Value>) {
    (
        StatusCode::METHOD_NOT_ALLOWED,
        Json(json!({
            "error": "stateless MCP endpoint: POST a JSON-RPC message; no server-initiated stream is offered"
        })),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;
    use std::sync::Arc;
    use tokio::sync::Mutex;
    use vela_protocol::access_tier::AccessTier;
    use vela_protocol::sign::ActorRecord;

    fn public_only_state() -> (AppState, String) {
        let path =
            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../examples/erdos-formalization");
        let mut project = vela_protocol::repo::load_from_path(&path).unwrap();
        let finding = project.findings.first_mut().expect("fixture finding");
        finding.access_tier = AccessTier::Classified;
        let classified_id = finding.id.clone();
        project.actors.push(ActorRecord {
            id: "reviewer:classified-http-fixture".to_string(),
            public_key: "11".repeat(32),
            algorithm: "ed25519".to_string(),
            created_at: "2026-07-22T00:00:00Z".to_string(),
            tier: None,
            orcid: None,
            access_clearance: Some(AccessTier::Classified),
            revoked_at: None,
            revoked_reason: None,
        });
        (
            AppState {
                project: Arc::new(Mutex::new(project)),
                project_infos: Vec::new(),
                client: reqwest::Client::new(),
                profile: vela_edge::tool_registry::McpProfile::ReadOnly,
                source_path: Some(path),
            },
            classified_id,
        )
    }

    #[tokio::test]
    async fn http_reader_is_always_public_only_without_authenticated_identity() {
        let (state, classified_id) = public_only_state();
        let project = state.project.lock().await;
        let frontier_id = project.frontier_id();
        let public_count = project
            .findings
            .iter()
            .filter(|finding| finding.access_tier == AccessTier::Public)
            .count();
        drop(project);

        let (status, Json(list)) = http_entry_findings(
            State(state.clone()),
            axum::extract::Path(frontier_id.clone()),
            axum::extract::Query(HashMap::new()),
        )
        .await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(list["count"], public_count);

        let (status, _) = http_entry_finding(
            State(state),
            axum::extract::Path((frontier_id, classified_id)),
        )
        .await;
        assert_eq!(status, StatusCode::NOT_FOUND);
    }
}