World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
The graph exports as RDF, with its intervals and its evidence (#320)
WaylandYang54e66a678da1
diff --git a/Cargo.lock b/Cargo.lockindex fe1462ff..e15558c0 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2235,6 +2235,12 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "json-event-parser"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "574b0cd5e90ee2ba03a66d0611fc9a09c9a0c28b2ecc2dc8a181dd31a53ca5d7"+[[package]]name = "jsonwebtoken"version = "10.4.0"@@ -2787,6 +2793,19 @@ version = "0.2.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "54b4ed3a7192fa19f5f48f99871f2755047fabefd7f222f12a1df1773796a102"+[[package]]+name = "oxjsonld"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6e1380a504a8571763f13b8bcad629ff90d0300d47d8a519f3c6c599625840e"+dependencies = [+ "json-event-parser",+ "oxiri",+ "oxrdf",+ "ryu-js",+ "thiserror 2.0.20",+]+[[package]]name = "oxrdf"version = "0.3.3"@@ -2799,6 +2818,19 @@ dependencies = ["thiserror 2.0.20",]+[[package]]+name = "oxrdfio"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "696223589ecbcab06b1a5df9b527dc25b0c656160cca38752fdb3878a5d3dd03"+dependencies = [+ "oxjsonld",+ "oxrdf",+ "oxrdfxml",+ "oxttl",+ "thiserror 2.0.20",+]+[[package]]name = "oxrdfxml"version = "0.2.3"@@ -3660,6 +3692,12 @@ version = "1.0.23"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"+[[package]]+name = "ryu-js"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714"+[[package]]name = "same-file"version = "1.0.6"@@ -5109,6 +5147,8 @@ dependencies = ["futures-util","jsonwebtoken","object_store",+ "oxrdf",+ "oxrdfio","percent-encoding","quick-xml 0.42.0","reqwest",diff --git a/Cargo.toml b/Cargo.tomlindex 36c00feb..da21fac2 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -87,6 +87,7 @@ csv = "1"oxttl = "0.2"oxrdfxml = "0.2"oxrdf = "0.3"+oxrdfio = "0.2"async-stream = "0.3"futures-util = "0.3"tokio-stream = "0.1"diff --git a/crates/utopia-server/Cargo.toml b/crates/utopia-server/Cargo.tomlindex 83232333..306d3c31 100644--- a/crates/utopia-server/Cargo.toml+++ b/crates/utopia-server/Cargo.toml@@ -41,6 +41,8 @@ async-trait = "0.1.92"sqlparser = "0.62.0"object_store = { version = "0.14.1", features = ["aws", "azure", "gcp"] }quick-xml.workspace = true+oxrdf.workspace = true+oxrdfio.workspace = trueurl = "2.5.8"percent-encoding = "2.3.2"base64.workspace = truediff --git a/crates/utopia-server/src/api/export_routes.rs b/crates/utopia-server/src/api/export_routes.rsnew file mode 100644index 00000000..ff853c7c--- /dev/null+++ b/crates/utopia-server/src/api/export_routes.rs@@ -0,0 +1,177 @@+//! 整库导出为 RDF(0020)。+//!+//! **边查边发**:一页事实序列化完就把攒下的字节送出去,不在内存里拼出整份文件。+//! 一个十万条事实的库正是最需要导出的那种库,也正是「先拼成一个 String」会+//! 把服务打死的那种库。+//!+//! 中途出错只能截断——HTTP 头早就发出去了。所以错误进日志,而客户端拿到的是+//! 一份短了一截的文件;这比先攒后发要好,那种做法在同样的库上根本发不出来。++use axum::body::Body;+use axum::extract::{Path, Query, State};+use axum::http::{header, HeaderMap, HeaderValue, StatusCode};+use axum::response::{IntoResponse, Response};+use serde::Deserialize;+use utopia_core::models::Role;+use utopia_core::AppError;+use uuid::Uuid;++use super::graph_routes::require_kb;+use crate::auth::AuthUser;+use crate::error::ApiResult;+use crate::rdf::{self, Format, Names, SharedBuf, Sink};+use crate::state::AppState;++#[derive(Deserialize)]+pub struct ExportQuery {+ /// `turtle`(缺省)或 `jsonld`+ #[serde(default)]+ pub format: Option<String>,+ /// 造 IRI 用的对外地址。不给就用 URN——稳定,且不假装自己知道部署在哪+ #[serde(default)]+ pub base: Option<String>,+}++pub async fn export(+ State(state): State<AppState>,+ AuthUser(user): AuthUser,+ Path(kb_id): Path<Uuid>,+ Query(q): Query<ExportQuery>,+) -> ApiResult<Response> {+ let kb = require_kb(&state, &user, kb_id, Role::Viewer).await?;+ let format = Format::parse(q.format.as_deref()).ok_or_else(|| {+ AppError::Validation("Unknown `format` (expected turtle or jsonld)".into())+ })?;+ let names = Names::new(kb_id, q.base.as_deref()).map_err(AppError::Validation)?;++ // 导出是一次「整个库离开这台机器」的动作,台账要记下(0014 的同一条理由)+ let _ = utopia_store::audit::record(+ &state.pool,+ Some(kb_id),+ user.id,+ "kb.exported",+ "knowledge_base",+ Some(kb_id),+ serde_json::json!({ "format": format.extension() }),+ )+ .await;++ let pool = state.pool.clone();+ let stream = async_stream::try_stream! {+ let buf = SharedBuf::default();+ let mut sink = Sink::new(format, buf.clone());++ let classes = utopia_store::export::classes(&pool, kb_id).await.map_err(io)?;+ let relations = utopia_store::export::relations(&pool, kb_id).await.map_err(io)?;+ let vocab = rdf::vocabulary(&names, &classes, &relations);+ for c in &classes {+ rdf::emit_class(&mut sink, &vocab, c)?;+ }+ for r in &relations {+ rdf::emit_relation(&mut sink, &vocab, r)?;+ }+ yield axum::body::Bytes::from(buf.take());++ let mut after = None;+ loop {+ let page = utopia_store::export::documents_page(&pool, kb_id, after).await.map_err(io)?;+ let Some(last) = page.last() else { break };+ after = Some(last.id);+ for d in &page {+ rdf::emit_document(&mut sink, &names, d)?;+ }+ yield axum::body::Bytes::from(buf.take());+ }++ let mut after = None;+ loop {+ let page = utopia_store::export::entities_page(&pool, kb_id, after).await.map_err(io)?;+ let Some(last) = page.last() else { break };+ after = Some(last.id);+ for e in &page {+ rdf::emit_entity(&mut sink, &names, &vocab, e)?;+ }+ yield axum::body::Bytes::from(buf.take());+ }++ // 现行三元组按「导出这一刻」判定,整份文件用同一个 now:+ // 边发边取当前时间的话,同一份文件的前后两半会按两个不同的现在写+ let now = chrono::Utc::now();+ let mut after = None;+ loop {+ let page = utopia_store::export::facts_page(&pool, kb_id, after).await.map_err(io)?;+ let Some(last) = page.last() else { break };+ after = Some(last.id);+ for f in &page {+ rdf::emit_fact(&mut sink, &names, &vocab, f, now)?;+ }+ yield axum::body::Bytes::from(buf.take());+ }++ let mut after = None;+ loop {+ let page = utopia_store::export::derived_page(&pool, kb_id, after).await.map_err(io)?;+ let Some(last) = page.last() else { break };+ after = Some(last.id);+ for d in &page {+ rdf::emit_derived(&mut sink, &names, &vocab, d)?;+ }+ yield axum::body::Bytes::from(buf.take());+ }++ sink.finish()?;+ yield axum::body::Bytes::from(buf.take());+ };++ let filename = format!("{}.{}", slug(&kb.name), format.extension());+ let mut headers = HeaderMap::new();+ headers.insert(+ header::CONTENT_TYPE,+ HeaderValue::from_static(format.content_type()),+ );+ if let Ok(v) = HeaderValue::from_str(&format!("attachment; filename=\"{filename}\"")) {+ headers.insert(header::CONTENT_DISPOSITION, v);+ }+ Ok((+ StatusCode::OK,+ headers,+ Body::from_stream(Box::pin(stream)+ as std::pin::Pin<+ Box<+ dyn futures_util::Stream<Item = Result<axum::body::Bytes, std::io::Error>>+ + Send,+ >,+ >),+ )+ .into_response())+}++/// 库里出的错在流中间只能变成 io 错误——响应头已经发出去了,改不了状态码。+fn io(e: AppError) -> std::io::Error {+ tracing::error!(error = %e, "导出中断");+ std::io::Error::other(e.to_string())+}++/// 文件名用的短名。ASCII 之外的字符不进 Content-Disposition 的 filename,+/// 中文库名会在那里变成一串问号+fn slug(name: &str) -> String {+ let mut out: String = name+ .chars()+ .map(|c| {+ if c.is_ascii_alphanumeric() {+ c.to_ascii_lowercase()+ } else {+ '-'+ }+ })+ .collect();+ while out.contains("--") {+ out = out.replace("--", "-");+ }+ let trimmed = out.trim_matches('-').to_string();+ if trimmed.is_empty() {+ "export".into()+ } else {+ trimmed+ }+}diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rsindex 6e0702c8..41d8743e 100644--- a/crates/utopia-server/src/api/mod.rs+++ b/crates/utopia-server/src/api/mod.rs@@ -5,6 +5,7 @@ mod chat;mod datasource_routes;pub(crate) mod documents_routes;mod events_routes;+mod export_routes;mod graph_routes;mod jobs_routes;mod kbs;@@ -89,6 +90,9 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {.route("/kbs/{id}/readiness", get(kbs::readiness)).route("/kbs/{id}/members", get(kbs::members)).route("/kbs/{id}/audit", get(kbs::audit_log))+ // 整库导出为 RDF(0020)。viewer 就能导:能看见的东西本来就能一条条抄走,+ // 拦在这里只是让诚实的人多花点力气+ .route("/kbs/{id}/export", get(export_routes::export))// 失败任务回队列(#216):库内给 Editor,全局给管理员.route("/kbs/{id}/jobs/failed", get(jobs_routes::failed_in_kb)).route("/kbs/{id}/jobs/requeue", post(jobs_routes::requeue_in_kb))diff --git a/crates/utopia-server/src/main.rs b/crates/utopia-server/src/main.rsindex 4154f7fc..8dc05d8d 100644--- a/crates/utopia-server/src/main.rs+++ b/crates/utopia-server/src/main.rs@@ -23,6 +23,7 @@ mod pack_alignment;mod pipeline;mod predicate_match;mod query_engine;+mod rdf;mod retrieval;mod state;mod type_resolution;diff --git a/crates/utopia-server/src/rdf.rs b/crates/utopia-server/src/rdf.rsnew file mode 100644index 00000000..ff433354--- /dev/null+++ b/crates/utopia-server/src/rdf.rs@@ -0,0 +1,961 @@+//! 账本 → RDF(0020)。+//!+//! 读的人不是另一个 Utopia,是一个手里有三元组库、要问「这个结论凭什么」的人。+//! 所以导出的内容是**区间与出处**,不只是当下的那些边——一份读起来干净自信、+//! 却没说其中一半在三月被撤回过的图,比没有导出更坏。+//!+//! 三件事定了这份文件的形状:+//!+//! 1. **导入来的类和关系留着原 IRI**(`entity_types.iri` / `relation_types.iri`)。+//! schema.org 的库导出去还是 `schema:Organization`,对面手里的词汇表对得上+//! 2. **区间挂在具体化语句上**,不是挂在三元组上。RDF-star 更自然但多数消费者+//! 还读不了,命名图在 Turtle 里根本没有——一份打不开的文件不叫导出+//! 3. **有标准词就不自造**:`prov:invalidatedAtTime` 说的正是我们记录轴上那件事,+//! 另起一个私名只会把一个大家都认识的概念藏起来++use std::io::Write;+use std::sync::{Arc, Mutex};++use chrono::{DateTime, Utc};+use oxrdf::vocab::{rdf, rdfs, xsd};+use oxrdf::{Literal, NamedNode, NamedNodeRef, Term, TripleRef};+use utopia_store::export::{+ ExportClass, ExportDerived, ExportDocument, ExportEntity, ExportFact, ExportRelation,+};+use uuid::Uuid;++const OWL: &str = "http://www.w3.org/2002/07/owl#";+const PROV: &str = "http://www.w3.org/ns/prov#";+const SCHEMA: &str = "https://schema.org/";+/// 没有标准词的那几样才落在这里:置信度、派生标记、模型原话。+///+/// **URN 而不是 http://**:域名还没定,而一个词汇表 IRI 一旦发出去就不该再改。+/// 指向一个我们并不提供的地址,比指向一个不承诺解引用的 URN 更糟+const UTOPIA: &str = "urn:utopia:ns:";++fn nn(iri: impl Into<String>) -> NamedNode {+ // 拼出来的 IRI 全部来自 uuid / 本体 key / 配置里的 base,越界的字符在+ // `Names::new` 就挡掉了;这里再失败只能是 bug,不该把整份导出变成 500+ NamedNode::new(iri.into()).expect("导出 IRI 必须合法")+}++fn owl(term: &str) -> NamedNode {+ nn(format!("{OWL}{term}"))+}+fn prov(term: &str) -> NamedNode {+ nn(format!("{PROV}{term}"))+}+fn schema(term: &str) -> NamedNode {+ nn(format!("{SCHEMA}{term}"))+}+fn utopia(term: &str) -> NamedNode {+ nn(format!("{UTOPIA}{term}"))+}++/// 这份导出里的 IRI 怎么造。+///+/// 缺省是 URN:`urn:utopia:kb:{kb}:entity:{uuid}`。**稳定优先于可解引用**——+/// 同一个库隔一年再导一次,两份文件必须对得上;而一个自部署的实例并不知道+/// 自己对外的地址是什么。按请求的 Host 头去造,等于让身份取决于走了哪个反代。+/// 部署方知道自己发布在哪时,`?base=https://…/` 换成 http IRI。+pub struct Names {+ prefix: String,+ sep: char,+}++impl Names {+ pub fn new(kb_id: Uuid, base: Option<&str>) -> Result<Self, String> {+ match base.map(str::trim).filter(|b| !b.is_empty()) {+ Some(base) => {+ if !(base.starts_with("http://") || base.starts_with("https://")) {+ return Err("`base` must be an http(s) IRI".into());+ }+ if base.contains(['<', '>', '"', '{', '}', '|', '\\', '^', '`', ' ']) {+ return Err("`base` contains characters that cannot appear in an IRI".into());+ }+ let trimmed = base.trim_end_matches('/');+ Ok(Self {+ prefix: format!("{trimmed}/kb/{kb_id}/"),+ sep: '/',+ })+ }+ None => Ok(Self {+ prefix: format!("urn:utopia:kb:{kb_id}:"),+ sep: ':',+ }),+ }+ }++ fn mint(&self, kind: &str, id: &str) -> NamedNode {+ nn(format!("{}{kind}{}{id}", self.prefix, self.sep))+ }++ pub fn entity(&self, id: Uuid) -> NamedNode {+ self.mint("entity", &id.to_string())+ }+ pub fn fact(&self, id: Uuid) -> NamedNode {+ self.mint("fact", &id.to_string())+ }+ pub fn derived(&self, id: Uuid) -> NamedNode {+ self.mint("derived", &id.to_string())+ }+ pub fn document(&self, id: Uuid) -> NamedNode {+ self.mint("document", &id.to_string())+ }+ pub fn rule(&self, id: Uuid) -> NamedNode {+ self.mint("rule", &id.to_string())+ }+ /// 本体自己长出来的类/关系用 **key** 而不是 uuid:key 是这个库内部就在用的+ /// 标识(`UNIQUE (kb_id, key)`,抽取提示词和 API 用的都是它),文件因此读得懂。+ /// 导入来的一律用原 IRI+ pub fn class(&self, c: &ExportClass) -> NamedNode {+ match c.iri.as_deref() {+ Some(iri) => NamedNode::new(iri).unwrap_or_else(|_| self.mint("class", &c.key)),+ None => self.mint("class", &c.key),+ }+ }+ pub fn relation(&self, r: &ExportRelation) -> NamedNode {+ match r.iri.as_deref() {+ Some(iri) => NamedNode::new(iri).unwrap_or_else(|_| self.mint("relation", &r.key)),+ None => self.mint("relation", &r.key),+ }+ }+}++/// 序列化器写进来的地方。写完一页就把攒下的字节取走发给客户端——+/// 几十万条事实不能先在内存里拼成一整个 String+#[derive(Clone, Default)]+pub struct SharedBuf(Arc<Mutex<Vec<u8>>>);++impl SharedBuf {+ pub fn take(&self) -> Vec<u8> {+ let mut guard = self.0.lock().expect("导出缓冲区被毒化");+ std::mem::take(&mut *guard)+ }+}++impl Write for SharedBuf {+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {+ self.0+ .lock()+ .expect("导出缓冲区被毒化")+ .extend_from_slice(buf);+ Ok(buf.len())+ }+ fn flush(&mut self) -> std::io::Result<()> {+ Ok(())+ }+}++/// 两种格式共用同一套三元组,只是落笔不同——`oxrdfio` 把两个序列化器收在+/// 同一个类型后面,所以这里没有分支。+pub struct Sink(oxrdfio::WriterQuadSerializer<SharedBuf>);++/// 前缀表。Turtle 里它决定文件读起来是 `schema:Organization` 还是一长串尖括号+const PREFIXES: [(&str, &str); 6] = [+ ("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"),+ ("rdfs", "http://www.w3.org/2000/01/rdf-schema#"),+ ("owl", OWL),+ ("xsd", "http://www.w3.org/2001/XMLSchema#"),+ ("prov", PROV),+ ("schema", SCHEMA),+];++impl Sink {+ pub fn new(format: Format, buf: SharedBuf) -> Self {+ let mut s = oxrdfio::RdfSerializer::from_format(format.rdf_format());+ for (p, iri) in PREFIXES {+ s = s.with_prefix(p, iri).expect("前缀表是常量,不该解析失败");+ }+ s = s+ .with_prefix("utopia", UTOPIA)+ .expect("前缀表是常量,不该解析失败");+ Sink(s.for_writer(buf))+ }++ fn triple(&mut self, t: TripleRef<'_>) -> std::io::Result<()> {+ self.0+ .serialize_quad(t.in_graph(oxrdf::GraphNameRef::DefaultGraph))+ }++ /// `s p o`,o 是资源。+ fn r(&mut self, s: &NamedNode, p: &NamedNode, o: &NamedNode) -> std::io::Result<()> {+ self.triple(TripleRef::new(s.as_ref(), p.as_ref(), o.as_ref()))+ }++ /// `s p o`,o 是字面值。+ fn l(&mut self, s: &NamedNode, p: &NamedNode, o: &Literal) -> std::io::Result<()> {+ self.triple(TripleRef::new(s.as_ref(), p.as_ref(), o.as_ref()))+ }++ pub fn finish(self) -> std::io::Result<()> {+ self.0.finish().map(|_| ())+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Format {+ Turtle,+ JsonLd,+}++impl Format {+ fn rdf_format(self) -> oxrdfio::RdfFormat {+ match self {+ Format::Turtle => oxrdfio::RdfFormat::Turtle,+ // streaming profile:按主语一组一组往外写,不在内存里攒出整个文档。+ // 导出是这个仓库里唯一一处「一次输出可能比库还大」的地方+ Format::JsonLd => oxrdfio::RdfFormat::JsonLd {+ profile: oxrdfio::JsonLdProfile::Streaming.into(),+ },+ }+ }++ pub fn parse(raw: Option<&str>) -> Option<Self> {+ match raw.unwrap_or("turtle").trim().to_ascii_lowercase().as_str() {+ "turtle" | "ttl" => Some(Format::Turtle),+ "jsonld" | "json-ld" | "json" => Some(Format::JsonLd),+ _ => None,+ }+ }+ pub fn content_type(self) -> &'static str {+ match self {+ Format::Turtle => "text/turtle; charset=utf-8",+ Format::JsonLd => "application/ld+json",+ }+ }+ pub fn extension(self) -> &'static str {+ match self {+ Format::Turtle => "ttl",+ Format::JsonLd => "jsonld",+ }+ }+}++fn dt(at: DateTime<Utc>) -> Literal {+ Literal::new_typed_literal(+ at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),+ xsd::DATE_TIME,+ )+}++/// 世界时间按**当时量到的精度**落字面值:只知道年份就写 `xsd:gYear`。+/// 一律写成 `xsd:date` 等于替账本补上它从来没有过的确定性+fn world_time(at: DateTime<Utc>, precision: Option<&str>) -> Literal {+ let iso = at.format("%Y-%m-%d").to_string();+ match precision {+ Some("year") => Literal::new_typed_literal(iso[..4].to_string(), xsd::G_YEAR),+ Some("month") => Literal::new_typed_literal(iso[..7].to_string(), xsd::G_YEAR_MONTH),+ _ => Literal::new_typed_literal(iso, xsd::DATE),+ }+}++fn text(s: impl Into<String>) -> Literal {+ Literal::new_simple_literal(s.into())+}++fn confidence(c: f32) -> Literal {+ Literal::new_typed_literal(format!("{c:.2}"), xsd::DECIMAL)+}++fn flag(b: bool) -> Literal {+ Literal::new_typed_literal(if b { "true" } else { "false" }, xsd::BOOLEAN)+}++/// 一次导出里要反复查的东西:类与关系的 IRI、属性的值域。+pub struct Vocabulary {+ pub classes: Vec<(Uuid, NamedNode)>,+ pub relations: Vec<(Uuid, NamedNode, Option<String>, Option<String>)>,+}++impl Vocabulary {+ pub fn class(&self, id: Uuid) -> Option<&NamedNode> {+ self.classes.iter().find(|(i, _)| *i == id).map(|(_, n)| n)+ }+ pub fn relation(&self, id: Uuid) -> Option<&NamedNode> {+ self.relations+ .iter()+ .find(|(i, _, _, _)| *i == id)+ .map(|(_, n, _, _)| n)+ }+ /// (datatype, unit)+ fn literal_shape(&self, id: Uuid) -> (Option<&str>, Option<&str>) {+ self.relations+ .iter()+ .find(|(i, _, _, _)| *i == id)+ .map(|(_, _, d, u)| (d.as_deref(), u.as_deref()))+ .unwrap_or((None, None))+ }+}++pub fn vocabulary(+ names: &Names,+ classes: &[ExportClass],+ relations: &[ExportRelation],+) -> Vocabulary {+ Vocabulary {+ classes: classes.iter().map(|c| (c.id, names.class(c))).collect(),+ relations: relations+ .iter()+ .map(|r| (r.id, names.relation(r), r.datatype.clone(), r.unit.clone()))+ .collect(),+ }+}++pub fn emit_class(sink: &mut Sink, vocab: &Vocabulary, c: &ExportClass) -> std::io::Result<()> {+ let iri = match vocab.class(c.id) {+ Some(n) => n.clone(),+ None => return Ok(()),+ };+ sink.r(&iri, &nn(rdf::TYPE.as_str()), &owl("Class"))?;+ sink.l(&iri, &nn(rdfs::LABEL.as_str()), &text(c.label.clone()))?;+ if !c.description.is_empty() {+ sink.l(+ &iri,+ &nn(rdfs::COMMENT.as_str()),+ &text(c.description.clone()),+ )?;+ }+ for parent in &c.parents {+ if let Some(p) = vocab.class(*parent) {+ let p = p.clone();+ sink.r(&iri, &nn(rdfs::SUB_CLASS_OF.as_str()), &p)?;+ }+ }+ for other in &c.disjoint {+ if let Some(o) = vocab.class(*other) {+ let o = o.clone();+ sink.r(&iri, &owl("disjointWith"), &o)?;+ }+ }+ Ok(())+}++pub fn emit_relation(+ sink: &mut Sink,+ vocab: &Vocabulary,+ r: &ExportRelation,+) -> std::io::Result<()> {+ let iri = match vocab.relation(r.id) {+ Some(n) => n.clone(),+ None => return Ok(()),+ };+ let kind = if r.kind == "attribute" {+ owl("DatatypeProperty")+ } else {+ owl("ObjectProperty")+ };+ sink.r(&iri, &nn(rdf::TYPE.as_str()), &kind)?;+ sink.l(&iri, &nn(rdfs::LABEL.as_str()), &text(r.label.clone()))?;+ if !r.description.is_empty() {+ sink.l(+ &iri,+ &nn(rdfs::COMMENT.as_str()),+ &text(r.description.clone()),+ )?;+ }+ // 公理照抄,一条不落:一致性检查就是按它们跑的,读的人要能自己复算+ for (on, term) in [+ (r.functional, "FunctionalProperty"),+ (r.inverse_functional, "InverseFunctionalProperty"),+ (r.is_transitive, "TransitiveProperty"),+ (r.is_symmetric, "SymmetricProperty"),+ (r.is_asymmetric, "AsymmetricProperty"),+ (r.is_irreflexive, "IrreflexiveProperty"),+ ] {+ if on {+ sink.r(&iri, &nn(rdf::TYPE.as_str()), &owl(term))?;+ }+ }+ for d in &r.domains {+ if let Some(c) = vocab.class(*d) {+ let c = c.clone();+ sink.r(&iri, &nn(rdfs::DOMAIN.as_str()), &c)?;+ }+ }+ for g in &r.ranges {+ if let Some(c) = vocab.class(*g) {+ let c = c.clone();+ sink.r(&iri, &nn(rdfs::RANGE.as_str()), &c)?;+ }+ }+ if let Some(unit) = &r.unit {+ sink.l(&iri, &utopia("unit"), &text(unit.clone()))?;+ }+ Ok(())+}++pub fn emit_entity(+ sink: &mut Sink,+ names: &Names,+ vocab: &Vocabulary,+ e: &ExportEntity,+) -> std::io::Result<()> {+ let iri = names.entity(e.id);+ sink.l(+ &iri,+ &nn(rdfs::LABEL.as_str()),+ &text(e.canonical_name.clone()),+ )?;+ // 类型可以没有(0009):没判出来就不写,而不是补一个 owl:Thing 充数+ if let Some(t) = e.type_id.and_then(|t| vocab.class(t)) {+ let t = t.clone();+ sink.r(&iri, &nn(rdf::TYPE.as_str()), &t)?;+ }+ Ok(())+}++pub fn emit_document(sink: &mut Sink, names: &Names, d: &ExportDocument) -> std::io::Result<()> {+ let iri = names.document(d.id);+ sink.r(&iri, &nn(rdf::TYPE.as_str()), &prov("Entity"))?;+ sink.l(&iri, &nn(rdfs::LABEL.as_str()), &text(d.filename.clone()))?;+ if let Some(key) = &d.external_key {+ sink.l(&iri, &utopia("externalKey"), &text(key.clone()))?;+ }+ if let Some(t) = d.doc_time {+ sink.l(&iri, &schema("datePublished"), &world_time(t, Some("day")))?;+ }+ sink.l(&iri, &prov("generatedAtTime"), &dt(d.created_at))?;+ // 删掉的文档仍在文件里:它的事实还挂着它当出处,抹掉出处等于抹掉证据链+ if let Some(t) = d.deleted_at {+ sink.l(&iri, &prov("invalidatedAtTime"), &dt(t))?;+ }+ Ok(())+}++/// 一条事实:具体化语句(必出)+ 现行三元组(只在现在仍持有且仍有效时出)。+pub fn emit_fact(+ sink: &mut Sink,+ names: &Names,+ vocab: &Vocabulary,+ f: &ExportFact,+ now: DateTime<Utc>,+) -> std::io::Result<()> {+ let stmt = names.fact(f.id);+ let subject = names.entity(f.subject_id);+ let predicate = f.predicate_id.and_then(|p| vocab.relation(p)).cloned();+ let object: Option<Term> = match (f.object_id, &f.object_value) {+ (Some(o), _) => Some(names.entity(o).into()),+ (None, Some(v)) => f.predicate_id.map(|p| {+ let (datatype, _) = vocab.literal_shape(p);+ literal_value(v, datatype).into()+ }),+ _ => None,+ };++ sink.r(&stmt, &nn(rdf::TYPE.as_str()), &nn(rdf::STATEMENT.as_str()))?;+ sink.r(&stmt, &nn(rdf::SUBJECT.as_str()), &subject)?;+ match (&predicate, &f.surface_predicate) {+ (Some(p), _) => sink.r(&stmt, &nn(rdf::PREDICATE.as_str()), p)?,+ // 本体没接住这条关系(0010):**不造一个谓词**。原话作为字面值留在这里,+ // 读的人看得见「系统听见的是这个词,而词汇表里没有它」+ (None, Some(word)) => sink.l(&stmt, &utopia("proposedPredicate"), &text(word.clone()))?,+ (None, None) => {}+ }+ if let Some(o) = &object {+ sink.triple(TripleRef::new(stmt.as_ref(), rdf::OBJECT, o.as_ref()))?;+ }+ emit_validity(+ sink,+ &stmt,+ f.valid_from,+ f.valid_from_precision.as_deref(),+ f.valid_to,+ f.valid_to_precision.as_deref(),+ )?;+ sink.l(&stmt, &prov("generatedAtTime"), &dt(f.recorded_at))?;+ if let Some(t) = f.invalidated_at {+ sink.l(&stmt, &prov("invalidatedAtTime"), &dt(t))?;+ }+ sink.l(&stmt, &utopia("confidence"), &confidence(f.confidence))?;+ if let Some(old) = f.supersedes {+ let old = names.fact(old);+ sink.r(&stmt, &utopia("supersedes"), &old)?;+ }+ for doc in &f.documents {+ let d = names.document(*doc);+ sink.r(&stmt, &prov("wasDerivedFrom"), &d)?;+ }+ for quote in &f.quotes {+ sink.l(&stmt, &utopia("quote"), &text(quote.clone()))?;+ }++ // 现行三元组:**仍被持有,且现在仍成立**。区间已闭合或已撤回的不写这一条,+ // 否则一个忽略具体化的消费者会读到「张三现在还管着那个项目」+ let held = f.invalidated_at.is_none();+ let ended =+ f.valid_to.is_some_and(|t| t <= now) || f.valid_to_precision.as_deref() == Some("unknown");+ let started = f.valid_from.is_none_or(|t| t <= now);+ if held && !ended && started {+ if let (Some(p), Some(o)) = (&predicate, &object) {+ sink.triple(TripleRef::new(subject.as_ref(), p.as_ref(), o.as_ref()))?;+ }+ }+ Ok(())+}++/// 派生事实(0002)。**不写现行三元组**:它是推出来的,不是谁断言的;+/// 一个忽略具体化的消费者不该把引擎的结论当成文档里的话+pub fn emit_derived(+ sink: &mut Sink,+ names: &Names,+ vocab: &Vocabulary,+ d: &ExportDerived,+) -> std::io::Result<()> {+ let stmt = names.derived(d.id);+ let rule = names.rule(d.rule_id);+ sink.r(&stmt, &nn(rdf::TYPE.as_str()), &nn(rdf::STATEMENT.as_str()))?;+ sink.r(+ &stmt,+ &nn(rdf::SUBJECT.as_str()),+ &names.entity(d.subject_id),+ )?;+ if let Some(p) = vocab.relation(d.predicate_id).cloned() {+ sink.r(&stmt, &nn(rdf::PREDICATE.as_str()), &p)?;+ }+ sink.r(&stmt, &nn(rdf::OBJECT.as_str()), &names.entity(d.object_id))?;+ sink.l(&stmt, &utopia("derived"), &flag(true))?;+ emit_validity(+ sink,+ &stmt,+ d.valid_from,+ d.valid_from_precision.as_deref(),+ d.valid_to,+ d.valid_to_precision.as_deref(),+ )?;+ sink.l(&stmt, &prov("generatedAtTime"), &dt(d.derived_at))?;+ if let Some(t) = d.invalidated_at {+ sink.l(&stmt, &prov("invalidatedAtTime"), &dt(t))?;+ }+ sink.l(&stmt, &utopia("confidence"), &confidence(d.confidence))?;+ sink.r(&stmt, &prov("wasGeneratedBy"), &rule)?;+ sink.r(&rule, &nn(rdf::TYPE.as_str()), &prov("Activity"))?;+ sink.l(&rule, &nn(rdfs::LABEL.as_str()), &text(d.rule.clone()))?;+ // 前提。审计顺着 prov:used 往下走一步就到断言,再走一步就到句子+ for premise in &d.premises {+ let p = names.fact(*premise);+ sink.r(&stmt, &prov("used"), &p)?;+ }+ Ok(())+}++fn emit_validity(+ sink: &mut Sink,+ stmt: &NamedNode,+ from: Option<DateTime<Utc>>,+ from_precision: Option<&str>,+ to: Option<DateTime<Utc>>,+ to_precision: Option<&str>,+) -> std::io::Result<()> {+ if let Some(t) = from {+ sink.l(stmt, &schema("validFrom"), &world_time(t, from_precision))?;+ }+ match (to, to_precision) {+ (Some(t), p) => sink.l(stmt, &schema("validThrough"), &world_time(t, p))?,+ // 「结束了,但不知道哪天」——账本专门为它留了一个状态,导出不能把它+ // 压成「至今仍成立」(那正是 valid_to 一列承载两个意思时的老毛病)+ (None, Some("unknown")) => sink.l(stmt, &utopia("endedUnknown"), &flag(true))?,+ (None, _) => {}+ }+ Ok(())+}++/// 属性事实的字面值。`{"value": …, "unit": …}` 或 `{"summary": …}`+fn literal_value(v: &serde_json::Value, datatype: Option<&str>) -> Literal {+ let raw = v.get("value").unwrap_or(v);+ let as_text = match raw {+ serde_json::Value::String(s) => s.clone(),+ serde_json::Value::Null => v+ .get("summary")+ .and_then(|s| s.as_str())+ .unwrap_or_default()+ .to_string(),+ other => other.to_string(),+ };+ let ty: NamedNodeRef<'_> = match datatype {+ Some("number") => xsd::DECIMAL,+ Some("date") => xsd::DATE,+ Some("bool") => xsd::BOOLEAN,+ _ => xsd::STRING,+ };+ Literal::new_typed_literal(as_text, ty)+}++#[cfg(test)]+mod tests {+ use super::*;+ use oxrdf::Quad;++ fn kb() -> Uuid {+ Uuid::parse_str("01a06dc4-f40a-7013-b09f-1b499e2e7441").unwrap()+ }++ fn id(n: u8) -> Uuid {+ Uuid::from_bytes([n; 16])+ }++ fn at(s: &str) -> DateTime<Utc> {+ s.parse().unwrap()+ }++ fn class(n: u8, key: &str, iri: Option<&str>) -> ExportClass {+ ExportClass {+ id: id(n),+ key: key.into(),+ label: key.into(),+ description: String::new(),+ iri: iri.map(str::to_string),+ parents: vec![],+ disjoint: vec![],+ }+ }++ fn relation(n: u8, key: &str, iri: Option<&str>, kind: &str) -> ExportRelation {+ ExportRelation {+ id: id(n),+ key: key.into(),+ label: key.into(),+ description: String::new(),+ iri: iri.map(str::to_string),+ kind: kind.into(),+ datatype: (kind == "attribute").then(|| "number".to_string()),+ unit: None,+ temporal: "state".into(),+ functional: true,+ inverse_functional: false,+ is_transitive: false,+ is_symmetric: false,+ is_asymmetric: false,+ is_irreflexive: false,+ domains: vec![],+ ranges: vec![],+ }+ }++ fn fact(n: u8) -> ExportFact {+ ExportFact {+ id: id(n),+ subject_id: id(10),+ predicate_id: Some(id(2)),+ surface_predicate: None,+ object_id: Some(id(11)),+ object_value: None,+ valid_from: None,+ valid_from_precision: None,+ valid_to: None,+ valid_to_precision: None,+ recorded_at: at("2026-01-01T00:00:00Z"),+ invalidated_at: None,+ confidence: 0.9,+ supersedes: None,+ documents: vec![],+ quotes: vec![],+ }+ }++ /// 导出一遍再解析回来。**必须解析回来**:断言字符串里有没有某一段,+ /// 证明不了这份文件是不是合法的 Turtle,而那正是导出唯一要保证的事+ fn export(format: Format, emit: impl FnOnce(&mut Sink, &Names, &Vocabulary)) -> Vec<Quad> {+ let names = Names::new(kb(), None).unwrap();+ let classes = vec![+ class(1, "person", Some("https://schema.org/Person")),+ class(3, "team", None),+ ];+ let relations = vec![+ relation(+ 2,+ "works_for",+ Some("https://schema.org/worksFor"),+ "relation",+ ),+ relation(4, "headcount", None, "attribute"),+ ];+ let vocab = vocabulary(&names, &classes, &relations);+ let buf = SharedBuf::default();+ let mut sink = Sink::new(format, buf.clone());+ for c in &classes {+ emit_class(&mut sink, &vocab, c).unwrap();+ }+ for r in &relations {+ emit_relation(&mut sink, &vocab, r).unwrap();+ }+ emit(&mut sink, &names, &vocab);+ sink.finish().unwrap();+ let bytes = buf.take();+ oxrdfio::RdfParser::from_format(match format {+ Format::Turtle => oxrdfio::RdfFormat::Turtle,+ Format::JsonLd => oxrdfio::RdfFormat::JsonLd {+ profile: oxrdfio::JsonLdProfileSet::empty(),+ },+ })+ .for_slice(&bytes)+ .map(|q| q.expect("导出的文件必须解析得回来"))+ .collect()+ }++ fn has(quads: &[Quad], s: &str, p: &str, o: &str) -> bool {+ quads.iter().any(|q| {+ q.subject.to_string() == s && q.predicate.to_string() == format!("<{p}>") && {+ let obj = q.object.to_string();+ obj == o || obj == format!("<{o}>")+ }+ })+ }++ fn objects(quads: &[Quad], s: &str, p: &str) -> Vec<String> {+ quads+ .iter()+ .filter(|q| q.subject.to_string() == s && q.predicate.to_string() == format!("<{p}>"))+ .map(|q| q.object.to_string())+ .collect()+ }++ const STMT: &str = "<urn:utopia:kb:01a06dc4-f40a-7013-b09f-1b499e2e7441:fact:05050505-0505-0505-0505-050505050505>";+ const SUBJ: &str = "<urn:utopia:kb:01a06dc4-f40a-7013-b09f-1b499e2e7441:entity:0a0a0a0a-0a0a-0a0a-0a0a-0a0a0a0a0a0a>";+ const OBJ: &str = "<urn:utopia:kb:01a06dc4-f40a-7013-b09f-1b499e2e7441:entity:0b0b0b0b-0b0b-0b0b-0b0b-0b0b0b0b0b0b>";+ const WORKS_FOR: &str = "https://schema.org/worksFor";++ #[test]+ fn an_imported_class_keeps_its_own_iri() {+ let quads = export(Format::Turtle, |_, _, _| {});+ // 导入来的 schema.org 类导出去还是 schema:Person+ assert!(has(+ &quads,+ "<https://schema.org/Person>",+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",+ "http://www.w3.org/2002/07/owl#Class"+ ));+ // 本体自己长的用 key 铸 IRI,读得懂+ assert!(has(+ &quads,+ "<urn:utopia:kb:01a06dc4-f40a-7013-b09f-1b499e2e7441:class:team>",+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",+ "http://www.w3.org/2002/07/owl#Class"+ ));+ // 公理照抄:一致性检查按它跑,读的人要能自己复算+ assert!(has(+ &quads,+ &format!("<{WORKS_FOR}>"),+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",+ "http://www.w3.org/2002/07/owl#FunctionalProperty"+ ));+ }++ #[test]+ fn a_live_fact_is_both_a_statement_and_a_triple() {+ let quads = export(Format::Turtle, |sink, names, vocab| {+ emit_fact(sink, names, vocab, &fact(5), at("2026-06-01T00:00:00Z")).unwrap();+ });+ assert!(has(+ &quads,+ STMT,+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement"+ ));+ assert!(has(+ &quads,+ STMT,+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#subject",+ SUBJ+ ));+ assert!(+ has(&quads, SUBJ, WORKS_FOR, OBJ),+ "仍然成立的事实要有一条平铺三元组——不看具体化的消费者靠它拿到现状"+ );+ assert_eq!(+ objects(&quads, STMT, "urn:utopia:ns:confidence"),+ vec!["\"0.90\"^^<http://www.w3.org/2001/XMLSchema#decimal>"]+ );+ }++ #[test]+ fn a_closed_or_retracted_fact_is_a_statement_only() {+ // 区间已闭合:世界轴上它已经结束+ let mut closed = fact(5);+ closed.valid_from = Some(at("2023-01-01T00:00:00Z"));+ closed.valid_from_precision = Some("day".into());+ closed.valid_to = Some(at("2024-07-01T00:00:00Z"));+ closed.valid_to_precision = Some("day".into());+ let quads = export(Format::Turtle, |sink, names, vocab| {+ emit_fact(sink, names, vocab, &closed, at("2026-06-01T00:00:00Z")).unwrap();+ });+ assert!(+ !has(&quads, SUBJ, WORKS_FOR, OBJ),+ "结束了的关系不该以现在时写出去——那正是导出会骗人的地方"+ );+ assert_eq!(+ objects(&quads, STMT, "https://schema.org/validThrough"),+ vec!["\"2024-07-01\"^^<http://www.w3.org/2001/XMLSchema#date>"]+ );++ // 记录轴上被撤回:世界轴上它甚至还"开着",但我们已经不这么认为了+ let mut retracted = fact(5);+ retracted.invalidated_at = Some(at("2026-03-01T00:00:00Z"));+ let quads = export(Format::Turtle, |sink, names, vocab| {+ emit_fact(sink, names, vocab, &retracted, at("2026-06-01T00:00:00Z")).unwrap();+ });+ assert!(!has(&quads, SUBJ, WORKS_FOR, OBJ), "撤回的不出平铺三元组");+ assert_eq!(+ objects(&quads, STMT, "http://www.w3.org/ns/prov#invalidatedAtTime"),+ vec!["\"2026-03-01T00:00:00Z\"^^<http://www.w3.org/2001/XMLSchema#dateTime>"]+ );+ }++ #[test]+ fn a_year_stays_a_year() {+ let mut coarse = fact(5);+ coarse.valid_from = Some(at("2023-01-01T00:00:00Z"));+ coarse.valid_from_precision = Some("year".into());+ let quads = export(Format::Turtle, |sink, names, vocab| {+ emit_fact(sink, names, vocab, &coarse, at("2026-06-01T00:00:00Z")).unwrap();+ });+ // 只量到年份就写 gYear。一律写成 xsd:date 等于替账本补上它没有过的确定性+ assert_eq!(+ objects(&quads, STMT, "https://schema.org/validFrom"),+ vec!["\"2023\"^^<http://www.w3.org/2001/XMLSchema#gYear>"]+ );+ }++ #[test]+ fn an_ended_but_undated_relation_says_so() {+ let mut ended = fact(5);+ ended.valid_to = None;+ ended.valid_to_precision = Some("unknown".into());+ let quads = export(Format::Turtle, |sink, names, vocab| {+ emit_fact(sink, names, vocab, &ended, at("2026-06-01T00:00:00Z")).unwrap();+ });+ // 「结束了,但不知道哪天」不能压成「至今仍成立」+ assert!(has(+ &quads,+ STMT,+ "urn:utopia:ns:endedUnknown",+ "\"true\"^^<http://www.w3.org/2001/XMLSchema#boolean>"+ ));+ assert!(!has(&quads, SUBJ, WORKS_FOR, OBJ));+ }++ #[test]+ fn a_predicate_the_ontology_never_accepted_is_not_invented() {+ let mut bare = fact(5);+ bare.predicate_id = None;+ bare.surface_predicate = Some("acquired".into());+ let quads = export(Format::Turtle, |sink, names, vocab| {+ emit_fact(sink, names, vocab, &bare, at("2026-06-01T00:00:00Z")).unwrap();+ });+ assert!(+ objects(+ &quads,+ STMT,+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate"+ )+ .is_empty(),+ "本体没有这条关系就不铸一个谓词出来(0010)"+ );+ assert_eq!(+ objects(&quads, STMT, "urn:utopia:ns:proposedPredicate"),+ vec!["\"acquired\""]+ );+ }++ #[test]+ fn an_attribute_carries_its_datatype() {+ let mut attr = fact(5);+ attr.predicate_id = Some(id(4));+ attr.object_id = None;+ attr.object_value = Some(serde_json::json!({ "value": 42, "unit": "people" }));+ let quads = export(Format::Turtle, |sink, names, vocab| {+ emit_fact(sink, names, vocab, &attr, at("2026-06-01T00:00:00Z")).unwrap();+ });+ assert_eq!(+ objects(+ &quads,+ STMT,+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#object"+ ),+ vec!["\"42\"^^<http://www.w3.org/2001/XMLSchema#decimal>"]+ );+ }++ #[test]+ fn a_derivation_says_it_is_one_and_names_its_premises() {+ let derived = ExportDerived {+ id: id(7),+ subject_id: id(10),+ predicate_id: id(2),+ object_id: id(11),+ rule_id: id(8),+ valid_from: None,+ valid_from_precision: None,+ valid_to: None,+ valid_to_precision: None,+ derived_at: at("2026-02-01T00:00:00Z"),+ invalidated_at: None,+ confidence: 0.8,+ rule: "transitive".into(),+ premises: vec![id(5)],+ };+ let quads = export(Format::Turtle, |sink, names, vocab| {+ emit_derived(sink, names, vocab, &derived).unwrap();+ });+ let stmt = "<urn:utopia:kb:01a06dc4-f40a-7013-b09f-1b499e2e7441:derived:07070707-0707-0707-0707-070707070707>";+ assert!(has(+ &quads,+ stmt,+ "urn:utopia:ns:derived",+ "\"true\"^^<http://www.w3.org/2001/XMLSchema#boolean>"+ ));+ assert_eq!(+ objects(&quads, stmt, "http://www.w3.org/ns/prov#used"),+ vec![STMT]+ );+ assert!(+ !has(&quads, SUBJ, WORKS_FOR, OBJ),+ "推出来的边不写成平铺三元组:那会让人把引擎的结论当成文档里的话"+ );+ }++ #[test]+ fn evidence_points_back_at_the_document_and_the_sentence() {+ let mut cited = fact(5);+ cited.documents = vec![id(12)];+ cited.quotes = vec!["Lin Zhao joined Acme in 2023.".into()];+ let quads = export(Format::Turtle, |sink, names, vocab| {+ emit_fact(sink, names, vocab, &cited, at("2026-06-01T00:00:00Z")).unwrap();+ });+ assert_eq!(+ objects(&quads, STMT, "http://www.w3.org/ns/prov#wasDerivedFrom"),+ vec!["<urn:utopia:kb:01a06dc4-f40a-7013-b09f-1b499e2e7441:document:0c0c0c0c-0c0c-0c0c-0c0c-0c0c0c0c0c0c>"]+ );+ assert_eq!(+ objects(&quads, STMT, "urn:utopia:ns:quote"),+ vec!["\"Lin Zhao joined Acme in 2023.\""]+ );+ }++ #[test]+ fn json_ld_carries_the_same_triples() {+ let emit = |sink: &mut Sink, names: &Names, vocab: &Vocabulary| {+ emit_fact(sink, names, vocab, &fact(5), at("2026-06-01T00:00:00Z")).unwrap();+ };+ let ttl = export(Format::Turtle, emit);+ let jsonld = export(Format::JsonLd, emit);+ assert_eq!(+ ttl.len(),+ jsonld.len(),+ "两种格式是同一张图的两种写法,三元组数目必须一样"+ );+ assert!(has(&jsonld, SUBJ, WORKS_FOR, OBJ));+ }++ #[test]+ fn a_published_deployment_can_mint_http_iris() {+ let names = Names::new(kb(), Some("https://acme.example/utopia/")).unwrap();+ assert_eq!(+ names.entity(id(10)).as_str(),+ "https://acme.example/utopia/kb/01a06dc4-f40a-7013-b09f-1b499e2e7441/entity/0a0a0a0a-0a0a-0a0a-0a0a-0a0a0a0a0a0a"+ );+ // 非 http 的 base 拒掉:拼出来的会是一份谁也解析不了的文件+ assert!(Names::new(kb(), Some("javascript:alert(1)")).is_err());+ assert!(Names::new(kb(), Some("https://acme.example/a b")).is_err());+ }+}diff --git a/crates/utopia-store/src/export.rs b/crates/utopia-store/src/export.rsnew file mode 100644index 00000000..70bc1fdb--- /dev/null+++ b/crates/utopia-store/src/export.rs@@ -0,0 +1,232 @@+//! 导出用的读取面(0020)。+//!+//! 与界面那几个视图分开写,因为问的东西不一样:界面要「现在是什么样」,+//! 导出要**全部**——闭合的区间、撤回的行、修正链,一条都不能少,否则导出的+//! 是一张干净自信的图,而那正是审计要看的东西被抹掉的样子。+//!+//! 除本体外一律**按 id 分页**:一个库的事实可以有几十万条,全读进内存再序列化+//! 会在最需要它的那种部署上炸掉。id 是 uuid v7,按它排序即按写入顺序排序。++use chrono::{DateTime, Utc};+use sqlx::PgPool;+use utopia_core::AppResult;+use uuid::Uuid;++/// 一次取多少行。够大以免把往返次数拉满,够小以免一页就撑爆内存。+pub const PAGE: i64 = 500;++#[derive(Debug, Clone, sqlx::FromRow)]+pub struct ExportClass {+ pub id: Uuid,+ pub key: String,+ pub label: String,+ pub description: String,+ /// 导入来的类留着它原来的 IRI——schema.org 的 Organization 导出去还是+ /// `schema:Organization`,读的人手里的词汇表对得上+ pub iri: Option<String>,+ pub parents: Vec<Uuid>,+ pub disjoint: Vec<Uuid>,+}++#[derive(Debug, Clone, sqlx::FromRow)]+pub struct ExportRelation {+ pub id: Uuid,+ pub key: String,+ pub label: String,+ pub description: String,+ pub iri: Option<String>,+ /// relation | attribute(后者值域是字面值)+ pub kind: String,+ pub datatype: Option<String>,+ pub unit: Option<String>,+ pub temporal: String,+ pub functional: bool,+ pub inverse_functional: bool,+ pub is_transitive: bool,+ pub is_symmetric: bool,+ pub is_asymmetric: bool,+ pub is_irreflexive: bool,+ pub domains: Vec<Uuid>,+ pub ranges: Vec<Uuid>,+}++#[derive(Debug, Clone, sqlx::FromRow)]+pub struct ExportEntity {+ pub id: Uuid,+ pub canonical_name: String,+ pub type_id: Option<Uuid>,+}++#[derive(Debug, Clone, sqlx::FromRow)]+pub struct ExportFact {+ pub id: Uuid,+ pub subject_id: Uuid,+ pub predicate_id: Option<Uuid>,+ /// 本体没接住这条关系时,模型的原话(0010)。导出去是为了让读的人看见+ /// 「系统当时听见的是这个词,而词汇表里没有」+ pub surface_predicate: Option<String>,+ pub object_id: Option<Uuid>,+ pub object_value: Option<serde_json::Value>,+ pub valid_from: Option<DateTime<Utc>>,+ pub valid_from_precision: Option<String>,+ pub valid_to: Option<DateTime<Utc>>,+ pub valid_to_precision: Option<String>,+ pub recorded_at: DateTime<Utc>,+ pub invalidated_at: Option<DateTime<Utc>>,+ pub confidence: f32,+ pub supersedes: Option<Uuid>,+ pub documents: Vec<Uuid>,+ pub quotes: Vec<String>,+}++#[derive(Debug, Clone, sqlx::FromRow)]+pub struct ExportDerived {+ pub id: Uuid,+ pub subject_id: Uuid,+ pub predicate_id: Uuid,+ pub object_id: Uuid,+ pub rule_id: Uuid,+ pub valid_from: Option<DateTime<Utc>>,+ pub valid_from_precision: Option<String>,+ pub valid_to: Option<DateTime<Utc>>,+ pub valid_to_precision: Option<String>,+ pub derived_at: DateTime<Utc>,+ pub invalidated_at: Option<DateTime<Utc>>,+ pub confidence: f32,+ /// transitive | symmetric+ pub rule: String,+ /// 前提事实。审计要顺着它往下走到句子+ pub premises: Vec<Uuid>,+}++#[derive(Debug, Clone, sqlx::FromRow)]+pub struct ExportDocument {+ pub id: Uuid,+ pub filename: String,+ pub external_key: Option<String>,+ pub doc_time: Option<DateTime<Utc>>,+ pub created_at: DateTime<Utc>,+ /// 删过的文档留着墓碑(#268)。导出里它仍在,只是记录轴上已经结束+ pub deleted_at: Option<DateTime<Utc>>,+}++pub async fn classes(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<ExportClass>> {+ Ok(sqlx::query_as(+ "SELECT t.id, t.key, t.label, t.description, t.iri,+ COALESCE(ARRAY(SELECT p.parent_id FROM entity_type_parents p+ WHERE p.child_id = t.id ORDER BY p.parent_id), '{}') AS parents,+ COALESCE(ARRAY(SELECT CASE WHEN d.a_id = t.id THEN d.b_id ELSE d.a_id END+ FROM entity_type_disjoint d+ WHERE d.kb_id = $1 AND (d.a_id = t.id OR d.b_id = t.id)+ ORDER BY 1), '{}') AS disjoint+ FROM entity_types t WHERE t.kb_id = $1 ORDER BY t.key",+ )+ .bind(kb_id)+ .fetch_all(pool)+ .await?)+}++pub async fn relations(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<ExportRelation>> {+ Ok(sqlx::query_as(+ "SELECT r.id, r.key, r.label, r.description, r.iri, r.kind, r.datatype, r.unit,+ r.temporal, r.functional, r.inverse_functional,+ r.is_transitive, r.is_symmetric, r.is_asymmetric, r.is_irreflexive,+ COALESCE(ARRAY(SELECT d.entity_type_id FROM relation_type_domains d+ WHERE d.relation_type_id = r.id ORDER BY 1), '{}') AS domains,+ COALESCE(ARRAY(SELECT g.entity_type_id FROM relation_type_ranges g+ WHERE g.relation_type_id = r.id ORDER BY 1), '{}') AS ranges+ FROM relation_types r WHERE r.kb_id = $1 ORDER BY r.key",+ )+ .bind(kb_id)+ .fetch_all(pool)+ .await?)+}++/// 合并掉的实体不导出:它已经不是一个东西了,它的事实早已搬到留下的那个身上。+pub async fn entities_page(+ pool: &PgPool,+ kb_id: Uuid,+ after: Option<Uuid>,+) -> AppResult<Vec<ExportEntity>> {+ Ok(sqlx::query_as(+ "SELECT id, canonical_name, type_id FROM entities+ WHERE kb_id = $1 AND merged_into IS NULL AND id > COALESCE($2, '00000000-0000-0000-0000-000000000000'::uuid)+ ORDER BY id LIMIT $3",+ )+ .bind(kb_id)+ .bind(after)+ .bind(PAGE)+ .fetch_all(pool)+ .await?)+}++/// **不过滤 `invalidated_at`。** 撤回的、被修正顶掉的、区间早已闭合的,全在里面+/// ——它们各自带着两根轴上的时刻,读的人自己判断当时成立不成立(0019、0020)。+pub async fn facts_page(+ pool: &PgPool,+ kb_id: Uuid,+ after: Option<Uuid>,+) -> AppResult<Vec<ExportFact>> {+ Ok(sqlx::query_as(+ "SELECT f.id, f.subject_id, f.predicate_id,+ fact_surface_predicate(f.id) AS surface_predicate,+ f.object_id, f.object_value,+ f.valid_from, f.valid_from_precision, f.valid_to, f.valid_to_precision,+ f.recorded_at, f.invalidated_at, f.confidence, f.supersedes,+ COALESCE(ARRAY(SELECT DISTINCT e.document_id FROM fact_evidence e+ WHERE e.fact_id = f.id AND e.document_id IS NOT NULL), '{}')+ AS documents,+ COALESCE(ARRAY(SELECT e.quote FROM fact_evidence e+ WHERE e.fact_id = f.id AND e.quote IS NOT NULL+ ORDER BY e.chunk_id), '{}') AS quotes+ FROM facts f+ WHERE f.kb_id = $1 AND f.id > COALESCE($2, '00000000-0000-0000-0000-000000000000'::uuid)+ ORDER BY f.id LIMIT $3",+ )+ .bind(kb_id)+ .bind(after)+ .bind(PAGE)+ .fetch_all(pool)+ .await?)+}++pub async fn derived_page(+ pool: &PgPool,+ kb_id: Uuid,+ after: Option<Uuid>,+) -> AppResult<Vec<ExportDerived>> {+ Ok(sqlx::query_as(+ "SELECT d.id, d.subject_id, d.predicate_id, d.object_id, d.rule_id,+ d.valid_from, d.valid_from_precision, d.valid_to, d.valid_to_precision,+ d.derived_at, d.invalidated_at, d.confidence,+ ru.kind AS rule,+ COALESCE(ARRAY(SELECT fd.premise_fact_id FROM fact_derivations fd+ WHERE fd.derived_fact_id = d.id ORDER BY fd.seq), '{}') AS premises+ FROM derived_facts d JOIN rules ru ON ru.id = d.rule_id+ WHERE d.kb_id = $1 AND d.id > COALESCE($2, '00000000-0000-0000-0000-000000000000'::uuid)+ ORDER BY d.id LIMIT $3",+ )+ .bind(kb_id)+ .bind(after)+ .bind(PAGE)+ .fetch_all(pool)+ .await?)+}++pub async fn documents_page(+ pool: &PgPool,+ kb_id: Uuid,+ after: Option<Uuid>,+) -> AppResult<Vec<ExportDocument>> {+ Ok(sqlx::query_as(+ "SELECT id, filename, external_key, doc_time, created_at, deleted_at+ FROM documents+ WHERE kb_id = $1 AND id > COALESCE($2, '00000000-0000-0000-0000-000000000000'::uuid)+ ORDER BY id LIMIT $3",+ )+ .bind(kb_id)+ .bind(after)+ .bind(PAGE)+ .fetch_all(pool)+ .await?)+}diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rsindex 151fcac4..6713cee2 100644--- a/crates/utopia-store/src/lib.rs+++ b/crates/utopia-store/src/lib.rs@@ -9,6 +9,7 @@ pub mod conversations;pub mod datasources;pub mod db;pub mod documents;+pub mod export;pub mod extraction_drops;pub mod graph;pub mod jobs;diff --git a/crates/utopia-store/tests/an_export_carries_the_whole_ledger.rs b/crates/utopia-store/tests/an_export_carries_the_whole_ledger.rsnew file mode 100644index 00000000..908b3e8e--- /dev/null+++ b/crates/utopia-store/tests/an_export_carries_the_whole_ledger.rs@@ -0,0 +1,288 @@+//! 导出读的是**整本账**(0020 / #308),打在真库上。+//!+//! 界面那些读路径全都过滤 `invalidated_at`——它们答的是「现在是什么样」。+//! 导出如果照抄那套过滤,导出去的就是一张干净自信的图,而三月被撤回的那一半+//! 一个字都不剩。审计要的恰恰是那一半。+//!+//! 所以这里断言的都是「**没有**被过滤掉」:撤回的事实在、删掉的文档在、+//! 本体没接住的原话在、派生的前提在。合并掉的实体是唯一该消失的东西——+//! 它的事实早已搬到留下的那个身上,再导一遍就是把同一条事实说两遍。++use sqlx::PgPool;+use uuid::Uuid;++struct Fixture {+ org: Uuid,+ kb: Uuid,+ live: Uuid,+ retracted: Uuid,+ bare: Uuid,+ kept: Uuid,+ swallowed: Uuid,+ deleted_doc: Uuid,+ derived: Uuid,+}++async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ let (person, company) = (Uuid::now_v7(), Uuid::now_v7());+ let (works_for, part_of) = (Uuid::now_v7(), Uuid::now_v7());+ let (kept, swallowed, acme, group) = (+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ );+ let (doc, deleted_doc, chunk) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ let (live, retracted, bare) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ let (rule, derived) = (Uuid::now_v7(), Uuid::now_v7());+ let tag = Uuid::now_v7();++ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'export-test')")+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'export-test')")+ .bind(ws)+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'export-test')",+ )+ .bind(kb)+ .bind(ws)+ .execute(pool)+ .await?;+ for (id, key, label, iri) in [+ (+ person,+ "person",+ "Person",+ Some("https://schema.org/Person"),+ ),+ (company, "company", "Company", None),+ ] {+ sqlx::query(+ "INSERT INTO entity_types (id, kb_id, key, label, iri) VALUES ($1, $2, $3, $4, $5)",+ )+ .bind(id)+ .bind(kb)+ .bind(key)+ .bind(label)+ .bind(iri)+ .execute(pool)+ .await?;+ }+ sqlx::query(+ "INSERT INTO relation_types (id, kb_id, key, label, iri, functional)+ VALUES ($1, $2, 'works_for', 'works for', 'https://schema.org/worksFor', TRUE)",+ )+ .bind(works_for)+ .bind(kb)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO relation_types (id, kb_id, key, label, is_transitive)+ VALUES ($1, $2, 'part_of', 'part of', TRUE)",+ )+ .bind(part_of)+ .bind(kb)+ .execute(pool)+ .await?;+ for (id, type_id, name) in [+ (kept, person, "Lin Zhao"),+ (swallowed, person, "L. Zhao"),+ (acme, company, "Acme"),+ (group, company, "Acme Group"),+ ] {+ sqlx::query(+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",+ )+ .bind(id)+ .bind(kb)+ .bind(type_id)+ .bind(name)+ .execute(pool)+ .await?;+ }+ // 合并掉的那个:事实早已搬走,导出里不该再出现+ sqlx::query("UPDATE entities SET merged_into = $2 WHERE id = $1")+ .bind(swallowed)+ .bind(kept)+ .execute(pool)+ .await?;++ for (id, name, deleted) in [(doc, "handbook.md", false), (deleted_doc, "old.md", true)] {+ sqlx::query(+ "INSERT INTO documents (id, kb_id, filename, sha256, status, external_key, deleted_at)+ VALUES ($1, $2, $3, $4, 'ready', $5,+ CASE WHEN $6 THEN now() ELSE NULL END)",+ )+ .bind(id)+ .bind(kb)+ .bind(name)+ .bind(format!("sha-{tag}-{name}"))+ .bind(format!("file:///{name}"))+ .bind(deleted)+ .execute(pool)+ .await?;+ }+ sqlx::query(+ "INSERT INTO chunks (id, kb_id, document_id, seq, text)+ VALUES ($1, $2, $3, 0, 'Lin Zhao works for Acme.')",+ )+ .bind(chunk)+ .bind(kb)+ .bind(doc)+ .execute(pool)+ .await?;++ let fact = |id: Uuid, predicate: Option<Uuid>, object: Uuid, invalidated: bool| {+ sqlx::query(+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, confidence,+ invalidated_at)+ VALUES ($1, $2, $3, $4, $5, 0.9,+ CASE WHEN $6 THEN now() ELSE NULL END)",+ )+ .bind(id)+ .bind(kb)+ .bind(kept)+ .bind(predicate)+ .bind(object)+ .bind(invalidated)+ };+ fact(live, Some(works_for), acme, false)+ .execute(pool)+ .await?;+ fact(retracted, Some(works_for), group, true)+ .execute(pool)+ .await?;+ // 本体没接住的那条(0010):谓词为空,原话在证据里+ fact(bare, None, group, false).execute(pool).await?;+ sqlx::query(+ "INSERT INTO fact_evidence (fact_id, chunk_id, quote, document_id, proposed_predicate)+ VALUES ($1, $2, 'Lin Zhao works for Acme.', $3, NULL),+ ($4, $2, 'Lin Zhao advises Acme Group.', $3, 'advises')",+ )+ .bind(live)+ .bind(chunk)+ .bind(doc)+ .bind(bare)+ .execute(pool)+ .await?;++ sqlx::query(+ "INSERT INTO rules (id, kb_id, predicate_id, kind) VALUES ($1, $2, $3, 'transitive')",+ )+ .bind(rule)+ .bind(kb)+ .bind(part_of)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO derived_facts (id, kb_id, subject_id, predicate_id, object_id, rule_id)+ VALUES ($1, $2, $3, $4, $5, $6)",+ )+ .bind(derived)+ .bind(kb)+ .bind(acme)+ .bind(part_of)+ .bind(group)+ .bind(rule)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO fact_derivations (derived_fact_id, premise_fact_id, seq) VALUES ($1, $2, 0)",+ )+ .bind(derived)+ .bind(live)+ .execute(pool)+ .await?;++ Ok(Fixture {+ org,+ kb,+ live,+ retracted,+ bare,+ kept,+ swallowed,+ deleted_doc,+ derived,+ })+}++#[tokio::test]+async fn an_export_reads_the_whole_ledger_not_the_current_view() -> anyhow::Result<()> {+ let Some(url) = utopia_store::test_db::url() else {+ return Ok(());+ };+ let pool = PgPool::connect(&url).await?;+ let f = seed(&pool).await?;++ // 1. 事实:撤回的那条**在**。界面把它藏起来是对的,导出把它藏起来就是骗人+ let facts = utopia_store::export::facts_page(&pool, f.kb, None).await?;+ let ids: Vec<Uuid> = facts.iter().map(|x| x.id).collect();+ assert!(ids.contains(&f.live));+ assert!(+ ids.contains(&f.retracted),+ "撤回的事实必须导出——它带着 invalidated_at,读的人自己判断"+ );+ let retracted = facts.iter().find(|x| x.id == f.retracted).unwrap();+ assert!(retracted.invalidated_at.is_some());++ // 2. 证据跟着事实走:出处文档与原句都在同一行上+ let live = facts.iter().find(|x| x.id == f.live).unwrap();+ assert_eq!(live.documents.len(), 1);+ assert_eq!(live.quotes, vec!["Lin Zhao works for Acme."]);++ // 3. 本体没接住的那条:谓词为空,但模型的原话拿得到——导出里它不会+ // 被铸成一个假谓词,也不会消失+ let bare = facts.iter().find(|x| x.id == f.bare).unwrap();+ assert!(bare.predicate_id.is_none());+ assert_eq!(bare.surface_predicate.as_deref(), Some("advises"));++ // 4. 实体:合并掉的那个是唯一该消失的东西+ let entities = utopia_store::export::entities_page(&pool, f.kb, None).await?;+ let ids: Vec<Uuid> = entities.iter().map(|e| e.id).collect();+ assert!(ids.contains(&f.kept));+ assert!(+ !ids.contains(&f.swallowed),+ "合并掉的实体再导一遍,等于把同一条事实说两遍"+ );++ // 5. 文档:删掉的留着墓碑(#268)。抹掉出处等于抹掉证据链+ let docs = utopia_store::export::documents_page(&pool, f.kb, None).await?;+ let deleted = docs.iter().find(|d| d.id == f.deleted_doc).unwrap();+ assert!(deleted.deleted_at.is_some());++ // 6. 派生:带着规则和前提,审计顺着它走得到断言+ let derived = utopia_store::export::derived_page(&pool, f.kb, None).await?;+ let d = derived.iter().find(|d| d.id == f.derived).unwrap();+ assert_eq!(d.rule, "transitive");+ assert_eq!(d.premises, vec![f.live]);++ // 7. 词汇表:导入来的类留着原 IRI,公理位照抄+ let classes = utopia_store::export::classes(&pool, f.kb).await?;+ let person = classes.iter().find(|c| c.key == "person").unwrap();+ assert_eq!(person.iri.as_deref(), Some("https://schema.org/Person"));+ let relations = utopia_store::export::relations(&pool, f.kb).await?;+ assert!(relations+ .iter()+ .any(|r| r.key == "works_for" && r.functional));+ assert!(relations+ .iter()+ .any(|r| r.key == "part_of" && r.is_transitive));++ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")+ .bind(f.kb)+ .execute(&pool)+ .await?;+ let gone = sqlx::query("DELETE FROM organizations WHERE id = $1")+ .bind(f.org)+ .execute(&pool)+ .await?;+ assert_eq!(gone.rows_affected(), 1, "一次性 org 没删掉");+ Ok(())+}diff --git a/docs/decisions/0020-an-auditor-reads-it-without-us.md b/docs/decisions/0020-an-auditor-reads-it-without-us.mdnew file mode 100644index 00000000..d4e6332c--- /dev/null+++ b/docs/decisions/0020-an-auditor-reads-it-without-us.md@@ -0,0 +1,47 @@+# 0020 · An auditor reads it without us++- **Status**: implemented · `GET /api/v1/kbs/{id}/export?format=turtle|jsonld` streams the base as RDF; `rdf.rs` holds the mapping, `oxrdfio` the serialisers · SPARQL is still not here, and this record says why it can wait+- **Written**: 2026-09-05 (conventions in the [README](README.md))+- **Related**: [0001](0001-ontology-import-and-governance.md) kept the imported file verbatim and projected what today's consumers can use — this is the first consumer pointing the other way. [0015](0015-recording-a-sentence-is-not-asserting-a-fact.md) and [0019](0019-the-second-clock-can-be-rewound.md) are what makes the export worth reading: the intervals and the lineage are the content, not the triples++> `owl_import.rs` reads OWL in and five packs ship inside the binary. Nothing went the other way. The data an auditor asks for is all on disk — facts carry validity, evidence points at documents and versions, the ledger records who and when — and it could only leave in the shapes the REST API happened to expose.++## Who this is for++Not another Utopia. A regulator, an auditor, or the team's own graph tooling: someone who has a triple store and a question about a decision that was made, and who should not have to learn our JSON to answer it. That fixes what the export must carry — **the intervals and the lineage**, not just the current edges — and it fixes the failure mode: an export that reads as a clean, confident graph while dropping the fact that half of it was retracted in March is worse than no export.++## Identity++Classes and relations that came in from an import **keep the IRI they came with**. A base built from the schema.org pack exports `schema:Organization`, not a Utopia mint of it, so the file lines up with the vocabulary the reader already has. That is the payoff for having stored `iri` on `entity_types` and `relation_types` since the first import.++Everything else is minted under a base namespace: entities, documents, and one IRI per fact. Facts get their own IRI rather than blank nodes because a statement someone may have to cite has to be addressable, and because `supersedes` needs somewhere to point. A class or relation the ontology grew itself is minted from its **key** rather than its uuid — the key is what the base already uses as its identifier (`UNIQUE (kb_id, key)`, and it is what the extraction prompt and the API speak), so the file stays readable; a rename is the one event that moves such an IRI, and renaming a class is rarer than reading the export.++The default namespace is a URN — `urn:utopia:kb:{kb_id}:entity:{uuid}` — and `?base=https://…/` overrides it for a deployment that publishes at a known address. The default is stable rather than dereferenceable, which is the right way round: two exports of the same base a year apart must line up, and a self-hosted deployment does not know its own public URL. Minting from the request's `Host` header would have made identity depend on which proxy the exporter came through.++## Intervals ride on the statement, not the triple++A triple cannot say "until July 2024". The three ways to fix that:++| | Why not |+|---|---|+| RDF-star (`<< s p o >> :validFrom …`) | The natural shape, and the one most consumers still cannot parse. A file nobody can load is not an export |+| A named graph per fact | Legal in TriG and JSON-LD, absent from Turtle, and it turns a base into tens of thousands of graphs. Tooling that groups by graph becomes unusable |+| RDF 1.1 reification | Verbose, universally understood, and needs no feature flags |++Reification wins on the only criterion that matters here — the file has to open in whatever the reader already runs.++So every fact appears as an `rdf:Statement` carrying `schema:validFrom` / `schema:validThrough` (world time), `prov:generatedAtTime` / `prov:invalidatedAtTime` (record time), its confidence, and its evidence. **Standard terms wherever they exist**: PROV-O's `invalidatedAtTime` means exactly what our recording axis means, and reaching for a custom term there would hide a familiar concept behind a private name. Three things have no standard spelling and get a minted one: `confidence`, `derived`, and the model's original wording for a predicate the ontology never accepted.++Facts **currently held and currently valid** are additionally written as the plain triple. A consumer that ignores reification then gets a correct present-tense graph rather than an assertion that Zhang San still runs a project he handed over in 2024. Everything else — closed intervals, retracted rows, corrections — is in the file exactly once, as a statement, where the dates are impossible to miss.++## Lineage is PROV-O because that is what PROV-O is++Each statement is `prov:wasDerivedFrom` the documents its evidence chunks belong to, and carries the quoted sentence. Documents are `prov:Entity` with their title and the source key they arrived under. Derived facts ([0002](0002-reasoning-engine.md)) are `prov:wasGeneratedBy` the rule that produced them, with `prov:used` on each premise statement, so a reader can walk from a conclusion to the sentences underneath it without our API — which is the sentence in the README that this record exists to make true.++One of the five built-in packs is PROV-O, so a base that has it loaded already knows these terms.++## What is not here++- **A SPARQL endpoint.** The escape hatch over an in-memory Oxigraph projection was the original plan and stays a later cut. Someone who asked for "the reasoning behind this decision" wants a file they can keep; a query endpoint is the second thing they ask for, not the first.+- **Import of our own export.** The export is not a backup format, and reading it back would need entity resolution to be told "these IRIs are already resolved". Nothing stops it later; nothing depends on it now.+- **A button.** The API is the deliverable; where the download lives in the interface is a separate cut.