Skip to main content

qualia_core_db/services/
poet_api.rs

1//! Bounded HTTP adapters for POET's native evaluation capabilities.
2//!
3//! These handlers expose the same `PoetSnapshot` and NLP implementations used
4//! by the desktop host. They deliberately return execution failures as typed
5//! JSON responses so browser clients can render honest diagnostics.
6
7use std::collections::BTreeMap;
8use std::sync::{Mutex, OnceLock};
9
10use axum::{
11    body::Bytes,
12    http::StatusCode,
13    response::{IntoResponse, Response},
14    Json,
15};
16use serde::{Deserialize, Serialize};
17
18use crate::poet_host::{format_value, PoetSnapshot};
19
20/// Process-sticky Poet host for HTTP `/eval` `/invoke` `/intent`.
21/// Desktop already keeps `Mutex<PoetSnapshot>`; recreating `from_daemon()`
22/// per request dropped `volume_open` loads so `volume_commit` saw an empty graph.
23static STICKY_POET_HOST: OnceLock<Mutex<PoetSnapshot>> = OnceLock::new();
24
25fn with_sticky_poet_host<R>(f: impl FnOnce(&mut PoetSnapshot) -> R) -> R {
26    let cell = STICKY_POET_HOST.get_or_init(|| Mutex::new(PoetSnapshot::from_daemon()));
27    let mut guard = cell.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
28    // While attached, refresh revision from the live daemon graph; detached
29    // sanctuary loads (volume_open) keep their resident committed set.
30    if guard.attached {
31        #[cfg(not(target_arch = "wasm32"))]
32        {
33            guard.revision = crate::daemon_graph::graph_revision().max(1);
34        }
35    }
36    f(&mut *guard)
37}
38
39pub const POET_PAYLOAD_LIMIT_BYTES: usize = 64 * 1024;
40const MAX_JSON_DEPTH: usize = 32;
41const MAX_JSON_NODES: usize = 4096;
42
43#[derive(Debug, Deserialize)]
44pub struct NativeEvalRequest {
45    pub source: String,
46    #[serde(default)]
47    pub as_cell: bool,
48    #[serde(default)]
49    pub function: Option<String>,
50}
51
52#[derive(Debug, Serialize)]
53pub struct NativeEvalResponse {
54    pub ok: bool,
55    pub value: String,
56    pub diagnostic: Option<String>,
57    pub revision: u64,
58    pub committed: usize,
59    pub honesty: &'static str,
60}
61
62#[derive(Debug, Deserialize)]
63pub struct NativeInvokeRequest {
64    pub id: String,
65    #[serde(default)]
66    pub args: serde_json::Value,
67}
68
69#[derive(Debug, Deserialize)]
70pub struct NativeGazetteerRequest {
71    pub source: String,
72}
73
74#[derive(Debug, Serialize)]
75pub struct GazetteerHitDto {
76    pub surface: String,
77    pub iri: String,
78    pub kind: String,
79}
80
81#[derive(Debug, Serialize)]
82pub struct NativeGazetteerResponse {
83    pub ok: bool,
84    pub token_count: usize,
85    pub sentence_count: usize,
86    pub sealed: usize,
87    pub hits: Vec<GazetteerHitDto>,
88    pub diagnostic: Option<String>,
89}
90
91#[derive(Debug, Deserialize)]
92struct IntentTarget {
93    value: String,
94}
95
96#[derive(Debug, Deserialize)]
97struct NativeIntentEnvelope {
98    action_type: String,
99    target_identifier: IntentTarget,
100    #[serde(default)]
101    parameters: serde_json::Value,
102}
103
104fn decode_json<T: serde::de::DeserializeOwned>(body: &Bytes) -> Result<T, Response> {
105    if body.len() > POET_PAYLOAD_LIMIT_BYTES {
106        return Err((
107            StatusCode::PAYLOAD_TOO_LARGE,
108            Json(serde_json::json!({
109                "ok": false,
110                "code": "payload_too_large",
111                "diagnostic": format!("POET requests are limited to {POET_PAYLOAD_LIMIT_BYTES} bytes")
112            })),
113        )
114            .into_response());
115    }
116    serde_json::from_slice(body).map_err(|error| {
117        (
118            StatusCode::BAD_REQUEST,
119            Json(serde_json::json!({
120                "ok": false,
121                "code": "invalid_json",
122                "diagnostic": error.to_string()
123            })),
124        )
125            .into_response()
126    })
127}
128
129fn eval_response(
130    snapshot: &PoetSnapshot,
131    result: Result<vibe::Value, vibe::Diagnostic>,
132) -> NativeEvalResponse {
133    match result {
134        Ok(value) => NativeEvalResponse {
135            ok: true,
136            value: format_value(&value),
137            diagnostic: None,
138            revision: snapshot.revision,
139            committed: snapshot.committed.len(),
140            honesty: "live",
141        },
142        Err(error) => NativeEvalResponse {
143            ok: false,
144            value: String::new(),
145            diagnostic: Some(error.to_string()),
146            revision: snapshot.revision,
147            committed: snapshot.committed.len(),
148            honesty: "live",
149        },
150    }
151}
152
153/// HTTP `eval` handler.
154pub async fn eval_handler(body: Bytes) -> Response {
155    let request: NativeEvalRequest = match decode_json(&body) {
156        Ok(request) => request,
157        Err(response) => return response,
158    };
159
160    with_sticky_poet_host(|snapshot| {
161        let result = if let Some(function) = request.function.as_deref() {
162            snapshot.eval_fn(&request.source, function, Vec::new())
163        } else if request.as_cell {
164            snapshot.eval_cell_src(&request.source)
165        } else {
166            snapshot.eval_program_src(&request.source)
167        };
168        Json(eval_response(snapshot, result)).into_response()
169    })
170}
171
172fn json_to_vibe(
173    value: serde_json::Value,
174    depth: usize,
175    nodes: &mut usize,
176) -> Result<vibe::Value, &'static str> {
177    if depth > MAX_JSON_DEPTH {
178        return Err("invoke arguments exceed the maximum nesting depth");
179    }
180    *nodes += 1;
181    if *nodes > MAX_JSON_NODES {
182        return Err("invoke arguments contain too many values");
183    }
184
185    Ok(match value {
186        serde_json::Value::Null => vibe::Value::Null,
187        serde_json::Value::Bool(value) => vibe::Value::Bool(value),
188        serde_json::Value::Number(value) => {
189            if let Some(value) = value.as_i64() {
190                vibe::Value::I64(value)
191            } else if let Some(value) = value.as_u64() {
192                vibe::Value::U64(value)
193            } else if let Some(value) = value.as_f64() {
194                vibe::Value::F64(value)
195            } else {
196                return Err("invoke argument contains an unsupported number");
197            }
198        }
199        serde_json::Value::String(value) => vibe::Value::String(value),
200        serde_json::Value::Array(values) => vibe::Value::List(
201            values
202                .into_iter()
203                .map(|value| json_to_vibe(value, depth + 1, nodes))
204                .collect::<Result<Vec<_>, _>>()?,
205        ),
206        serde_json::Value::Object(values) => {
207            let mut record = BTreeMap::new();
208            for (key, value) in values {
209                record.insert(key, json_to_vibe(value, depth + 1, nodes)?);
210            }
211            vibe::Value::Record(record)
212        }
213    })
214}
215
216/// HTTP `invoke` handler.
217pub async fn invoke_handler(body: Bytes) -> Response {
218    let request: NativeInvokeRequest = match decode_json(&body) {
219        Ok(request) => request,
220        Err(response) => return response,
221    };
222    if request.id.trim().is_empty() {
223        return (
224            StatusCode::BAD_REQUEST,
225            Json(serde_json::json!({
226                "ok": false,
227                "code": "missing_capability_id",
228                "diagnostic": "The invoke capability id cannot be empty"
229            })),
230        )
231            .into_response();
232    }
233
234    let mut nodes = 0;
235    let args = match json_to_vibe(request.args, 0, &mut nodes) {
236        Ok(args) => args,
237        Err(diagnostic) => {
238            return (
239                StatusCode::BAD_REQUEST,
240                Json(serde_json::json!({
241                    "ok": false,
242                    "code": "invalid_arguments",
243                    "diagnostic": diagnostic
244                })),
245            )
246                .into_response();
247        }
248    };
249
250    with_sticky_poet_host(|snapshot| {
251        let result = snapshot.invoke_id(request.id.trim(), args);
252        Json(eval_response(snapshot, result)).into_response()
253    })
254}
255
256/// HTTP `gazetteer` handler.
257pub async fn gazetteer_handler(body: Bytes) -> Response {
258    let request: NativeGazetteerRequest = match decode_json(&body) {
259        Ok(request) => request,
260        Err(response) => return response,
261    };
262    if crate::nlp::budget::reject_source(request.source.len()).is_err() {
263        return (
264            StatusCode::PAYLOAD_TOO_LARGE,
265            Json(serde_json::json!({
266                "ok": false,
267                "code": "source_too_large",
268                "diagnostic": format!(
269                    "nlp gazetteer source exceeds {} bytes",
270                    crate::nlp::budget::MAX_SOURCE_BYTES
271                )
272            })),
273        )
274            .into_response();
275    }
276    let analysis = crate::nlp::analyze_document(&request.source);
277    let hits = analysis
278        .hits
279        .iter()
280        .map(|hit| GazetteerHitDto {
281            surface: hit
282                .span
283                .slice(&request.source)
284                .unwrap_or(hit.surface)
285                .to_string(),
286            iri: hit.iri.to_string(),
287            kind: "gazetteer".to_string(),
288        })
289        .collect();
290
291    Json(NativeGazetteerResponse {
292        ok: true,
293        token_count: analysis.token_count,
294        sentence_count: analysis.sentence_count,
295        sealed: analysis.plans.len(),
296        hits,
297        diagnostic: None,
298    })
299    .into_response()
300}
301
302fn intent_error(code: &'static str, diagnostic: impl Into<String>) -> Response {
303    (
304        StatusCode::UNPROCESSABLE_ENTITY,
305        Json(serde_json::json!({
306            "ok": false,
307            "status": "rejected",
308            "code": code,
309            "diagnostic": diagnostic.into()
310        })),
311    )
312        .into_response()
313}
314
315/// Dispatch a CBOR-LD Tool Chest envelope through supported native contracts.
316pub async fn intent_handler(body: Bytes) -> Response {
317    if body.len() > POET_PAYLOAD_LIMIT_BYTES {
318        return intent_error(
319            "payload_too_large",
320            "Intent exceeds the 64 KiB request limit",
321        );
322    }
323    let envelope: NativeIntentEnvelope = match ciborium::de::from_reader(body.as_ref()) {
324        Ok(envelope) => envelope,
325        Err(error) => return intent_error("invalid_cbor_ld", error.to_string()),
326    };
327
328    match envelope.action_type.as_str() {
329        "query" => {
330            let Some(query) = envelope
331                .parameters
332                .get("query")
333                .and_then(|value| value.as_str())
334            else {
335                return intent_error(
336                    "missing_query",
337                    "Query intent parameters need a `query` string",
338                );
339            };
340            let graph = crate::daemon_graph::graph_read_guard();
341            match crate::daemon_query::execute_query_on_graph(query, graph.as_slice()) {
342                Ok((stats, _)) => Json(serde_json::json!({
343                    "ok": true,
344                    "status": "accepted",
345                    "match_count": stats.match_count
346                }))
347                .into_response(),
348                Err(error) => intent_error("query_failed", format!("{error:?}")),
349            }
350        }
351        "invoke" | "validate" => {
352            let capability = if envelope.action_type == "validate" {
353                "SHACL.validate".to_string()
354            } else {
355                envelope
356                    .parameters
357                    .get("id")
358                    .and_then(|value| value.as_str())
359                    .unwrap_or(&envelope.target_identifier.value)
360                    .to_string()
361            };
362            let json_args = envelope
363                .parameters
364                .get("args")
365                .cloned()
366                .unwrap_or(envelope.parameters);
367            let mut nodes = 0;
368            let args = match json_to_vibe(json_args, 0, &mut nodes) {
369                Ok(args) => args,
370                Err(error) => return intent_error("invalid_arguments", error),
371            };
372            with_sticky_poet_host(|snapshot| match snapshot.invoke_id(&capability, args) {
373                Ok(value) => Json(serde_json::json!({
374                    "ok": true,
375                    "status": "accepted",
376                    "value": format_value(&value),
377                    "revision": snapshot.revision
378                }))
379                .into_response(),
380                Err(error) => intent_error("invoke_failed", error.to_string()),
381            })
382        }
383        "mutate" | "publish" | "annotate" => intent_error(
384            "typed_contract_required",
385            "This state-changing intent needs a dedicated typed and authorised contract",
386        ),
387        "navigate" => intent_error(
388            "local_action",
389            "Navigation is a local UI action and must not be sent to the daemon",
390        ),
391        "cancel" => intent_error(
392            "no_cancellable_job",
393            "No native cancellable job identifier was supplied",
394        ),
395        other => intent_error("unknown_action", format!("Unknown intent action `{other}`")),
396    }
397}
398
399#[cfg(test)]
400mod tests {
401    use super::*;
402
403    #[test]
404    fn json_conversion_preserves_records_and_lists() {
405        let mut nodes = 0;
406        let converted = json_to_vibe(
407            serde_json::json!({"name": "POET", "values": [1, true]}),
408            0,
409            &mut nodes,
410        )
411        .unwrap();
412        let vibe::Value::Record(record) = converted else {
413            panic!("expected record");
414        };
415        assert_eq!(
416            record.get("name"),
417            Some(&vibe::Value::String("POET".into()))
418        );
419        assert!(
420            matches!(record.get("values"), Some(vibe::Value::List(values)) if values.len() == 2)
421        );
422    }
423
424    #[tokio::test]
425    async fn gazetteer_uses_real_document_analyzer() {
426        let body =
427            Bytes::from_static(br#"{"source":"North Spring recorded 12.5 mm on 2026-08-15."}"#);
428        let response = gazetteer_handler(body).await;
429        assert_eq!(response.status(), StatusCode::OK);
430    }
431
432    #[tokio::test]
433    async fn oversized_payload_is_rejected() {
434        let response = eval_handler(Bytes::from(vec![b'x'; POET_PAYLOAD_LIMIT_BYTES + 1])).await;
435        assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);
436    }
437
438    #[tokio::test]
439    async fn unsupported_state_change_intent_fails_closed() {
440        let envelope = serde_json::json!({
441            "@context": "https://qualiadb.org/schema/vibe#",
442            "action_type": "publish",
443            "target_identifier": { "kind": "iri", "value": "pulse:test" },
444            "parameters": { "message": "not authorised" }
445        });
446        let mut body = Vec::new();
447        ciborium::ser::into_writer(&envelope, &mut body).unwrap();
448        let response = intent_handler(Bytes::from(body)).await;
449        assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
450    }
451
452    #[cfg(not(target_arch = "wasm32"))]
453    #[test]
454    fn sticky_host_keeps_volume_open_for_commit() {
455        use vibe::Value;
456        let dir = std::env::temp_dir().join(format!(
457            "q42-sticky-{}-{}",
458            std::process::id(),
459            std::time::SystemTime::now()
460                .duration_since(std::time::UNIX_EPOCH)
461                .unwrap()
462                .as_nanos()
463        ));
464        std::fs::create_dir_all(&dir).unwrap();
465        let path = dir.join("uat-sanctuary.q42");
466        let path_s = path.to_string_lossy().to_string();
467
468        // Reset sticky host so this test owns the sanctuary load.
469        with_sticky_poet_host(|snap| {
470            *snap = PoetSnapshot::with_seed(Vec::new());
471        });
472
473        with_sticky_poet_host(|snap| {
474            let mut rec = std::collections::BTreeMap::new();
475            rec.insert("path".into(), Value::String(path_s.clone()));
476            rec.insert("create".into(), Value::Bool(true));
477            rec.insert("load".into(), Value::Bool(true));
478            let opened = snap
479                .invoke_id("GraphDatabase.volume_open", Value::Record(rec))
480                .expect("volume_open");
481            let Value::Record(r) = opened else {
482                panic!("expected record");
483            };
484            assert!(
485                matches!(r.get("quin_count"), Some(Value::U64(n)) if *n > 0),
486                "create-on-open should seed ≥1 quin"
487            );
488        });
489
490        with_sticky_poet_host(|snap| {
491            assert!(
492                !snap.committed.is_empty(),
493                "sticky host must retain volume_open load across calls"
494            );
495            let mut rec = std::collections::BTreeMap::new();
496            rec.insert("path".into(), Value::String(path_s.clone()));
497            rec.insert("sanctuary".into(), Value::Bool(true));
498            snap.invoke_id("GraphDatabase.volume_commit", Value::Record(rec))
499                .expect("volume_commit after sticky open");
500        });
501
502        let _ = std::fs::remove_dir_all(&dir);
503    }
504}